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 "X86TargetMachine.h"
19 #include "llvm/CallingConv.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/Function.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/ADT/BitVector.h"
26 #include "llvm/ADT/VectorExtras.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/PseudoSourceValue.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/Support/CommandLine.h"
42 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
44 // Forward declarations.
45 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
48 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
49 : TargetLowering(TM) {
50 Subtarget = &TM.getSubtarget<X86Subtarget>();
51 X86ScalarSSEf64 = Subtarget->hasSSE2();
52 X86ScalarSSEf32 = Subtarget->hasSSE1();
53 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
55 RegInfo = TM.getRegisterInfo();
58 // Set up the TargetLowering object.
60 // X86 is weird, it always uses i8 for shift amounts and setcc results.
61 setShiftAmountType(MVT::i8);
62 setBooleanContents(ZeroOrOneBooleanContent);
63 setSchedulingPreference(SchedulingForRegPressure);
64 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
65 setStackPointerRegisterToSaveRestore(X86StackPtr);
67 if (Subtarget->isTargetDarwin()) {
68 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
69 setUseUnderscoreSetJmp(false);
70 setUseUnderscoreLongJmp(false);
71 } else if (Subtarget->isTargetMingw()) {
72 // MS runtime is weird: it exports _setjmp, but longjmp!
73 setUseUnderscoreSetJmp(true);
74 setUseUnderscoreLongJmp(false);
76 setUseUnderscoreSetJmp(true);
77 setUseUnderscoreLongJmp(true);
80 // Set up the register classes.
81 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
82 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
83 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
84 if (Subtarget->is64Bit())
85 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
87 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
89 // We don't accept any truncstore of integer registers.
90 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
91 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
92 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
93 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
94 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
95 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
97 // SETOEQ and SETUNE require checking two conditions.
98 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
99 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
100 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
101 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
102 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
103 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
105 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
107 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
108 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
109 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
111 if (Subtarget->is64Bit()) {
112 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
113 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
114 } else if (!UseSoftFloat) {
115 if (X86ScalarSSEf64) {
116 // We have an impenetrably clever algorithm for ui64->double only.
117 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
119 // We have an algorithm for SSE2, and we turn this into a 64-bit
120 // FILD for other targets.
121 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
124 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
126 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
127 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
129 if (!UseSoftFloat && !NoImplicitFloat) {
130 // SSE has no i16 to fp conversion, only i32
131 if (X86ScalarSSEf32) {
132 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
133 // f32 and f64 cases are Legal, f80 case is not
134 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
136 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
137 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
140 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
141 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
144 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
145 // are Legal, f80 is custom lowered.
146 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
147 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
149 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
151 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
152 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
154 if (X86ScalarSSEf32) {
155 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
156 // f32 and f64 cases are Legal, f80 case is not
157 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
159 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
160 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
163 // Handle FP_TO_UINT by promoting the destination to a larger signed
165 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
166 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
167 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
169 if (Subtarget->is64Bit()) {
170 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
171 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
172 } else if (!UseSoftFloat) {
173 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
174 // Expand FP_TO_UINT into a select.
175 // FIXME: We would like to use a Custom expander here eventually to do
176 // the optimal thing for SSE vs. the default expansion in the legalizer.
177 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
179 // With SSE3 we can use fisttpll to convert to a signed i64; without
180 // SSE, we're stuck with a fistpll.
181 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
184 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
185 if (!X86ScalarSSEf64) {
186 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
187 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
190 // Scalar integer divide and remainder are lowered to use operations that
191 // produce two results, to match the available instructions. This exposes
192 // the two-result form to trivial CSE, which is able to combine x/y and x%y
193 // into a single instruction.
195 // Scalar integer multiply-high is also lowered to use two-result
196 // operations, to match the available instructions. However, plain multiply
197 // (low) operations are left as Legal, as there are single-result
198 // instructions for this in x86. Using the two-result multiply instructions
199 // when both high and low results are needed must be arranged by dagcombine.
200 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
201 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
202 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
203 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
204 setOperationAction(ISD::SREM , MVT::i8 , Expand);
205 setOperationAction(ISD::UREM , MVT::i8 , Expand);
206 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
207 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
208 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
209 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
210 setOperationAction(ISD::SREM , MVT::i16 , Expand);
211 setOperationAction(ISD::UREM , MVT::i16 , Expand);
212 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
213 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
214 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
215 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
216 setOperationAction(ISD::SREM , MVT::i32 , Expand);
217 setOperationAction(ISD::UREM , MVT::i32 , Expand);
218 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
219 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
220 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
221 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
222 setOperationAction(ISD::SREM , MVT::i64 , Expand);
223 setOperationAction(ISD::UREM , MVT::i64 , Expand);
225 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
226 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
227 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
228 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
229 if (Subtarget->is64Bit())
230 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
231 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
232 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
233 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
234 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
235 setOperationAction(ISD::FREM , MVT::f32 , Expand);
236 setOperationAction(ISD::FREM , MVT::f64 , Expand);
237 setOperationAction(ISD::FREM , MVT::f80 , Expand);
238 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
240 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
241 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
242 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
243 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
244 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
245 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
246 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
247 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
248 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
249 if (Subtarget->is64Bit()) {
250 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
251 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
252 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
255 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
256 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
258 // These should be promoted to a larger select which is supported.
259 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
260 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
261 // X86 wants to expand cmov itself.
262 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
263 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
264 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
265 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
266 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
267 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
268 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
269 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
270 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
271 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
272 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
273 if (Subtarget->is64Bit()) {
274 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
275 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
277 // X86 ret instruction may pop stack.
278 setOperationAction(ISD::RET , MVT::Other, Custom);
279 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
282 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
283 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
284 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
285 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
286 if (Subtarget->is64Bit())
287 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
288 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
289 if (Subtarget->is64Bit()) {
290 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
291 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
292 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
293 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
295 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
296 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
297 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
298 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
299 if (Subtarget->is64Bit()) {
300 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
301 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
302 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
305 if (Subtarget->hasSSE1())
306 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
308 if (!Subtarget->hasSSE2())
309 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
311 // Expand certain atomics
312 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
313 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
314 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
315 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
317 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
318 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
319 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
320 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
322 if (!Subtarget->is64Bit()) {
323 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
324 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
325 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
326 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
327 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
328 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
329 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
332 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
333 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
334 // FIXME - use subtarget debug flags
335 if (!Subtarget->isTargetDarwin() &&
336 !Subtarget->isTargetELF() &&
337 !Subtarget->isTargetCygMing()) {
338 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
339 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
342 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
343 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
344 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
345 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
346 if (Subtarget->is64Bit()) {
347 setExceptionPointerRegister(X86::RAX);
348 setExceptionSelectorRegister(X86::RDX);
350 setExceptionPointerRegister(X86::EAX);
351 setExceptionSelectorRegister(X86::EDX);
353 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
354 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
356 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
358 setOperationAction(ISD::TRAP, MVT::Other, Legal);
360 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
361 setOperationAction(ISD::VASTART , MVT::Other, Custom);
362 setOperationAction(ISD::VAEND , MVT::Other, Expand);
363 if (Subtarget->is64Bit()) {
364 setOperationAction(ISD::VAARG , MVT::Other, Custom);
365 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
367 setOperationAction(ISD::VAARG , MVT::Other, Expand);
368 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
371 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
372 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
373 if (Subtarget->is64Bit())
374 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
375 if (Subtarget->isTargetCygMing())
376 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
378 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
380 if (!UseSoftFloat && X86ScalarSSEf64) {
381 // f32 and f64 use SSE.
382 // Set up the FP register classes.
383 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
384 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
386 // Use ANDPD to simulate FABS.
387 setOperationAction(ISD::FABS , MVT::f64, Custom);
388 setOperationAction(ISD::FABS , MVT::f32, Custom);
390 // Use XORP to simulate FNEG.
391 setOperationAction(ISD::FNEG , MVT::f64, Custom);
392 setOperationAction(ISD::FNEG , MVT::f32, Custom);
394 // Use ANDPD and ORPD to simulate FCOPYSIGN.
395 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
396 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
398 // We don't support sin/cos/fmod
399 setOperationAction(ISD::FSIN , MVT::f64, Expand);
400 setOperationAction(ISD::FCOS , MVT::f64, Expand);
401 setOperationAction(ISD::FSIN , MVT::f32, Expand);
402 setOperationAction(ISD::FCOS , MVT::f32, Expand);
404 // Expand FP immediates into loads from the stack, except for the special
406 addLegalFPImmediate(APFloat(+0.0)); // xorpd
407 addLegalFPImmediate(APFloat(+0.0f)); // xorps
408 } else if (!UseSoftFloat && X86ScalarSSEf32) {
409 // Use SSE for f32, x87 for f64.
410 // Set up the FP register classes.
411 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
412 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
414 // Use ANDPS to simulate FABS.
415 setOperationAction(ISD::FABS , MVT::f32, Custom);
417 // Use XORP to simulate FNEG.
418 setOperationAction(ISD::FNEG , MVT::f32, Custom);
420 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
422 // Use ANDPS and ORPS to simulate FCOPYSIGN.
423 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
424 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
426 // We don't support sin/cos/fmod
427 setOperationAction(ISD::FSIN , MVT::f32, Expand);
428 setOperationAction(ISD::FCOS , MVT::f32, Expand);
430 // Special cases we handle for FP constants.
431 addLegalFPImmediate(APFloat(+0.0f)); // xorps
432 addLegalFPImmediate(APFloat(+0.0)); // FLD0
433 addLegalFPImmediate(APFloat(+1.0)); // FLD1
434 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
435 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
438 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
439 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
441 } else if (!UseSoftFloat) {
442 // f32 and f64 in x87.
443 // Set up the FP register classes.
444 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
445 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
447 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
448 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
449 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
450 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
453 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
454 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
456 addLegalFPImmediate(APFloat(+0.0)); // FLD0
457 addLegalFPImmediate(APFloat(+1.0)); // FLD1
458 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
459 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
460 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
461 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
462 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
463 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
466 // Long double always uses X87.
468 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
469 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
470 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
473 APFloat TmpFlt(+0.0);
474 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
476 addLegalFPImmediate(TmpFlt); // FLD0
478 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
479 APFloat TmpFlt2(+1.0);
480 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
482 addLegalFPImmediate(TmpFlt2); // FLD1
483 TmpFlt2.changeSign();
484 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
488 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
489 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
493 // Always use a library call for pow.
494 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
495 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
496 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
498 setOperationAction(ISD::FLOG, MVT::f80, Expand);
499 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
500 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
501 setOperationAction(ISD::FEXP, MVT::f80, Expand);
502 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
504 // First set operation action for all vector types to either promote
505 // (for widening) or expand (for scalarization). Then we will selectively
506 // turn on ones that can be effectively codegen'd.
507 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
508 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
509 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
510 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
511 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
512 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
513 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
514 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
515 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
516 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
517 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
518 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
519 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
520 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
521 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
522 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
523 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
524 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
525 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
526 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
527 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
528 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
529 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
530 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
531 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
532 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
533 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
534 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
535 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
536 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
537 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
538 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
539 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
555 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
556 // with -msoft-float, disable use of MMX as well.
557 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
558 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
559 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
560 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
561 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
562 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
564 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
565 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
566 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
567 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
569 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
570 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
571 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
572 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
574 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
575 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
577 setOperationAction(ISD::AND, MVT::v8i8, Promote);
578 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
579 setOperationAction(ISD::AND, MVT::v4i16, Promote);
580 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
581 setOperationAction(ISD::AND, MVT::v2i32, Promote);
582 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
583 setOperationAction(ISD::AND, MVT::v1i64, Legal);
585 setOperationAction(ISD::OR, MVT::v8i8, Promote);
586 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
587 setOperationAction(ISD::OR, MVT::v4i16, Promote);
588 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
589 setOperationAction(ISD::OR, MVT::v2i32, Promote);
590 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
591 setOperationAction(ISD::OR, MVT::v1i64, Legal);
593 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
594 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
595 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
596 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
597 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
598 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
599 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
601 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
602 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
603 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
604 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
605 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
606 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
607 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
608 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
609 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
611 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
612 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
613 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
614 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
615 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
617 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
618 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
619 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
620 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
622 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
623 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
624 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
625 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
627 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
629 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
630 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
631 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
632 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
633 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
634 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
637 if (!UseSoftFloat && Subtarget->hasSSE1()) {
638 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
640 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
641 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
642 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
643 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
644 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
645 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
646 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
647 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
648 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
649 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
650 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
651 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
654 if (!UseSoftFloat && Subtarget->hasSSE2()) {
655 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
657 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
658 // registers cannot be used even for integer operations.
659 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
660 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
661 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
662 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
664 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
665 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
666 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
667 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
668 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
669 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
670 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
671 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
672 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
673 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
674 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
675 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
676 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
677 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
678 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
679 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
681 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
682 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
683 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
684 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
686 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
687 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
688 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
689 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
690 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
692 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
693 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
694 MVT VT = (MVT::SimpleValueType)i;
695 // Do not attempt to custom lower non-power-of-2 vectors
696 if (!isPowerOf2_32(VT.getVectorNumElements()))
698 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
699 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
700 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
703 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
704 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
705 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
706 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
707 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
708 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
710 if (Subtarget->is64Bit()) {
711 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
712 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
715 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
716 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
717 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
718 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
719 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
720 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
721 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
722 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
723 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
724 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
725 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
726 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
729 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
731 // Custom lower v2i64 and v2f64 selects.
732 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
733 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
734 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
735 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
739 if (Subtarget->hasSSE41()) {
740 // FIXME: Do we need to handle scalar-to-vector here?
741 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
743 // i8 and i16 vectors are custom , because the source register and source
744 // source memory operand types are not the same width. f32 vectors are
745 // custom since the immediate controlling the insert encodes additional
747 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
748 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
749 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
750 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
752 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
753 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
754 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
755 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
757 if (Subtarget->is64Bit()) {
758 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
759 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
763 if (Subtarget->hasSSE42()) {
764 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
767 // We want to custom lower some of our intrinsics.
768 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
770 // Add/Sub/Mul with overflow operations are custom lowered.
771 setOperationAction(ISD::SADDO, MVT::i32, Custom);
772 setOperationAction(ISD::SADDO, MVT::i64, Custom);
773 setOperationAction(ISD::UADDO, MVT::i32, Custom);
774 setOperationAction(ISD::UADDO, MVT::i64, Custom);
775 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
776 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
777 setOperationAction(ISD::USUBO, MVT::i32, Custom);
778 setOperationAction(ISD::USUBO, MVT::i64, Custom);
779 setOperationAction(ISD::SMULO, MVT::i32, Custom);
780 setOperationAction(ISD::SMULO, MVT::i64, Custom);
781 setOperationAction(ISD::UMULO, MVT::i32, Custom);
782 setOperationAction(ISD::UMULO, MVT::i64, Custom);
784 if (!Subtarget->is64Bit()) {
785 // These libcalls are not available in 32-bit.
786 setLibcallName(RTLIB::SHL_I128, 0);
787 setLibcallName(RTLIB::SRL_I128, 0);
788 setLibcallName(RTLIB::SRA_I128, 0);
791 // We have target-specific dag combine patterns for the following nodes:
792 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
793 setTargetDAGCombine(ISD::BUILD_VECTOR);
794 setTargetDAGCombine(ISD::SELECT);
795 setTargetDAGCombine(ISD::SHL);
796 setTargetDAGCombine(ISD::SRA);
797 setTargetDAGCombine(ISD::SRL);
798 setTargetDAGCombine(ISD::STORE);
799 if (Subtarget->is64Bit())
800 setTargetDAGCombine(ISD::MUL);
802 computeRegisterProperties();
804 // FIXME: These should be based on subtarget info. Plus, the values should
805 // be smaller when we are in optimizing for size mode.
806 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
807 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
808 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
809 allowUnalignedMemoryAccesses = true; // x86 supports it!
810 setPrefLoopAlignment(16);
811 benefitFromCodePlacementOpt = true;
815 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
820 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
821 /// the desired ByVal argument alignment.
822 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
825 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
826 if (VTy->getBitWidth() == 128)
828 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
829 unsigned EltAlign = 0;
830 getMaxByValAlign(ATy->getElementType(), EltAlign);
831 if (EltAlign > MaxAlign)
833 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
834 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
835 unsigned EltAlign = 0;
836 getMaxByValAlign(STy->getElementType(i), EltAlign);
837 if (EltAlign > MaxAlign)
846 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
847 /// function arguments in the caller parameter area. For X86, aggregates
848 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
849 /// are at 4-byte boundaries.
850 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
851 if (Subtarget->is64Bit()) {
852 // Max of 8 and alignment of type.
853 unsigned TyAlign = TD->getABITypeAlignment(Ty);
860 if (Subtarget->hasSSE1())
861 getMaxByValAlign(Ty, Align);
865 /// getOptimalMemOpType - Returns the target specific optimal type for load
866 /// and store operations as a result of memset, memcpy, and memmove
867 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
870 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
871 bool isSrcConst, bool isSrcStr) const {
872 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
873 // linux. This is because the stack realignment code can't handle certain
874 // cases like PR2962. This should be removed when PR2962 is fixed.
875 if (!NoImplicitFloat && Subtarget->getStackAlignment() >= 16) {
876 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
878 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
881 if (Subtarget->is64Bit() && Size >= 8)
886 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
888 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
889 SelectionDAG &DAG) const {
890 if (usesGlobalOffsetTable())
891 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
892 if (!Subtarget->isPICStyleRIPRel())
893 // This doesn't have DebugLoc associated with it, but is not really the
894 // same as a Register.
895 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
900 //===----------------------------------------------------------------------===//
901 // Return Value Calling Convention Implementation
902 //===----------------------------------------------------------------------===//
904 #include "X86GenCallingConv.inc"
906 /// LowerRET - Lower an ISD::RET node.
907 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
908 DebugLoc dl = Op.getDebugLoc();
909 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
911 SmallVector<CCValAssign, 16> RVLocs;
912 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
913 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
914 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
915 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
917 // If this is the first return lowered for this function, add the regs to the
918 // liveout set for the function.
919 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
920 for (unsigned i = 0; i != RVLocs.size(); ++i)
921 if (RVLocs[i].isRegLoc())
922 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
924 SDValue Chain = Op.getOperand(0);
926 // Handle tail call return.
927 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
928 if (Chain.getOpcode() == X86ISD::TAILCALL) {
929 SDValue TailCall = Chain;
930 SDValue TargetAddress = TailCall.getOperand(1);
931 SDValue StackAdjustment = TailCall.getOperand(2);
932 assert(((TargetAddress.getOpcode() == ISD::Register &&
933 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
934 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
935 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
936 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
937 "Expecting an global address, external symbol, or register");
938 assert(StackAdjustment.getOpcode() == ISD::Constant &&
939 "Expecting a const value");
941 SmallVector<SDValue,8> Operands;
942 Operands.push_back(Chain.getOperand(0));
943 Operands.push_back(TargetAddress);
944 Operands.push_back(StackAdjustment);
945 // Copy registers used by the call. Last operand is a flag so it is not
947 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
948 Operands.push_back(Chain.getOperand(i));
950 return DAG.getNode(X86ISD::TC_RETURN, dl, MVT::Other, &Operands[0],
957 SmallVector<SDValue, 6> RetOps;
958 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
959 // Operand #1 = Bytes To Pop
960 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
962 // Copy the result values into the output registers.
963 for (unsigned i = 0; i != RVLocs.size(); ++i) {
964 CCValAssign &VA = RVLocs[i];
965 assert(VA.isRegLoc() && "Can only return in registers!");
966 SDValue ValToCopy = Op.getOperand(i*2+1);
968 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
969 // the RET instruction and handled by the FP Stackifier.
970 if (VA.getLocReg() == X86::ST0 ||
971 VA.getLocReg() == X86::ST1) {
972 // If this is a copy from an xmm register to ST(0), use an FPExtend to
973 // change the value to the FP stack register class.
974 if (isScalarFPTypeInSSEReg(VA.getValVT()))
975 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
976 RetOps.push_back(ValToCopy);
977 // Don't emit a copytoreg.
981 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
982 // which is returned in RAX / RDX.
983 if (Subtarget->is64Bit()) {
984 MVT ValVT = ValToCopy.getValueType();
985 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
986 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
987 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
988 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
992 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
993 Flag = Chain.getValue(1);
996 // The x86-64 ABI for returning structs by value requires that we copy
997 // the sret argument into %rax for the return. We saved the argument into
998 // a virtual register in the entry block, so now we copy the value out
1000 if (Subtarget->is64Bit() &&
1001 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1002 MachineFunction &MF = DAG.getMachineFunction();
1003 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1004 unsigned Reg = FuncInfo->getSRetReturnReg();
1006 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1007 FuncInfo->setSRetReturnReg(Reg);
1009 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1011 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1012 Flag = Chain.getValue(1);
1015 RetOps[0] = Chain; // Update chain.
1017 // Add the flag if we have it.
1019 RetOps.push_back(Flag);
1021 return DAG.getNode(X86ISD::RET_FLAG, dl,
1022 MVT::Other, &RetOps[0], RetOps.size());
1026 /// LowerCallResult - Lower the result values of an ISD::CALL into the
1027 /// appropriate copies out of appropriate physical registers. This assumes that
1028 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1029 /// being lowered. The returns a SDNode with the same number of values as the
1031 SDNode *X86TargetLowering::
1032 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1033 unsigned CallingConv, SelectionDAG &DAG) {
1035 DebugLoc dl = TheCall->getDebugLoc();
1036 // Assign locations to each value returned by this call.
1037 SmallVector<CCValAssign, 16> RVLocs;
1038 bool isVarArg = TheCall->isVarArg();
1039 bool Is64Bit = Subtarget->is64Bit();
1040 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1041 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1043 SmallVector<SDValue, 8> ResultVals;
1045 // Copy all of the result registers out of their specified physreg.
1046 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1047 CCValAssign &VA = RVLocs[i];
1048 MVT CopyVT = VA.getValVT();
1050 // If this is x86-64, and we disabled SSE, we can't return FP values
1051 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1052 ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
1053 cerr << "SSE register return with SSE disabled\n";
1057 // If this is a call to a function that returns an fp value on the floating
1058 // point stack, but where we prefer to use the value in xmm registers, copy
1059 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1060 if ((VA.getLocReg() == X86::ST0 ||
1061 VA.getLocReg() == X86::ST1) &&
1062 isScalarFPTypeInSSEReg(VA.getValVT())) {
1067 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1068 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1069 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1070 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1071 MVT::v2i64, InFlag).getValue(1);
1072 Val = Chain.getValue(0);
1073 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1074 Val, DAG.getConstant(0, MVT::i64));
1076 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1077 MVT::i64, InFlag).getValue(1);
1078 Val = Chain.getValue(0);
1080 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1082 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1083 CopyVT, InFlag).getValue(1);
1084 Val = Chain.getValue(0);
1086 InFlag = Chain.getValue(2);
1088 if (CopyVT != VA.getValVT()) {
1089 // Round the F80 the right size, which also moves to the appropriate xmm
1091 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1092 // This truncation won't change the value.
1093 DAG.getIntPtrConstant(1));
1096 ResultVals.push_back(Val);
1099 // Merge everything together with a MERGE_VALUES node.
1100 ResultVals.push_back(Chain);
1101 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
1102 &ResultVals[0], ResultVals.size()).getNode();
1106 //===----------------------------------------------------------------------===//
1107 // C & StdCall & Fast Calling Convention implementation
1108 //===----------------------------------------------------------------------===//
1109 // StdCall calling convention seems to be standard for many Windows' API
1110 // routines and around. It differs from C calling convention just a little:
1111 // callee should clean up the stack, not caller. Symbols should be also
1112 // decorated in some fancy way :) It doesn't support any vector arguments.
1113 // For info on fast calling convention see Fast Calling Convention (tail call)
1114 // implementation LowerX86_32FastCCCallTo.
1116 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1118 static bool CallIsStructReturn(CallSDNode *TheCall) {
1119 unsigned NumOps = TheCall->getNumArgs();
1123 return TheCall->getArgFlags(0).isSRet();
1126 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1127 /// return semantics.
1128 static bool ArgsAreStructReturn(SDValue Op) {
1129 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1133 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1136 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1137 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1139 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1143 switch (CallingConv) {
1146 case CallingConv::X86_StdCall:
1147 return !Subtarget->is64Bit();
1148 case CallingConv::X86_FastCall:
1149 return !Subtarget->is64Bit();
1150 case CallingConv::Fast:
1151 return PerformTailCallOpt;
1155 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1156 /// given CallingConvention value.
1157 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1158 if (Subtarget->is64Bit()) {
1159 if (Subtarget->isTargetWin64())
1160 return CC_X86_Win64_C;
1161 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1162 return CC_X86_64_TailCall;
1167 if (CC == CallingConv::X86_FastCall)
1168 return CC_X86_32_FastCall;
1169 else if (CC == CallingConv::Fast)
1170 return CC_X86_32_FastCC;
1175 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1176 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1178 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1179 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1180 if (CC == CallingConv::X86_FastCall)
1182 else if (CC == CallingConv::X86_StdCall)
1188 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1189 /// in a register before calling.
1190 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1191 return !IsTailCall && !Is64Bit &&
1192 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1193 Subtarget->isPICStyleGOT();
1196 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1197 /// address to be loaded in a register.
1199 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1200 return !Is64Bit && IsTailCall &&
1201 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1202 Subtarget->isPICStyleGOT();
1205 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1206 /// by "Src" to address "Dst" with size and alignment information specified by
1207 /// the specific parameter attribute. The copy will be passed as a byval
1208 /// function parameter.
1210 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1211 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1213 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1214 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1215 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1218 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1219 const CCValAssign &VA,
1220 MachineFrameInfo *MFI,
1222 SDValue Root, unsigned i) {
1223 // Create the nodes corresponding to a load from this parameter slot.
1224 ISD::ArgFlagsTy Flags =
1225 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1226 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1227 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1229 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1230 // changed with more analysis.
1231 // In case of tail call optimization mark all arguments mutable. Since they
1232 // could be overwritten by lowering of arguments in case of a tail call.
1233 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1234 VA.getLocMemOffset(), isImmutable);
1235 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1236 if (Flags.isByVal())
1238 return DAG.getLoad(VA.getValVT(), Op.getDebugLoc(), Root, FIN,
1239 PseudoSourceValue::getFixedStack(FI), 0);
1243 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1244 MachineFunction &MF = DAG.getMachineFunction();
1245 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1246 DebugLoc dl = Op.getDebugLoc();
1248 const Function* Fn = MF.getFunction();
1249 if (Fn->hasExternalLinkage() &&
1250 Subtarget->isTargetCygMing() &&
1251 Fn->getName() == "main")
1252 FuncInfo->setForceFramePointer(true);
1254 // Decorate the function name.
1255 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1257 MachineFrameInfo *MFI = MF.getFrameInfo();
1258 SDValue Root = Op.getOperand(0);
1259 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1260 unsigned CC = MF.getFunction()->getCallingConv();
1261 bool Is64Bit = Subtarget->is64Bit();
1262 bool IsWin64 = Subtarget->isTargetWin64();
1264 assert(!(isVarArg && CC == CallingConv::Fast) &&
1265 "Var args not supported with calling convention fastcc");
1267 // Assign locations to all of the incoming arguments.
1268 SmallVector<CCValAssign, 16> ArgLocs;
1269 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1270 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1272 SmallVector<SDValue, 8> ArgValues;
1273 unsigned LastVal = ~0U;
1274 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1275 CCValAssign &VA = ArgLocs[i];
1276 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1278 assert(VA.getValNo() != LastVal &&
1279 "Don't support value assigned to multiple locs yet");
1280 LastVal = VA.getValNo();
1282 if (VA.isRegLoc()) {
1283 MVT RegVT = VA.getLocVT();
1284 TargetRegisterClass *RC = NULL;
1285 if (RegVT == MVT::i32)
1286 RC = X86::GR32RegisterClass;
1287 else if (Is64Bit && RegVT == MVT::i64)
1288 RC = X86::GR64RegisterClass;
1289 else if (RegVT == MVT::f32)
1290 RC = X86::FR32RegisterClass;
1291 else if (RegVT == MVT::f64)
1292 RC = X86::FR64RegisterClass;
1293 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1294 RC = X86::VR128RegisterClass;
1295 else if (RegVT.isVector()) {
1296 assert(RegVT.getSizeInBits() == 64);
1298 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1300 // Darwin calling convention passes MMX values in either GPRs or
1301 // XMMs in x86-64. Other targets pass them in memory.
1302 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1303 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1306 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1311 assert(0 && "Unknown argument type!");
1314 unsigned Reg = DAG.getMachineFunction().addLiveIn(VA.getLocReg(), RC);
1315 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
1317 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1318 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1320 if (VA.getLocInfo() == CCValAssign::SExt)
1321 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1322 DAG.getValueType(VA.getValVT()));
1323 else if (VA.getLocInfo() == CCValAssign::ZExt)
1324 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1325 DAG.getValueType(VA.getValVT()));
1327 if (VA.getLocInfo() != CCValAssign::Full)
1328 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1330 // Handle MMX values passed in GPRs.
1331 if (Is64Bit && RegVT != VA.getLocVT()) {
1332 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1333 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1334 else if (RC == X86::VR128RegisterClass) {
1335 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1336 ArgValue, DAG.getConstant(0, MVT::i64));
1337 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1341 ArgValues.push_back(ArgValue);
1343 assert(VA.isMemLoc());
1344 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1348 // The x86-64 ABI for returning structs by value requires that we copy
1349 // the sret argument into %rax for the return. Save the argument into
1350 // a virtual register so that we can access it from the return points.
1351 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1352 MachineFunction &MF = DAG.getMachineFunction();
1353 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1354 unsigned Reg = FuncInfo->getSRetReturnReg();
1356 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1357 FuncInfo->setSRetReturnReg(Reg);
1359 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, ArgValues[0]);
1360 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1363 unsigned StackSize = CCInfo.getNextStackOffset();
1364 // align stack specially for tail calls
1365 if (PerformTailCallOpt && CC == CallingConv::Fast)
1366 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1368 // If the function takes variable number of arguments, make a frame index for
1369 // the start of the first vararg value... for expansion of llvm.va_start.
1371 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1372 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1375 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1377 // FIXME: We should really autogenerate these arrays
1378 static const unsigned GPR64ArgRegsWin64[] = {
1379 X86::RCX, X86::RDX, X86::R8, X86::R9
1381 static const unsigned XMMArgRegsWin64[] = {
1382 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1384 static const unsigned GPR64ArgRegs64Bit[] = {
1385 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1387 static const unsigned XMMArgRegs64Bit[] = {
1388 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1389 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1391 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1394 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1395 GPR64ArgRegs = GPR64ArgRegsWin64;
1396 XMMArgRegs = XMMArgRegsWin64;
1398 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1399 GPR64ArgRegs = GPR64ArgRegs64Bit;
1400 XMMArgRegs = XMMArgRegs64Bit;
1402 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1404 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1407 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1408 "SSE register cannot be used when SSE is disabled!");
1409 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloat) &&
1410 "SSE register cannot be used when SSE is disabled!");
1411 if (UseSoftFloat || NoImplicitFloat || !Subtarget->hasSSE1())
1412 // Kernel mode asks for SSE to be disabled, so don't push them
1414 TotalNumXMMRegs = 0;
1416 // For X86-64, if there are vararg parameters that are passed via
1417 // registers, then we must store them to their spots on the stack so they
1418 // may be loaded by deferencing the result of va_next.
1419 VarArgsGPOffset = NumIntRegs * 8;
1420 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1421 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1422 TotalNumXMMRegs * 16, 16);
1424 // Store the integer parameter registers.
1425 SmallVector<SDValue, 8> MemOps;
1426 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1427 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1428 DAG.getIntPtrConstant(VarArgsGPOffset));
1429 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1430 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1431 X86::GR64RegisterClass);
1432 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
1434 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1435 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1436 MemOps.push_back(Store);
1437 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1438 DAG.getIntPtrConstant(8));
1441 // Now store the XMM (fp + vector) parameter registers.
1442 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1443 DAG.getIntPtrConstant(VarArgsFPOffset));
1444 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1445 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1446 X86::VR128RegisterClass);
1447 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::v4f32);
1449 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1450 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1451 MemOps.push_back(Store);
1452 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1453 DAG.getIntPtrConstant(16));
1455 if (!MemOps.empty())
1456 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1457 &MemOps[0], MemOps.size());
1461 ArgValues.push_back(Root);
1463 // Some CCs need callee pop.
1464 if (IsCalleePop(isVarArg, CC)) {
1465 BytesToPopOnReturn = StackSize; // Callee pops everything.
1466 BytesCallerReserves = 0;
1468 BytesToPopOnReturn = 0; // Callee pops nothing.
1469 // If this is an sret function, the return should pop the hidden pointer.
1470 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1471 BytesToPopOnReturn = 4;
1472 BytesCallerReserves = StackSize;
1476 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1477 if (CC == CallingConv::X86_FastCall)
1478 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1481 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1483 // Return the new list of results.
1484 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1485 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1489 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1490 const SDValue &StackPtr,
1491 const CCValAssign &VA,
1493 SDValue Arg, ISD::ArgFlagsTy Flags) {
1494 DebugLoc dl = TheCall->getDebugLoc();
1495 unsigned LocMemOffset = VA.getLocMemOffset();
1496 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1497 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1498 if (Flags.isByVal()) {
1499 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1501 return DAG.getStore(Chain, dl, Arg, PtrOff,
1502 PseudoSourceValue::getStack(), LocMemOffset);
1505 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1506 /// optimization is performed and it is required.
1508 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1509 SDValue &OutRetAddr,
1515 if (!IsTailCall || FPDiff==0) return Chain;
1517 // Adjust the Return address stack slot.
1518 MVT VT = getPointerTy();
1519 OutRetAddr = getReturnAddressFrameIndex(DAG);
1521 // Load the "old" Return address.
1522 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1523 return SDValue(OutRetAddr.getNode(), 1);
1526 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1527 /// optimization is performed and it is required (FPDiff!=0).
1529 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1530 SDValue Chain, SDValue RetAddrFrIdx,
1531 bool Is64Bit, int FPDiff, DebugLoc dl) {
1532 // Store the return address to the appropriate stack slot.
1533 if (!FPDiff) return Chain;
1534 // Calculate the new stack slot for the return address.
1535 int SlotSize = Is64Bit ? 8 : 4;
1536 int NewReturnAddrFI =
1537 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1538 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1539 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1540 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1541 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1545 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1546 MachineFunction &MF = DAG.getMachineFunction();
1547 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1548 SDValue Chain = TheCall->getChain();
1549 unsigned CC = TheCall->getCallingConv();
1550 bool isVarArg = TheCall->isVarArg();
1551 bool IsTailCall = TheCall->isTailCall() &&
1552 CC == CallingConv::Fast && PerformTailCallOpt;
1553 SDValue Callee = TheCall->getCallee();
1554 bool Is64Bit = Subtarget->is64Bit();
1555 bool IsStructRet = CallIsStructReturn(TheCall);
1556 DebugLoc dl = TheCall->getDebugLoc();
1558 assert(!(isVarArg && CC == CallingConv::Fast) &&
1559 "Var args not supported with calling convention fastcc");
1561 // Analyze operands of the call, assigning locations to each operand.
1562 SmallVector<CCValAssign, 16> ArgLocs;
1563 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1564 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1566 // Get a count of how many bytes are to be pushed on the stack.
1567 unsigned NumBytes = CCInfo.getNextStackOffset();
1568 if (PerformTailCallOpt && CC == CallingConv::Fast)
1569 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1573 // Lower arguments at fp - stackoffset + fpdiff.
1574 unsigned NumBytesCallerPushed =
1575 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1576 FPDiff = NumBytesCallerPushed - NumBytes;
1578 // Set the delta of movement of the returnaddr stackslot.
1579 // But only set if delta is greater than previous delta.
1580 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1581 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1584 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1586 SDValue RetAddrFrIdx;
1587 // Load return adress for tail calls.
1588 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1591 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1592 SmallVector<SDValue, 8> MemOpChains;
1595 // Walk the register/memloc assignments, inserting copies/loads. In the case
1596 // of tail call optimization arguments are handle later.
1597 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1598 CCValAssign &VA = ArgLocs[i];
1599 SDValue Arg = TheCall->getArg(i);
1600 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1601 bool isByVal = Flags.isByVal();
1603 // Promote the value if needed.
1604 switch (VA.getLocInfo()) {
1605 default: assert(0 && "Unknown loc info!");
1606 case CCValAssign::Full: break;
1607 case CCValAssign::SExt:
1608 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1610 case CCValAssign::ZExt:
1611 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1613 case CCValAssign::AExt:
1614 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1618 if (VA.isRegLoc()) {
1620 MVT RegVT = VA.getLocVT();
1621 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1622 switch (VA.getLocReg()) {
1625 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1627 // Special case: passing MMX values in GPR registers.
1628 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1631 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1632 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1633 // Special case: passing MMX values in XMM registers.
1634 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1635 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1636 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1641 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1643 if (!IsTailCall || (IsTailCall && isByVal)) {
1644 assert(VA.isMemLoc());
1645 if (StackPtr.getNode() == 0)
1646 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1648 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1649 Chain, Arg, Flags));
1654 if (!MemOpChains.empty())
1655 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1656 &MemOpChains[0], MemOpChains.size());
1658 // Build a sequence of copy-to-reg nodes chained together with token chain
1659 // and flag operands which copy the outgoing args into registers.
1661 // Tail call byval lowering might overwrite argument registers so in case of
1662 // tail call optimization the copies to registers are lowered later.
1664 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1665 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1666 RegsToPass[i].second, InFlag);
1667 InFlag = Chain.getValue(1);
1670 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1672 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1673 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1674 DAG.getNode(X86ISD::GlobalBaseReg,
1675 DebugLoc::getUnknownLoc(),
1678 InFlag = Chain.getValue(1);
1680 // If we are tail calling and generating PIC/GOT style code load the address
1681 // of the callee into ecx. The value in ecx is used as target of the tail
1682 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1683 // calls on PIC/GOT architectures. Normally we would just put the address of
1684 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1685 // restored (since ebx is callee saved) before jumping to the target@PLT.
1686 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1687 // Note: The actual moving to ecx is done further down.
1688 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1689 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1690 !G->getGlobal()->hasProtectedVisibility())
1691 Callee = LowerGlobalAddress(Callee, DAG);
1692 else if (isa<ExternalSymbolSDNode>(Callee))
1693 Callee = LowerExternalSymbol(Callee,DAG);
1696 if (Is64Bit && isVarArg) {
1697 // From AMD64 ABI document:
1698 // For calls that may call functions that use varargs or stdargs
1699 // (prototype-less calls or calls to functions containing ellipsis (...) in
1700 // the declaration) %al is used as hidden argument to specify the number
1701 // of SSE registers used. The contents of %al do not need to match exactly
1702 // the number of registers, but must be an ubound on the number of SSE
1703 // registers used and is in the range 0 - 8 inclusive.
1705 // FIXME: Verify this on Win64
1706 // Count the number of XMM registers allocated.
1707 static const unsigned XMMArgRegs[] = {
1708 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1709 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1711 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1712 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1713 && "SSE registers cannot be used when SSE is disabled");
1715 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1716 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1717 InFlag = Chain.getValue(1);
1721 // For tail calls lower the arguments to the 'real' stack slot.
1723 SmallVector<SDValue, 8> MemOpChains2;
1726 // Do not flag preceeding copytoreg stuff together with the following stuff.
1728 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1729 CCValAssign &VA = ArgLocs[i];
1730 if (!VA.isRegLoc()) {
1731 assert(VA.isMemLoc());
1732 SDValue Arg = TheCall->getArg(i);
1733 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1734 // Create frame index.
1735 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1736 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1737 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1738 FIN = DAG.getFrameIndex(FI, getPointerTy());
1740 if (Flags.isByVal()) {
1741 // Copy relative to framepointer.
1742 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1743 if (StackPtr.getNode() == 0)
1744 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1746 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1748 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1751 // Store relative to framepointer.
1752 MemOpChains2.push_back(
1753 DAG.getStore(Chain, dl, Arg, FIN,
1754 PseudoSourceValue::getFixedStack(FI), 0));
1759 if (!MemOpChains2.empty())
1760 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1761 &MemOpChains2[0], MemOpChains2.size());
1763 // Copy arguments to their registers.
1764 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1765 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1766 RegsToPass[i].second, InFlag);
1767 InFlag = Chain.getValue(1);
1771 // Store the return address to the appropriate stack slot.
1772 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1776 // If the callee is a GlobalAddress node (quite common, every direct call is)
1777 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1778 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1779 // We should use extra load for direct calls to dllimported functions in
1781 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1782 getTargetMachine(), true))
1783 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1785 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1786 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1787 } else if (IsTailCall) {
1788 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1790 Chain = DAG.getCopyToReg(Chain, dl,
1791 DAG.getRegister(Opc, getPointerTy()),
1793 Callee = DAG.getRegister(Opc, getPointerTy());
1794 // Add register as live out.
1795 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1798 // Returns a chain & a flag for retval copy to use.
1799 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1800 SmallVector<SDValue, 8> Ops;
1803 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1804 DAG.getIntPtrConstant(0, true), InFlag);
1805 InFlag = Chain.getValue(1);
1807 // Returns a chain & a flag for retval copy to use.
1808 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1812 Ops.push_back(Chain);
1813 Ops.push_back(Callee);
1816 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1818 // Add argument registers to the end of the list so that they are known live
1820 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1821 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1822 RegsToPass[i].second.getValueType()));
1824 // Add an implicit use GOT pointer in EBX.
1825 if (!IsTailCall && !Is64Bit &&
1826 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1827 Subtarget->isPICStyleGOT())
1828 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1830 // Add an implicit use of AL for x86 vararg functions.
1831 if (Is64Bit && isVarArg)
1832 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1834 if (InFlag.getNode())
1835 Ops.push_back(InFlag);
1838 assert(InFlag.getNode() &&
1839 "Flag must be set. Depend on flag being set in LowerRET");
1840 Chain = DAG.getNode(X86ISD::TAILCALL, dl,
1841 TheCall->getVTList(), &Ops[0], Ops.size());
1843 return SDValue(Chain.getNode(), Op.getResNo());
1846 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
1847 InFlag = Chain.getValue(1);
1849 // Create the CALLSEQ_END node.
1850 unsigned NumBytesForCalleeToPush;
1851 if (IsCalleePop(isVarArg, CC))
1852 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1853 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1854 // If this is is a call to a struct-return function, the callee
1855 // pops the hidden struct pointer, so we have to push it back.
1856 // This is common for Darwin/X86, Linux & Mingw32 targets.
1857 NumBytesForCalleeToPush = 4;
1859 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1861 // Returns a flag for retval copy to use.
1862 Chain = DAG.getCALLSEQ_END(Chain,
1863 DAG.getIntPtrConstant(NumBytes, true),
1864 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1867 InFlag = Chain.getValue(1);
1869 // Handle result values, copying them out of physregs into vregs that we
1871 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1876 //===----------------------------------------------------------------------===//
1877 // Fast Calling Convention (tail call) implementation
1878 //===----------------------------------------------------------------------===//
1880 // Like std call, callee cleans arguments, convention except that ECX is
1881 // reserved for storing the tail called function address. Only 2 registers are
1882 // free for argument passing (inreg). Tail call optimization is performed
1884 // * tailcallopt is enabled
1885 // * caller/callee are fastcc
1886 // On X86_64 architecture with GOT-style position independent code only local
1887 // (within module) calls are supported at the moment.
1888 // To keep the stack aligned according to platform abi the function
1889 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1890 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1891 // If a tail called function callee has more arguments than the caller the
1892 // caller needs to make sure that there is room to move the RETADDR to. This is
1893 // achieved by reserving an area the size of the argument delta right after the
1894 // original REtADDR, but before the saved framepointer or the spilled registers
1895 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1907 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1908 /// for a 16 byte align requirement.
1909 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1910 SelectionDAG& DAG) {
1911 MachineFunction &MF = DAG.getMachineFunction();
1912 const TargetMachine &TM = MF.getTarget();
1913 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1914 unsigned StackAlignment = TFI.getStackAlignment();
1915 uint64_t AlignMask = StackAlignment - 1;
1916 int64_t Offset = StackSize;
1917 uint64_t SlotSize = TD->getPointerSize();
1918 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1919 // Number smaller than 12 so just add the difference.
1920 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1922 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1923 Offset = ((~AlignMask) & Offset) + StackAlignment +
1924 (StackAlignment-SlotSize);
1929 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1930 /// following the call is a return. A function is eligible if caller/callee
1931 /// calling conventions match, currently only fastcc supports tail calls, and
1932 /// the function CALL is immediatly followed by a RET.
1933 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1935 SelectionDAG& DAG) const {
1936 if (!PerformTailCallOpt)
1939 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1940 MachineFunction &MF = DAG.getMachineFunction();
1941 unsigned CallerCC = MF.getFunction()->getCallingConv();
1942 unsigned CalleeCC= TheCall->getCallingConv();
1943 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1944 SDValue Callee = TheCall->getCallee();
1945 // On x86/32Bit PIC/GOT tail calls are supported.
1946 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1947 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1950 // Can only do local tail calls (in same module, hidden or protected) on
1951 // x86_64 PIC/GOT at the moment.
1952 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1953 return G->getGlobal()->hasHiddenVisibility()
1954 || G->getGlobal()->hasProtectedVisibility();
1962 X86TargetLowering::createFastISel(MachineFunction &mf,
1963 MachineModuleInfo *mmo,
1965 DenseMap<const Value *, unsigned> &vm,
1966 DenseMap<const BasicBlock *,
1967 MachineBasicBlock *> &bm,
1968 DenseMap<const AllocaInst *, int> &am
1970 , SmallSet<Instruction*, 8> &cil
1973 return X86::createFastISel(mf, mmo, dw, vm, bm, am
1981 //===----------------------------------------------------------------------===//
1982 // Other Lowering Hooks
1983 //===----------------------------------------------------------------------===//
1986 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1987 MachineFunction &MF = DAG.getMachineFunction();
1988 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1989 int ReturnAddrIndex = FuncInfo->getRAIndex();
1991 if (ReturnAddrIndex == 0) {
1992 // Set up a frame object for the return address.
1993 uint64_t SlotSize = TD->getPointerSize();
1994 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
1995 FuncInfo->setRAIndex(ReturnAddrIndex);
1998 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2002 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2003 /// specific condition code, returning the condition code and the LHS/RHS of the
2004 /// comparison to make.
2005 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2006 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2008 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2009 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2010 // X > -1 -> X == 0, jump !sign.
2011 RHS = DAG.getConstant(0, RHS.getValueType());
2012 return X86::COND_NS;
2013 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2014 // X < 0 -> X == 0, jump on sign.
2016 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2018 RHS = DAG.getConstant(0, RHS.getValueType());
2019 return X86::COND_LE;
2023 switch (SetCCOpcode) {
2024 default: assert(0 && "Invalid integer condition!");
2025 case ISD::SETEQ: return X86::COND_E;
2026 case ISD::SETGT: return X86::COND_G;
2027 case ISD::SETGE: return X86::COND_GE;
2028 case ISD::SETLT: return X86::COND_L;
2029 case ISD::SETLE: return X86::COND_LE;
2030 case ISD::SETNE: return X86::COND_NE;
2031 case ISD::SETULT: return X86::COND_B;
2032 case ISD::SETUGT: return X86::COND_A;
2033 case ISD::SETULE: return X86::COND_BE;
2034 case ISD::SETUGE: return X86::COND_AE;
2038 // First determine if it is required or is profitable to flip the operands.
2040 // If LHS is a foldable load, but RHS is not, flip the condition.
2041 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2042 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2043 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2044 std::swap(LHS, RHS);
2047 switch (SetCCOpcode) {
2053 std::swap(LHS, RHS);
2057 // On a floating point condition, the flags are set as follows:
2059 // 0 | 0 | 0 | X > Y
2060 // 0 | 0 | 1 | X < Y
2061 // 1 | 0 | 0 | X == Y
2062 // 1 | 1 | 1 | unordered
2063 switch (SetCCOpcode) {
2064 default: assert(0 && "Condcode should be pre-legalized away");
2066 case ISD::SETEQ: return X86::COND_E;
2067 case ISD::SETOLT: // flipped
2069 case ISD::SETGT: return X86::COND_A;
2070 case ISD::SETOLE: // flipped
2072 case ISD::SETGE: return X86::COND_AE;
2073 case ISD::SETUGT: // flipped
2075 case ISD::SETLT: return X86::COND_B;
2076 case ISD::SETUGE: // flipped
2078 case ISD::SETLE: return X86::COND_BE;
2080 case ISD::SETNE: return X86::COND_NE;
2081 case ISD::SETUO: return X86::COND_P;
2082 case ISD::SETO: return X86::COND_NP;
2086 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2087 /// code. Current x86 isa includes the following FP cmov instructions:
2088 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2089 static bool hasFPCMov(unsigned X86CC) {
2105 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2106 /// the specified range (L, H].
2107 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2108 return (Val < 0) || (Val >= Low && Val < Hi);
2111 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2112 /// specified value.
2113 static bool isUndefOrEqual(int Val, int CmpVal) {
2114 if (Val < 0 || Val == CmpVal)
2119 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2120 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2121 /// the second operand.
2122 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2123 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2124 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2125 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2126 return (Mask[0] < 2 && Mask[1] < 2);
2130 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2131 SmallVector<int, 8> M;
2133 return ::isPSHUFDMask(M, N->getValueType(0));
2136 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2137 /// is suitable for input to PSHUFHW.
2138 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2139 if (VT != MVT::v8i16)
2142 // Lower quadword copied in order or undef.
2143 for (int i = 0; i != 4; ++i)
2144 if (Mask[i] >= 0 && Mask[i] != i)
2147 // Upper quadword shuffled.
2148 for (int i = 4; i != 8; ++i)
2149 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2155 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2156 SmallVector<int, 8> M;
2158 return ::isPSHUFHWMask(M, N->getValueType(0));
2161 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2162 /// is suitable for input to PSHUFLW.
2163 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2164 if (VT != MVT::v8i16)
2167 // Upper quadword copied in order.
2168 for (int i = 4; i != 8; ++i)
2169 if (Mask[i] >= 0 && Mask[i] != i)
2172 // Lower quadword shuffled.
2173 for (int i = 0; i != 4; ++i)
2180 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2181 SmallVector<int, 8> M;
2183 return ::isPSHUFLWMask(M, N->getValueType(0));
2186 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2187 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2188 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2189 int NumElems = VT.getVectorNumElements();
2190 if (NumElems != 2 && NumElems != 4)
2193 int Half = NumElems / 2;
2194 for (int i = 0; i < Half; ++i)
2195 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2197 for (int i = Half; i < NumElems; ++i)
2198 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2204 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2205 SmallVector<int, 8> M;
2207 return ::isSHUFPMask(M, N->getValueType(0));
2210 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2211 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2212 /// half elements to come from vector 1 (which would equal the dest.) and
2213 /// the upper half to come from vector 2.
2214 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2215 int NumElems = VT.getVectorNumElements();
2217 if (NumElems != 2 && NumElems != 4)
2220 int Half = NumElems / 2;
2221 for (int i = 0; i < Half; ++i)
2222 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2224 for (int i = Half; i < NumElems; ++i)
2225 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2230 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2231 SmallVector<int, 8> M;
2233 return isCommutedSHUFPMask(M, N->getValueType(0));
2236 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2237 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2238 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2239 if (N->getValueType(0).getVectorNumElements() != 4)
2242 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2243 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2244 isUndefOrEqual(N->getMaskElt(1), 7) &&
2245 isUndefOrEqual(N->getMaskElt(2), 2) &&
2246 isUndefOrEqual(N->getMaskElt(3), 3);
2249 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2250 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2251 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2252 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2254 if (NumElems != 2 && NumElems != 4)
2257 for (unsigned i = 0; i < NumElems/2; ++i)
2258 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2261 for (unsigned i = NumElems/2; i < NumElems; ++i)
2262 if (!isUndefOrEqual(N->getMaskElt(i), i))
2268 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2269 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2271 bool X86::isMOVHPMask(ShuffleVectorSDNode *N) {
2272 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2274 if (NumElems != 2 && NumElems != 4)
2277 for (unsigned i = 0; i < NumElems/2; ++i)
2278 if (!isUndefOrEqual(N->getMaskElt(i), i))
2281 for (unsigned i = 0; i < NumElems/2; ++i)
2282 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2288 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2289 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2291 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2292 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2297 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2298 isUndefOrEqual(N->getMaskElt(1), 3) &&
2299 isUndefOrEqual(N->getMaskElt(2), 2) &&
2300 isUndefOrEqual(N->getMaskElt(3), 3);
2303 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2304 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2305 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2306 bool V2IsSplat = false) {
2307 int NumElts = VT.getVectorNumElements();
2308 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2311 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2313 int BitI1 = Mask[i+1];
2314 if (!isUndefOrEqual(BitI, j))
2317 if (!isUndefOrEqual(BitI1, NumElts))
2320 if (!isUndefOrEqual(BitI1, j + NumElts))
2327 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2328 SmallVector<int, 8> M;
2330 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2333 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2334 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2335 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, MVT VT,
2336 bool V2IsSplat = false) {
2337 int NumElts = VT.getVectorNumElements();
2338 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2341 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2343 int BitI1 = Mask[i+1];
2344 if (!isUndefOrEqual(BitI, j + NumElts/2))
2347 if (isUndefOrEqual(BitI1, NumElts))
2350 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2357 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2358 SmallVector<int, 8> M;
2360 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2363 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2364 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2366 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2367 int NumElems = VT.getVectorNumElements();
2368 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2371 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2373 int BitI1 = Mask[i+1];
2374 if (!isUndefOrEqual(BitI, j))
2376 if (!isUndefOrEqual(BitI1, j))
2382 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2383 SmallVector<int, 8> M;
2385 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2388 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2389 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2391 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2392 int NumElems = VT.getVectorNumElements();
2393 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2396 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2398 int BitI1 = Mask[i+1];
2399 if (!isUndefOrEqual(BitI, j))
2401 if (!isUndefOrEqual(BitI1, j))
2407 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2408 SmallVector<int, 8> M;
2410 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2413 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2414 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2415 /// MOVSD, and MOVD, i.e. setting the lowest element.
2416 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2417 int NumElts = VT.getVectorNumElements();
2418 if (NumElts != 2 && NumElts != 4)
2421 if (!isUndefOrEqual(Mask[0], NumElts))
2424 for (int i = 1; i < NumElts; ++i)
2425 if (!isUndefOrEqual(Mask[i], i))
2431 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2432 SmallVector<int, 8> M;
2434 return ::isMOVLMask(M, N->getValueType(0));
2437 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2438 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2439 /// element of vector 2 and the other elements to come from vector 1 in order.
2440 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2441 bool V2IsSplat = false, bool V2IsUndef = false) {
2442 int NumOps = VT.getVectorNumElements();
2443 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2446 if (!isUndefOrEqual(Mask[0], 0))
2449 for (int i = 1; i < NumOps; ++i)
2450 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2451 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2452 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2458 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2459 bool V2IsUndef = false) {
2460 SmallVector<int, 8> M;
2462 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2465 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2466 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2467 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2468 if (N->getValueType(0).getVectorNumElements() != 4)
2471 // Expect 1, 1, 3, 3
2472 for (unsigned i = 0; i < 2; ++i) {
2473 int Elt = N->getMaskElt(i);
2474 if (Elt >= 0 && Elt != 1)
2479 for (unsigned i = 2; i < 4; ++i) {
2480 int Elt = N->getMaskElt(i);
2481 if (Elt >= 0 && Elt != 3)
2486 // Don't use movshdup if it can be done with a shufps.
2487 // FIXME: verify that matching u, u, 3, 3 is what we want.
2491 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2492 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2493 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2494 if (N->getValueType(0).getVectorNumElements() != 4)
2497 // Expect 0, 0, 2, 2
2498 for (unsigned i = 0; i < 2; ++i)
2499 if (N->getMaskElt(i) > 0)
2503 for (unsigned i = 2; i < 4; ++i) {
2504 int Elt = N->getMaskElt(i);
2505 if (Elt >= 0 && Elt != 2)
2510 // Don't use movsldup if it can be done with a shufps.
2514 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2515 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2516 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2517 int e = N->getValueType(0).getVectorNumElements() / 2;
2519 for (int i = 0; i < e; ++i)
2520 if (!isUndefOrEqual(N->getMaskElt(i), i))
2522 for (int i = 0; i < e; ++i)
2523 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2528 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2529 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2531 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2532 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2533 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2535 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2537 for (int i = 0; i < NumOperands; ++i) {
2538 int Val = SVOp->getMaskElt(NumOperands-i-1);
2539 if (Val < 0) Val = 0;
2540 if (Val >= NumOperands) Val -= NumOperands;
2542 if (i != NumOperands - 1)
2548 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2549 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2551 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2552 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2554 // 8 nodes, but we only care about the last 4.
2555 for (unsigned i = 7; i >= 4; --i) {
2556 int Val = SVOp->getMaskElt(i);
2565 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2566 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2568 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2569 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2571 // 8 nodes, but we only care about the first 4.
2572 for (int i = 3; i >= 0; --i) {
2573 int Val = SVOp->getMaskElt(i);
2582 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2583 /// their permute mask.
2584 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2585 SelectionDAG &DAG) {
2586 MVT VT = SVOp->getValueType(0);
2587 unsigned NumElems = VT.getVectorNumElements();
2588 SmallVector<int, 8> MaskVec;
2590 for (unsigned i = 0; i != NumElems; ++i) {
2591 int idx = SVOp->getMaskElt(i);
2593 MaskVec.push_back(idx);
2594 else if (idx < (int)NumElems)
2595 MaskVec.push_back(idx + NumElems);
2597 MaskVec.push_back(idx - NumElems);
2599 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2600 SVOp->getOperand(0), &MaskVec[0]);
2603 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2604 /// the two vector operands have swapped position.
2605 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, MVT VT) {
2606 unsigned NumElems = VT.getVectorNumElements();
2607 for (unsigned i = 0; i != NumElems; ++i) {
2611 else if (idx < (int)NumElems)
2612 Mask[i] = idx + NumElems;
2614 Mask[i] = idx - NumElems;
2618 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2619 /// match movhlps. The lower half elements should come from upper half of
2620 /// V1 (and in order), and the upper half elements should come from the upper
2621 /// half of V2 (and in order).
2622 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2623 if (Op->getValueType(0).getVectorNumElements() != 4)
2625 for (unsigned i = 0, e = 2; i != e; ++i)
2626 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2628 for (unsigned i = 2; i != 4; ++i)
2629 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2634 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2635 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2637 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2638 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2640 N = N->getOperand(0).getNode();
2641 if (!ISD::isNON_EXTLoad(N))
2644 *LD = cast<LoadSDNode>(N);
2648 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2649 /// match movlp{s|d}. The lower half elements should come from lower half of
2650 /// V1 (and in order), and the upper half elements should come from the upper
2651 /// half of V2 (and in order). And since V1 will become the source of the
2652 /// MOVLP, it must be either a vector load or a scalar load to vector.
2653 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
2654 ShuffleVectorSDNode *Op) {
2655 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2657 // Is V2 is a vector load, don't do this transformation. We will try to use
2658 // load folding shufps op.
2659 if (ISD::isNON_EXTLoad(V2))
2662 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
2664 if (NumElems != 2 && NumElems != 4)
2666 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2667 if (!isUndefOrEqual(Op->getMaskElt(i), i))
2669 for (unsigned i = NumElems/2; i != NumElems; ++i)
2670 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
2675 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2677 static bool isSplatVector(SDNode *N) {
2678 if (N->getOpcode() != ISD::BUILD_VECTOR)
2681 SDValue SplatValue = N->getOperand(0);
2682 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2683 if (N->getOperand(i) != SplatValue)
2688 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2690 static inline bool isZeroNode(SDValue Elt) {
2691 return ((isa<ConstantSDNode>(Elt) &&
2692 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2693 (isa<ConstantFPSDNode>(Elt) &&
2694 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2697 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2698 /// to an zero vector.
2699 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
2700 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
2701 SDValue V1 = N->getOperand(0);
2702 SDValue V2 = N->getOperand(1);
2703 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2704 for (unsigned i = 0; i != NumElems; ++i) {
2705 int Idx = N->getMaskElt(i);
2706 if (Idx >= (int)NumElems) {
2707 unsigned Opc = V2.getOpcode();
2708 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2710 if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V2.getOperand(Idx-NumElems)))
2712 } else if (Idx >= 0) {
2713 unsigned Opc = V1.getOpcode();
2714 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2716 if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V1.getOperand(Idx)))
2723 /// getZeroVector - Returns a vector of specified type with all zero elements.
2725 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2727 assert(VT.isVector() && "Expected a vector type");
2729 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2730 // type. This ensures they get CSE'd.
2732 if (VT.getSizeInBits() == 64) { // MMX
2733 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2734 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2735 } else if (HasSSE2) { // SSE2
2736 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2737 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2739 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2740 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2742 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2745 /// getOnesVector - Returns a vector of specified type with all bits set.
2747 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2748 assert(VT.isVector() && "Expected a vector type");
2750 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2751 // type. This ensures they get CSE'd.
2752 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2754 if (VT.getSizeInBits() == 64) // MMX
2755 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2757 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2758 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2762 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2763 /// that point to V2 points to its first element.
2764 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
2765 MVT VT = SVOp->getValueType(0);
2766 unsigned NumElems = VT.getVectorNumElements();
2768 bool Changed = false;
2769 SmallVector<int, 8> MaskVec;
2770 SVOp->getMask(MaskVec);
2772 for (unsigned i = 0; i != NumElems; ++i) {
2773 if (MaskVec[i] > (int)NumElems) {
2774 MaskVec[i] = NumElems;
2779 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
2780 SVOp->getOperand(1), &MaskVec[0]);
2781 return SDValue(SVOp, 0);
2784 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2785 /// operation of specified width.
2786 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2788 unsigned NumElems = VT.getVectorNumElements();
2789 SmallVector<int, 8> Mask;
2790 Mask.push_back(NumElems);
2791 for (unsigned i = 1; i != NumElems; ++i)
2793 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2796 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
2797 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2799 unsigned NumElems = VT.getVectorNumElements();
2800 SmallVector<int, 8> Mask;
2801 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2803 Mask.push_back(i + NumElems);
2805 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2808 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
2809 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2811 unsigned NumElems = VT.getVectorNumElements();
2812 unsigned Half = NumElems/2;
2813 SmallVector<int, 8> Mask;
2814 for (unsigned i = 0; i != Half; ++i) {
2815 Mask.push_back(i + Half);
2816 Mask.push_back(i + NumElems + Half);
2818 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2821 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2822 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
2824 if (SV->getValueType(0).getVectorNumElements() <= 4)
2825 return SDValue(SV, 0);
2827 MVT PVT = MVT::v4f32;
2828 MVT VT = SV->getValueType(0);
2829 DebugLoc dl = SV->getDebugLoc();
2830 SDValue V1 = SV->getOperand(0);
2831 int NumElems = VT.getVectorNumElements();
2832 int EltNo = SV->getSplatIndex();
2834 // unpack elements to the correct location
2835 while (NumElems > 4) {
2836 if (EltNo < NumElems/2) {
2837 V1 = getUnpackl(DAG, dl, VT, V1, V1);
2839 V1 = getUnpackh(DAG, dl, VT, V1, V1);
2840 EltNo -= NumElems/2;
2845 // Perform the splat.
2846 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
2847 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
2848 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
2849 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
2852 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2853 /// vector of zero or undef vector. This produces a shuffle where the low
2854 /// element of V2 is swizzled into the zero/undef vector, landing at element
2855 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2856 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
2857 bool isZero, bool HasSSE2,
2858 SelectionDAG &DAG) {
2859 MVT VT = V2.getValueType();
2861 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
2862 unsigned NumElems = VT.getVectorNumElements();
2863 SmallVector<int, 16> MaskVec;
2864 for (unsigned i = 0; i != NumElems; ++i)
2865 // If this is the insertion idx, put the low elt of V2 here.
2866 MaskVec.push_back(i == Idx ? NumElems : i);
2867 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
2870 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
2871 /// a shuffle that is zero.
2873 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
2874 bool Low, SelectionDAG &DAG) {
2875 unsigned NumZeros = 0;
2876 for (int i = 0; i < NumElems; ++i) {
2877 unsigned Index = Low ? i : NumElems-i-1;
2878 int Idx = SVOp->getMaskElt(Index);
2883 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
2884 if (Elt.getNode() && isZeroNode(Elt))
2892 /// isVectorShift - Returns true if the shuffle can be implemented as a
2893 /// logical left or right shift of a vector.
2894 /// FIXME: split into pslldqi, psrldqi, palignr variants.
2895 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
2896 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
2897 int NumElems = SVOp->getValueType(0).getVectorNumElements();
2900 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
2903 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
2907 bool SeenV1 = false;
2908 bool SeenV2 = false;
2909 for (int i = NumZeros; i < NumElems; ++i) {
2910 int Val = isLeft ? (i - NumZeros) : i;
2911 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
2923 if (SeenV1 && SeenV2)
2926 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
2932 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2934 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
2935 unsigned NumNonZero, unsigned NumZero,
2936 SelectionDAG &DAG, TargetLowering &TLI) {
2940 DebugLoc dl = Op.getDebugLoc();
2943 for (unsigned i = 0; i < 16; ++i) {
2944 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2945 if (ThisIsNonZero && First) {
2947 V = getZeroVector(MVT::v8i16, true, DAG, dl);
2949 V = DAG.getUNDEF(MVT::v8i16);
2954 SDValue ThisElt(0, 0), LastElt(0, 0);
2955 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2956 if (LastIsNonZero) {
2957 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
2958 MVT::i16, Op.getOperand(i-1));
2960 if (ThisIsNonZero) {
2961 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
2962 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
2963 ThisElt, DAG.getConstant(8, MVT::i8));
2965 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
2969 if (ThisElt.getNode())
2970 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
2971 DAG.getIntPtrConstant(i/2));
2975 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
2978 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2980 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
2981 unsigned NumNonZero, unsigned NumZero,
2982 SelectionDAG &DAG, TargetLowering &TLI) {
2986 DebugLoc dl = Op.getDebugLoc();
2989 for (unsigned i = 0; i < 8; ++i) {
2990 bool isNonZero = (NonZeros & (1 << i)) != 0;
2994 V = getZeroVector(MVT::v8i16, true, DAG, dl);
2996 V = DAG.getUNDEF(MVT::v8i16);
2999 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3000 MVT::v8i16, V, Op.getOperand(i),
3001 DAG.getIntPtrConstant(i));
3008 /// getVShift - Return a vector logical shift node.
3010 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3011 unsigned NumBits, SelectionDAG &DAG,
3012 const TargetLowering &TLI, DebugLoc dl) {
3013 bool isMMX = VT.getSizeInBits() == 64;
3014 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3015 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3016 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3017 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3018 DAG.getNode(Opc, dl, ShVT, SrcOp,
3019 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3023 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3024 DebugLoc dl = Op.getDebugLoc();
3025 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3026 if (ISD::isBuildVectorAllZeros(Op.getNode())
3027 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3028 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3029 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3030 // eliminated on x86-32 hosts.
3031 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3034 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3035 return getOnesVector(Op.getValueType(), DAG, dl);
3036 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3039 MVT VT = Op.getValueType();
3040 MVT EVT = VT.getVectorElementType();
3041 unsigned EVTBits = EVT.getSizeInBits();
3043 unsigned NumElems = Op.getNumOperands();
3044 unsigned NumZero = 0;
3045 unsigned NumNonZero = 0;
3046 unsigned NonZeros = 0;
3047 bool IsAllConstants = true;
3048 SmallSet<SDValue, 8> Values;
3049 for (unsigned i = 0; i < NumElems; ++i) {
3050 SDValue Elt = Op.getOperand(i);
3051 if (Elt.getOpcode() == ISD::UNDEF)
3054 if (Elt.getOpcode() != ISD::Constant &&
3055 Elt.getOpcode() != ISD::ConstantFP)
3056 IsAllConstants = false;
3057 if (isZeroNode(Elt))
3060 NonZeros |= (1 << i);
3065 if (NumNonZero == 0) {
3066 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3067 return DAG.getUNDEF(VT);
3070 // Special case for single non-zero, non-undef, element.
3071 if (NumNonZero == 1 && NumElems <= 4) {
3072 unsigned Idx = CountTrailingZeros_32(NonZeros);
3073 SDValue Item = Op.getOperand(Idx);
3075 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3076 // the value are obviously zero, truncate the value to i32 and do the
3077 // insertion that way. Only do this if the value is non-constant or if the
3078 // value is a constant being inserted into element 0. It is cheaper to do
3079 // a constant pool load than it is to do a movd + shuffle.
3080 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3081 (!IsAllConstants || Idx == 0)) {
3082 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3083 // Handle MMX and SSE both.
3084 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3085 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3087 // Truncate the value (which may itself be a constant) to i32, and
3088 // convert it to a vector with movd (S2V+shuffle to zero extend).
3089 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3090 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3091 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3092 Subtarget->hasSSE2(), DAG);
3094 // Now we have our 32-bit value zero extended in the low element of
3095 // a vector. If Idx != 0, swizzle it into place.
3097 SmallVector<int, 4> Mask;
3098 Mask.push_back(Idx);
3099 for (unsigned i = 1; i != VecElts; ++i)
3101 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3102 DAG.getUNDEF(Item.getValueType()),
3105 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3109 // If we have a constant or non-constant insertion into the low element of
3110 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3111 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3112 // depending on what the source datatype is. Because we can only get here
3113 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3115 // Don't do this for i64 values on x86-32.
3116 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3117 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3118 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3119 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3120 Subtarget->hasSSE2(), DAG);
3123 // Is it a vector logical left shift?
3124 if (NumElems == 2 && Idx == 1 &&
3125 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3126 unsigned NumBits = VT.getSizeInBits();
3127 return getVShift(true, VT,
3128 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3129 VT, Op.getOperand(1)),
3130 NumBits/2, DAG, *this, dl);
3133 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3136 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3137 // is a non-constant being inserted into an element other than the low one,
3138 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3139 // movd/movss) to move this into the low element, then shuffle it into
3141 if (EVTBits == 32) {
3142 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3144 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3145 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3146 Subtarget->hasSSE2(), DAG);
3147 SmallVector<int, 8> MaskVec;
3148 for (unsigned i = 0; i < NumElems; i++)
3149 MaskVec.push_back(i == Idx ? 0 : 1);
3150 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3154 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3155 if (Values.size() == 1)
3158 // A vector full of immediates; various special cases are already
3159 // handled, so this is best done with a single constant-pool load.
3163 // Let legalizer expand 2-wide build_vectors.
3164 if (EVTBits == 64) {
3165 if (NumNonZero == 1) {
3166 // One half is zero or undef.
3167 unsigned Idx = CountTrailingZeros_32(NonZeros);
3168 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3169 Op.getOperand(Idx));
3170 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3171 Subtarget->hasSSE2(), DAG);
3176 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3177 if (EVTBits == 8 && NumElems == 16) {
3178 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3180 if (V.getNode()) return V;
3183 if (EVTBits == 16 && NumElems == 8) {
3184 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3186 if (V.getNode()) return V;
3189 // If element VT is == 32 bits, turn it into a number of shuffles.
3190 SmallVector<SDValue, 8> V;
3192 if (NumElems == 4 && NumZero > 0) {
3193 for (unsigned i = 0; i < 4; ++i) {
3194 bool isZero = !(NonZeros & (1 << i));
3196 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3198 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3201 for (unsigned i = 0; i < 2; ++i) {
3202 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3205 V[i] = V[i*2]; // Must be a zero vector.
3208 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3211 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3214 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3219 SmallVector<int, 8> MaskVec;
3220 bool Reverse = (NonZeros & 0x3) == 2;
3221 for (unsigned i = 0; i < 2; ++i)
3222 MaskVec.push_back(Reverse ? 1-i : i);
3223 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3224 for (unsigned i = 0; i < 2; ++i)
3225 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3226 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3229 if (Values.size() > 2) {
3230 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3231 // values to be inserted is equal to the number of elements, in which case
3232 // use the unpack code below in the hopes of matching the consecutive elts
3233 // load merge pattern for shuffles.
3234 // FIXME: We could probably just check that here directly.
3235 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3236 getSubtarget()->hasSSE41()) {
3237 V[0] = DAG.getUNDEF(VT);
3238 for (unsigned i = 0; i < NumElems; ++i)
3239 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3240 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3241 Op.getOperand(i), DAG.getIntPtrConstant(i));
3244 // Expand into a number of unpckl*.
3246 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3247 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3248 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3249 for (unsigned i = 0; i < NumElems; ++i)
3250 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3252 while (NumElems != 0) {
3253 for (unsigned i = 0; i < NumElems; ++i)
3254 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3263 // v8i16 shuffles - Prefer shuffles in the following order:
3264 // 1. [all] pshuflw, pshufhw, optional move
3265 // 2. [ssse3] 1 x pshufb
3266 // 3. [ssse3] 2 x pshufb + 1 x por
3267 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3269 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3270 SelectionDAG &DAG, X86TargetLowering &TLI) {
3271 SDValue V1 = SVOp->getOperand(0);
3272 SDValue V2 = SVOp->getOperand(1);
3273 DebugLoc dl = SVOp->getDebugLoc();
3274 SmallVector<int, 8> MaskVals;
3276 // Determine if more than 1 of the words in each of the low and high quadwords
3277 // of the result come from the same quadword of one of the two inputs. Undef
3278 // mask values count as coming from any quadword, for better codegen.
3279 SmallVector<unsigned, 4> LoQuad(4);
3280 SmallVector<unsigned, 4> HiQuad(4);
3281 BitVector InputQuads(4);
3282 for (unsigned i = 0; i < 8; ++i) {
3283 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3284 int EltIdx = SVOp->getMaskElt(i);
3285 MaskVals.push_back(EltIdx);
3294 InputQuads.set(EltIdx / 4);
3297 int BestLoQuad = -1;
3298 unsigned MaxQuad = 1;
3299 for (unsigned i = 0; i < 4; ++i) {
3300 if (LoQuad[i] > MaxQuad) {
3302 MaxQuad = LoQuad[i];
3306 int BestHiQuad = -1;
3308 for (unsigned i = 0; i < 4; ++i) {
3309 if (HiQuad[i] > MaxQuad) {
3311 MaxQuad = HiQuad[i];
3315 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3316 // of the two input vectors, shuffle them into one input vector so only a
3317 // single pshufb instruction is necessary. If There are more than 2 input
3318 // quads, disable the next transformation since it does not help SSSE3.
3319 bool V1Used = InputQuads[0] || InputQuads[1];
3320 bool V2Used = InputQuads[2] || InputQuads[3];
3321 if (TLI.getSubtarget()->hasSSSE3()) {
3322 if (InputQuads.count() == 2 && V1Used && V2Used) {
3323 BestLoQuad = InputQuads.find_first();
3324 BestHiQuad = InputQuads.find_next(BestLoQuad);
3326 if (InputQuads.count() > 2) {
3332 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3333 // the shuffle mask. If a quad is scored as -1, that means that it contains
3334 // words from all 4 input quadwords.
3336 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3337 SmallVector<int, 8> MaskV;
3338 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3339 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3340 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3341 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3342 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3343 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3345 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3346 // source words for the shuffle, to aid later transformations.
3347 bool AllWordsInNewV = true;
3348 bool InOrder[2] = { true, true };
3349 for (unsigned i = 0; i != 8; ++i) {
3350 int idx = MaskVals[i];
3352 InOrder[i/4] = false;
3353 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3355 AllWordsInNewV = false;
3359 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3360 if (AllWordsInNewV) {
3361 for (int i = 0; i != 8; ++i) {
3362 int idx = MaskVals[i];
3365 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3366 if ((idx != i) && idx < 4)
3368 if ((idx != i) && idx > 3)
3377 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3378 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3379 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3380 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3381 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3385 // If we have SSSE3, and all words of the result are from 1 input vector,
3386 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3387 // is present, fall back to case 4.
3388 if (TLI.getSubtarget()->hasSSSE3()) {
3389 SmallVector<SDValue,16> pshufbMask;
3391 // If we have elements from both input vectors, set the high bit of the
3392 // shuffle mask element to zero out elements that come from V2 in the V1
3393 // mask, and elements that come from V1 in the V2 mask, so that the two
3394 // results can be OR'd together.
3395 bool TwoInputs = V1Used && V2Used;
3396 for (unsigned i = 0; i != 8; ++i) {
3397 int EltIdx = MaskVals[i] * 2;
3398 if (TwoInputs && (EltIdx >= 16)) {
3399 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3400 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3403 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3404 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3406 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3407 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3408 DAG.getNode(ISD::BUILD_VECTOR, dl,
3409 MVT::v16i8, &pshufbMask[0], 16));
3411 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3413 // Calculate the shuffle mask for the second input, shuffle it, and
3414 // OR it with the first shuffled input.
3416 for (unsigned i = 0; i != 8; ++i) {
3417 int EltIdx = MaskVals[i] * 2;
3419 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3420 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3423 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3424 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3426 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3427 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3428 DAG.getNode(ISD::BUILD_VECTOR, dl,
3429 MVT::v16i8, &pshufbMask[0], 16));
3430 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3431 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3434 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3435 // and update MaskVals with new element order.
3436 BitVector InOrder(8);
3437 if (BestLoQuad >= 0) {
3438 SmallVector<int, 8> MaskV;
3439 for (int i = 0; i != 4; ++i) {
3440 int idx = MaskVals[i];
3442 MaskV.push_back(-1);
3444 } else if ((idx / 4) == BestLoQuad) {
3445 MaskV.push_back(idx & 3);
3448 MaskV.push_back(-1);
3451 for (unsigned i = 4; i != 8; ++i)
3453 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3457 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3458 // and update MaskVals with the new element order.
3459 if (BestHiQuad >= 0) {
3460 SmallVector<int, 8> MaskV;
3461 for (unsigned i = 0; i != 4; ++i)
3463 for (unsigned i = 4; i != 8; ++i) {
3464 int idx = MaskVals[i];
3466 MaskV.push_back(-1);
3468 } else if ((idx / 4) == BestHiQuad) {
3469 MaskV.push_back((idx & 3) + 4);
3472 MaskV.push_back(-1);
3475 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3479 // In case BestHi & BestLo were both -1, which means each quadword has a word
3480 // from each of the four input quadwords, calculate the InOrder bitvector now
3481 // before falling through to the insert/extract cleanup.
3482 if (BestLoQuad == -1 && BestHiQuad == -1) {
3484 for (int i = 0; i != 8; ++i)
3485 if (MaskVals[i] < 0 || MaskVals[i] == i)
3489 // The other elements are put in the right place using pextrw and pinsrw.
3490 for (unsigned i = 0; i != 8; ++i) {
3493 int EltIdx = MaskVals[i];
3496 SDValue ExtOp = (EltIdx < 8)
3497 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3498 DAG.getIntPtrConstant(EltIdx))
3499 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3500 DAG.getIntPtrConstant(EltIdx - 8));
3501 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3502 DAG.getIntPtrConstant(i));
3507 // v16i8 shuffles - Prefer shuffles in the following order:
3508 // 1. [ssse3] 1 x pshufb
3509 // 2. [ssse3] 2 x pshufb + 1 x por
3510 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3512 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3513 SelectionDAG &DAG, X86TargetLowering &TLI) {
3514 SDValue V1 = SVOp->getOperand(0);
3515 SDValue V2 = SVOp->getOperand(1);
3516 DebugLoc dl = SVOp->getDebugLoc();
3517 SmallVector<int, 16> MaskVals;
3518 SVOp->getMask(MaskVals);
3520 // If we have SSSE3, case 1 is generated when all result bytes come from
3521 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3522 // present, fall back to case 3.
3523 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3526 for (unsigned i = 0; i < 16; ++i) {
3527 int EltIdx = MaskVals[i];
3536 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3537 if (TLI.getSubtarget()->hasSSSE3()) {
3538 SmallVector<SDValue,16> pshufbMask;
3540 // If all result elements are from one input vector, then only translate
3541 // undef mask values to 0x80 (zero out result) in the pshufb mask.
3543 // Otherwise, we have elements from both input vectors, and must zero out
3544 // elements that come from V2 in the first mask, and V1 in the second mask
3545 // so that we can OR them together.
3546 bool TwoInputs = !(V1Only || V2Only);
3547 for (unsigned i = 0; i != 16; ++i) {
3548 int EltIdx = MaskVals[i];
3549 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3550 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3553 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3555 // If all the elements are from V2, assign it to V1 and return after
3556 // building the first pshufb.
3559 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3560 DAG.getNode(ISD::BUILD_VECTOR, dl,
3561 MVT::v16i8, &pshufbMask[0], 16));
3565 // Calculate the shuffle mask for the second input, shuffle it, and
3566 // OR it with the first shuffled input.
3568 for (unsigned i = 0; i != 16; ++i) {
3569 int EltIdx = MaskVals[i];
3571 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3574 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3576 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3577 DAG.getNode(ISD::BUILD_VECTOR, dl,
3578 MVT::v16i8, &pshufbMask[0], 16));
3579 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3582 // No SSSE3 - Calculate in place words and then fix all out of place words
3583 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
3584 // the 16 different words that comprise the two doublequadword input vectors.
3585 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3586 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3587 SDValue NewV = V2Only ? V2 : V1;
3588 for (int i = 0; i != 8; ++i) {
3589 int Elt0 = MaskVals[i*2];
3590 int Elt1 = MaskVals[i*2+1];
3592 // This word of the result is all undef, skip it.
3593 if (Elt0 < 0 && Elt1 < 0)
3596 // This word of the result is already in the correct place, skip it.
3597 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3599 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3602 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3603 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3606 // If Elt0 and Elt1 are defined, are consecutive, and can be load
3607 // using a single extract together, load it and store it.
3608 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3609 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3610 DAG.getIntPtrConstant(Elt1 / 2));
3611 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3612 DAG.getIntPtrConstant(i));
3616 // If Elt1 is defined, extract it from the appropriate source. If the
3617 // source byte is not also odd, shift the extracted word left 8 bits
3618 // otherwise clear the bottom 8 bits if we need to do an or.
3620 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3621 DAG.getIntPtrConstant(Elt1 / 2));
3622 if ((Elt1 & 1) == 0)
3623 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3624 DAG.getConstant(8, TLI.getShiftAmountTy()));
3626 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3627 DAG.getConstant(0xFF00, MVT::i16));
3629 // If Elt0 is defined, extract it from the appropriate source. If the
3630 // source byte is not also even, shift the extracted word right 8 bits. If
3631 // Elt1 was also defined, OR the extracted values together before
3632 // inserting them in the result.
3634 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3635 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3636 if ((Elt0 & 1) != 0)
3637 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3638 DAG.getConstant(8, TLI.getShiftAmountTy()));
3640 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3641 DAG.getConstant(0x00FF, MVT::i16));
3642 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3645 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3646 DAG.getIntPtrConstant(i));
3648 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3651 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3652 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3653 /// done when every pair / quad of shuffle mask elements point to elements in
3654 /// the right sequence. e.g.
3655 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3657 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
3659 TargetLowering &TLI, DebugLoc dl) {
3660 MVT VT = SVOp->getValueType(0);
3661 SDValue V1 = SVOp->getOperand(0);
3662 SDValue V2 = SVOp->getOperand(1);
3663 unsigned NumElems = VT.getVectorNumElements();
3664 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3665 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3666 MVT MaskEltVT = MaskVT.getVectorElementType();
3668 switch (VT.getSimpleVT()) {
3669 default: assert(false && "Unexpected!");
3670 case MVT::v4f32: NewVT = MVT::v2f64; break;
3671 case MVT::v4i32: NewVT = MVT::v2i64; break;
3672 case MVT::v8i16: NewVT = MVT::v4i32; break;
3673 case MVT::v16i8: NewVT = MVT::v4i32; break;
3676 if (NewWidth == 2) {
3682 int Scale = NumElems / NewWidth;
3683 SmallVector<int, 8> MaskVec;
3684 for (unsigned i = 0; i < NumElems; i += Scale) {
3686 for (int j = 0; j < Scale; ++j) {
3687 int EltIdx = SVOp->getMaskElt(i+j);
3691 StartIdx = EltIdx - (EltIdx % Scale);
3692 if (EltIdx != StartIdx + j)
3696 MaskVec.push_back(-1);
3698 MaskVec.push_back(StartIdx / Scale);
3701 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3702 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3703 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
3706 /// getVZextMovL - Return a zero-extending vector move low node.
3708 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3709 SDValue SrcOp, SelectionDAG &DAG,
3710 const X86Subtarget *Subtarget, DebugLoc dl) {
3711 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3712 LoadSDNode *LD = NULL;
3713 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3714 LD = dyn_cast<LoadSDNode>(SrcOp);
3716 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3718 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3719 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3720 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3721 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3722 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3724 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3725 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3726 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3727 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3735 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3736 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3737 DAG.getNode(ISD::BIT_CONVERT, dl,
3741 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3744 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3745 SDValue V1 = SVOp->getOperand(0);
3746 SDValue V2 = SVOp->getOperand(1);
3747 DebugLoc dl = SVOp->getDebugLoc();
3748 MVT VT = SVOp->getValueType(0);
3750 SmallVector<std::pair<int, int>, 8> Locs;
3752 SmallVector<int, 8> Mask1(4U, -1);
3753 SmallVector<int, 8> PermMask;
3754 SVOp->getMask(PermMask);
3758 for (unsigned i = 0; i != 4; ++i) {
3759 int Idx = PermMask[i];
3761 Locs[i] = std::make_pair(-1, -1);
3763 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
3765 Locs[i] = std::make_pair(0, NumLo);
3769 Locs[i] = std::make_pair(1, NumHi);
3771 Mask1[2+NumHi] = Idx;
3777 if (NumLo <= 2 && NumHi <= 2) {
3778 // If no more than two elements come from either vector. This can be
3779 // implemented with two shuffles. First shuffle gather the elements.
3780 // The second shuffle, which takes the first shuffle as both of its
3781 // vector operands, put the elements into the right order.
3782 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3784 SmallVector<int, 8> Mask2(4U, -1);
3786 for (unsigned i = 0; i != 4; ++i) {
3787 if (Locs[i].first == -1)
3790 unsigned Idx = (i < 2) ? 0 : 4;
3791 Idx += Locs[i].first * 2 + Locs[i].second;
3796 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
3797 } else if (NumLo == 3 || NumHi == 3) {
3798 // Otherwise, we must have three elements from one vector, call it X, and
3799 // one element from the other, call it Y. First, use a shufps to build an
3800 // intermediate vector with the one element from Y and the element from X
3801 // that will be in the same half in the final destination (the indexes don't
3802 // matter). Then, use a shufps to build the final vector, taking the half
3803 // containing the element from Y from the intermediate, and the other half
3806 // Normalize it so the 3 elements come from V1.
3807 CommuteVectorShuffleMask(PermMask, VT);
3811 // Find the element from V2.
3813 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3814 int Val = PermMask[HiIndex];
3821 Mask1[0] = PermMask[HiIndex];
3823 Mask1[2] = PermMask[HiIndex^1];
3825 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3828 Mask1[0] = PermMask[0];
3829 Mask1[1] = PermMask[1];
3830 Mask1[2] = HiIndex & 1 ? 6 : 4;
3831 Mask1[3] = HiIndex & 1 ? 4 : 6;
3832 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3834 Mask1[0] = HiIndex & 1 ? 2 : 0;
3835 Mask1[1] = HiIndex & 1 ? 0 : 2;
3836 Mask1[2] = PermMask[2];
3837 Mask1[3] = PermMask[3];
3842 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
3846 // Break it into (shuffle shuffle_hi, shuffle_lo).
3848 SmallVector<int,8> LoMask(4U, -1);
3849 SmallVector<int,8> HiMask(4U, -1);
3851 SmallVector<int,8> *MaskPtr = &LoMask;
3852 unsigned MaskIdx = 0;
3855 for (unsigned i = 0; i != 4; ++i) {
3862 int Idx = PermMask[i];
3864 Locs[i] = std::make_pair(-1, -1);
3865 } else if (Idx < 4) {
3866 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3867 (*MaskPtr)[LoIdx] = Idx;
3870 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3871 (*MaskPtr)[HiIdx] = Idx;
3876 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
3877 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
3878 SmallVector<int, 8> MaskOps;
3879 for (unsigned i = 0; i != 4; ++i) {
3880 if (Locs[i].first == -1) {
3881 MaskOps.push_back(-1);
3883 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3884 MaskOps.push_back(Idx);
3887 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
3891 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3892 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
3893 SDValue V1 = Op.getOperand(0);
3894 SDValue V2 = Op.getOperand(1);
3895 MVT VT = Op.getValueType();
3896 DebugLoc dl = Op.getDebugLoc();
3897 unsigned NumElems = VT.getVectorNumElements();
3898 bool isMMX = VT.getSizeInBits() == 64;
3899 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3900 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3901 bool V1IsSplat = false;
3902 bool V2IsSplat = false;
3904 if (isZeroShuffle(SVOp))
3905 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3907 // Promote splats to v4f32.
3908 if (SVOp->isSplat()) {
3909 if (isMMX || NumElems < 4)
3911 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
3914 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3916 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3917 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3918 if (NewOp.getNode())
3919 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3920 LowerVECTOR_SHUFFLE(NewOp, DAG));
3921 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3922 // FIXME: Figure out a cleaner way to do this.
3923 // Try to make use of movq to zero out the top part.
3924 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
3925 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3926 if (NewOp.getNode()) {
3927 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
3928 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
3929 DAG, Subtarget, dl);
3931 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
3932 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3933 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
3934 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3935 DAG, Subtarget, dl);
3939 if (X86::isPSHUFDMask(SVOp))
3942 // Check if this can be converted into a logical shift.
3943 bool isLeft = false;
3946 bool isShift = getSubtarget()->hasSSE2() &&
3947 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
3948 if (isShift && ShVal.hasOneUse()) {
3949 // If the shifted value has multiple uses, it may be cheaper to use
3950 // v_set0 + movlhps or movhlps, etc.
3951 MVT EVT = VT.getVectorElementType();
3952 ShAmt *= EVT.getSizeInBits();
3953 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
3956 if (X86::isMOVLMask(SVOp)) {
3959 if (ISD::isBuildVectorAllZeros(V1.getNode()))
3960 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
3965 // FIXME: fold these into legal mask.
3966 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
3967 X86::isMOVSLDUPMask(SVOp) ||
3968 X86::isMOVHLPSMask(SVOp) ||
3969 X86::isMOVHPMask(SVOp) ||
3970 X86::isMOVLPMask(SVOp)))
3973 if (ShouldXformToMOVHLPS(SVOp) ||
3974 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
3975 return CommuteVectorShuffle(SVOp, DAG);
3978 // No better options. Use a vshl / vsrl.
3979 MVT EVT = VT.getVectorElementType();
3980 ShAmt *= EVT.getSizeInBits();
3981 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
3984 bool Commuted = false;
3985 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3986 // 1,1,1,1 -> v8i16 though.
3987 V1IsSplat = isSplatVector(V1.getNode());
3988 V2IsSplat = isSplatVector(V2.getNode());
3990 // Canonicalize the splat or undef, if present, to be on the RHS.
3991 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3992 Op = CommuteVectorShuffle(SVOp, DAG);
3993 SVOp = cast<ShuffleVectorSDNode>(Op);
3994 V1 = SVOp->getOperand(0);
3995 V2 = SVOp->getOperand(1);
3996 std::swap(V1IsSplat, V2IsSplat);
3997 std::swap(V1IsUndef, V2IsUndef);
4001 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4002 // Shuffling low element of v1 into undef, just return v1.
4005 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4006 // the instruction selector will not match, so get a canonical MOVL with
4007 // swapped operands to undo the commute.
4008 return getMOVL(DAG, dl, VT, V2, V1);
4011 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4012 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4013 X86::isUNPCKLMask(SVOp) ||
4014 X86::isUNPCKHMask(SVOp))
4018 // Normalize mask so all entries that point to V2 points to its first
4019 // element then try to match unpck{h|l} again. If match, return a
4020 // new vector_shuffle with the corrected mask.
4021 SDValue NewMask = NormalizeMask(SVOp, DAG);
4022 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4023 if (NSVOp != SVOp) {
4024 if (X86::isUNPCKLMask(NSVOp, true)) {
4026 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4033 // Commute is back and try unpck* again.
4034 // FIXME: this seems wrong.
4035 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4036 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4037 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4038 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4039 X86::isUNPCKLMask(NewSVOp) ||
4040 X86::isUNPCKHMask(NewSVOp))
4044 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4046 // Normalize the node to match x86 shuffle ops if needed
4047 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4048 return CommuteVectorShuffle(SVOp, DAG);
4050 // Check for legal shuffle and return?
4051 SmallVector<int, 16> PermMask;
4052 SVOp->getMask(PermMask);
4053 if (isShuffleMaskLegal(PermMask, VT))
4056 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4057 if (VT == MVT::v8i16) {
4058 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4059 if (NewOp.getNode())
4063 if (VT == MVT::v16i8) {
4064 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4065 if (NewOp.getNode())
4069 // Handle all 4 wide cases with a number of shuffles except for MMX.
4070 if (NumElems == 4 && !isMMX)
4071 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4077 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4078 SelectionDAG &DAG) {
4079 MVT VT = Op.getValueType();
4080 DebugLoc dl = Op.getDebugLoc();
4081 if (VT.getSizeInBits() == 8) {
4082 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4083 Op.getOperand(0), Op.getOperand(1));
4084 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4085 DAG.getValueType(VT));
4086 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4087 } else if (VT.getSizeInBits() == 16) {
4088 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4089 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4091 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4092 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4093 DAG.getNode(ISD::BIT_CONVERT, dl,
4097 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4098 Op.getOperand(0), Op.getOperand(1));
4099 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4100 DAG.getValueType(VT));
4101 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4102 } else if (VT == MVT::f32) {
4103 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4104 // the result back to FR32 register. It's only worth matching if the
4105 // result has a single use which is a store or a bitcast to i32. And in
4106 // the case of a store, it's not worth it if the index is a constant 0,
4107 // because a MOVSSmr can be used instead, which is smaller and faster.
4108 if (!Op.hasOneUse())
4110 SDNode *User = *Op.getNode()->use_begin();
4111 if ((User->getOpcode() != ISD::STORE ||
4112 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4113 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4114 (User->getOpcode() != ISD::BIT_CONVERT ||
4115 User->getValueType(0) != MVT::i32))
4117 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4118 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4121 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4122 } else if (VT == MVT::i32) {
4123 // ExtractPS works with constant index.
4124 if (isa<ConstantSDNode>(Op.getOperand(1)))
4132 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4133 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4136 if (Subtarget->hasSSE41()) {
4137 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4142 MVT VT = Op.getValueType();
4143 DebugLoc dl = Op.getDebugLoc();
4144 // TODO: handle v16i8.
4145 if (VT.getSizeInBits() == 16) {
4146 SDValue Vec = Op.getOperand(0);
4147 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4149 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4150 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4151 DAG.getNode(ISD::BIT_CONVERT, dl,
4154 // Transform it so it match pextrw which produces a 32-bit result.
4155 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4156 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4157 Op.getOperand(0), Op.getOperand(1));
4158 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4159 DAG.getValueType(VT));
4160 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4161 } else if (VT.getSizeInBits() == 32) {
4162 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4166 // SHUFPS the element to the lowest double word, then movss.
4167 int Mask[4] = { Idx, -1, -1, -1 };
4168 MVT VVT = Op.getOperand(0).getValueType();
4169 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4170 DAG.getUNDEF(VVT), Mask);
4171 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4172 DAG.getIntPtrConstant(0));
4173 } else if (VT.getSizeInBits() == 64) {
4174 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4175 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4176 // to match extract_elt for f64.
4177 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4181 // UNPCKHPD the element to the lowest double word, then movsd.
4182 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4183 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4184 int Mask[2] = { 1, -1 };
4185 MVT VVT = Op.getOperand(0).getValueType();
4186 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4187 DAG.getUNDEF(VVT), Mask);
4188 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4189 DAG.getIntPtrConstant(0));
4196 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4197 MVT VT = Op.getValueType();
4198 MVT EVT = VT.getVectorElementType();
4199 DebugLoc dl = Op.getDebugLoc();
4201 SDValue N0 = Op.getOperand(0);
4202 SDValue N1 = Op.getOperand(1);
4203 SDValue N2 = Op.getOperand(2);
4205 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4206 isa<ConstantSDNode>(N2)) {
4207 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4209 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4211 if (N1.getValueType() != MVT::i32)
4212 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4213 if (N2.getValueType() != MVT::i32)
4214 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4215 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4216 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4217 // Bits [7:6] of the constant are the source select. This will always be
4218 // zero here. The DAG Combiner may combine an extract_elt index into these
4219 // bits. For example (insert (extract, 3), 2) could be matched by putting
4220 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4221 // Bits [5:4] of the constant are the destination select. This is the
4222 // value of the incoming immediate.
4223 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4224 // combine either bitwise AND or insert of float 0.0 to set these bits.
4225 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4226 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4227 } else if (EVT == MVT::i32) {
4228 // InsertPS works with constant index.
4229 if (isa<ConstantSDNode>(N2))
4236 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4237 MVT VT = Op.getValueType();
4238 MVT EVT = VT.getVectorElementType();
4240 if (Subtarget->hasSSE41())
4241 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4246 DebugLoc dl = Op.getDebugLoc();
4247 SDValue N0 = Op.getOperand(0);
4248 SDValue N1 = Op.getOperand(1);
4249 SDValue N2 = Op.getOperand(2);
4251 if (EVT.getSizeInBits() == 16) {
4252 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4253 // as its second argument.
4254 if (N1.getValueType() != MVT::i32)
4255 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4256 if (N2.getValueType() != MVT::i32)
4257 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4258 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4264 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4265 DebugLoc dl = Op.getDebugLoc();
4266 if (Op.getValueType() == MVT::v2f32)
4267 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4268 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4269 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4270 Op.getOperand(0))));
4272 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4273 MVT VT = MVT::v2i32;
4274 switch (Op.getValueType().getSimpleVT()) {
4281 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4282 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4285 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4286 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4287 // one of the above mentioned nodes. It has to be wrapped because otherwise
4288 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4289 // be used to form addressing mode. These wrapped nodes will be selected
4292 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4293 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4294 // FIXME there isn't really any debug info here, should come from the parent
4295 DebugLoc dl = CP->getDebugLoc();
4296 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4297 CP->getAlignment());
4298 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4299 // With PIC, the address is actually $g + Offset.
4300 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4301 !Subtarget->isPICStyleRIPRel()) {
4302 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4303 DAG.getNode(X86ISD::GlobalBaseReg,
4304 DebugLoc::getUnknownLoc(),
4313 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4315 SelectionDAG &DAG) const {
4316 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4317 bool ExtraLoadRequired =
4318 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4320 // Create the TargetGlobalAddress node, folding in the constant
4321 // offset if it is legal.
4323 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4324 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4327 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4328 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4330 // With PIC, the address is actually $g + Offset.
4331 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4332 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4333 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4337 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4338 // load the value at address GV, not the value of GV itself. This means that
4339 // the GlobalAddress must be in the base or index register of the address, not
4340 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4341 // The same applies for external symbols during PIC codegen
4342 if (ExtraLoadRequired)
4343 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4344 PseudoSourceValue::getGOT(), 0);
4346 // If there was a non-zero offset that we didn't fold, create an explicit
4349 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4350 DAG.getConstant(Offset, getPointerTy()));
4356 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4357 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4358 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4359 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4363 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4364 SDValue *InFlag, const MVT PtrVT, unsigned ReturnReg) {
4365 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4366 DebugLoc dl = GA->getDebugLoc();
4367 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4368 GA->getValueType(0),
4371 SDValue Ops[] = { Chain, TGA, *InFlag };
4372 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4374 SDValue Ops[] = { Chain, TGA };
4375 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4377 SDValue Flag = Chain.getValue(1);
4378 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4381 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4383 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4386 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4387 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4388 DAG.getNode(X86ISD::GlobalBaseReg,
4389 DebugLoc::getUnknownLoc(),
4391 InFlag = Chain.getValue(1);
4393 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX);
4396 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4398 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4400 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX);
4403 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4404 // "local exec" model.
4405 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4406 const MVT PtrVT, TLSModel::Model model,
4408 DebugLoc dl = GA->getDebugLoc();
4409 // Get the Thread Pointer
4410 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4411 DebugLoc::getUnknownLoc(), PtrVT,
4412 DAG.getRegister(is64Bit? X86::FS : X86::GS,
4415 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4418 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4420 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4421 GA->getValueType(0),
4423 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
4425 if (model == TLSModel::InitialExec)
4426 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4427 PseudoSourceValue::getGOT(), 0);
4429 // The address of the thread local variable is the add of the thread
4430 // pointer with the offset of the variable.
4431 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4435 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4436 // TODO: implement the "local dynamic" model
4437 // TODO: implement the "initial exec"model for pic executables
4438 assert(Subtarget->isTargetELF() &&
4439 "TLS not implemented for non-ELF targets");
4440 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4441 GlobalValue *GV = GA->getGlobal();
4442 TLSModel::Model model =
4443 getTLSModel (GV, getTargetMachine().getRelocationModel());
4444 if (Subtarget->is64Bit()) {
4446 case TLSModel::GeneralDynamic:
4447 case TLSModel::LocalDynamic: // not implemented
4448 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4450 case TLSModel::InitialExec:
4451 case TLSModel::LocalExec:
4452 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, true);
4456 case TLSModel::GeneralDynamic:
4457 case TLSModel::LocalDynamic: // not implemented
4458 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4460 case TLSModel::InitialExec:
4461 case TLSModel::LocalExec:
4462 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, false);
4465 assert(0 && "Unreachable");
4470 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4471 // FIXME there isn't really any debug info here
4472 DebugLoc dl = Op.getDebugLoc();
4473 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4474 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4475 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4476 // With PIC, the address is actually $g + Offset.
4477 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4478 !Subtarget->isPICStyleRIPRel()) {
4479 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4480 DAG.getNode(X86ISD::GlobalBaseReg,
4481 DebugLoc::getUnknownLoc(),
4489 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4490 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4491 // FIXME there isn't really any debug into here
4492 DebugLoc dl = JT->getDebugLoc();
4493 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4494 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4495 // With PIC, the address is actually $g + Offset.
4496 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4497 !Subtarget->isPICStyleRIPRel()) {
4498 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4499 DAG.getNode(X86ISD::GlobalBaseReg,
4500 DebugLoc::getUnknownLoc(),
4508 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4509 /// take a 2 x i32 value to shift plus a shift amount.
4510 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4511 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4512 MVT VT = Op.getValueType();
4513 unsigned VTBits = VT.getSizeInBits();
4514 DebugLoc dl = Op.getDebugLoc();
4515 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4516 SDValue ShOpLo = Op.getOperand(0);
4517 SDValue ShOpHi = Op.getOperand(1);
4518 SDValue ShAmt = Op.getOperand(2);
4519 SDValue Tmp1 = isSRA ?
4520 DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4521 DAG.getConstant(VTBits - 1, MVT::i8)) :
4522 DAG.getConstant(0, VT);
4525 if (Op.getOpcode() == ISD::SHL_PARTS) {
4526 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4527 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4529 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4530 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4533 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4534 DAG.getConstant(VTBits, MVT::i8));
4535 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4536 AndNode, DAG.getConstant(0, MVT::i8));
4539 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4540 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4541 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4543 if (Op.getOpcode() == ISD::SHL_PARTS) {
4544 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4545 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4547 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4548 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4551 SDValue Ops[2] = { Lo, Hi };
4552 return DAG.getMergeValues(Ops, 2, dl);
4555 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4556 MVT SrcVT = Op.getOperand(0).getValueType();
4557 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4558 "Unknown SINT_TO_FP to lower!");
4560 // These are really Legal; return the operand so the caller accepts it as
4562 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4564 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
4565 Subtarget->is64Bit()) {
4569 DebugLoc dl = Op.getDebugLoc();
4570 unsigned Size = SrcVT.getSizeInBits()/8;
4571 MachineFunction &MF = DAG.getMachineFunction();
4572 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4573 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4574 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4576 PseudoSourceValue::getFixedStack(SSFI), 0);
4577 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
4580 SDValue X86TargetLowering::BuildFILD(SDValue Op, MVT SrcVT, SDValue Chain,
4582 SelectionDAG &DAG) {
4584 DebugLoc dl = Op.getDebugLoc();
4586 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4588 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4590 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4591 SmallVector<SDValue, 8> Ops;
4592 Ops.push_back(Chain);
4593 Ops.push_back(StackSlot);
4594 Ops.push_back(DAG.getValueType(SrcVT));
4595 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4596 Tys, &Ops[0], Ops.size());
4599 Chain = Result.getValue(1);
4600 SDValue InFlag = Result.getValue(2);
4602 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4603 // shouldn't be necessary except that RFP cannot be live across
4604 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4605 MachineFunction &MF = DAG.getMachineFunction();
4606 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4607 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4608 Tys = DAG.getVTList(MVT::Other);
4609 SmallVector<SDValue, 8> Ops;
4610 Ops.push_back(Chain);
4611 Ops.push_back(Result);
4612 Ops.push_back(StackSlot);
4613 Ops.push_back(DAG.getValueType(Op.getValueType()));
4614 Ops.push_back(InFlag);
4615 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4616 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4617 PseudoSourceValue::getFixedStack(SSFI), 0);
4623 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4624 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4625 // This algorithm is not obvious. Here it is in C code, more or less:
4627 double uint64_to_double( uint32_t hi, uint32_t lo ) {
4628 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4629 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4631 // Copy ints to xmm registers.
4632 __m128i xh = _mm_cvtsi32_si128( hi );
4633 __m128i xl = _mm_cvtsi32_si128( lo );
4635 // Combine into low half of a single xmm register.
4636 __m128i x = _mm_unpacklo_epi32( xh, xl );
4640 // Merge in appropriate exponents to give the integer bits the right
4642 x = _mm_unpacklo_epi32( x, exp );
4644 // Subtract away the biases to deal with the IEEE-754 double precision
4646 d = _mm_sub_pd( (__m128d) x, bias );
4648 // All conversions up to here are exact. The correctly rounded result is
4649 // calculated using the current rounding mode using the following
4651 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4652 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
4653 // store doesn't really need to be here (except
4654 // maybe to zero the other double)
4659 DebugLoc dl = Op.getDebugLoc();
4661 // Build some magic constants.
4662 std::vector<Constant*> CV0;
4663 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4664 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4665 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4666 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4667 Constant *C0 = ConstantVector::get(CV0);
4668 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
4670 std::vector<Constant*> CV1;
4671 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4672 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4673 Constant *C1 = ConstantVector::get(CV1);
4674 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
4676 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4677 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4679 DAG.getIntPtrConstant(1)));
4680 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4681 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4683 DAG.getIntPtrConstant(0)));
4684 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
4685 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
4686 PseudoSourceValue::getConstantPool(), 0,
4688 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
4689 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
4690 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
4691 PseudoSourceValue::getConstantPool(), 0,
4693 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
4695 // Add the halves; easiest way is to swap them into another reg first.
4696 int ShufMask[2] = { 1, -1 };
4697 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
4698 DAG.getUNDEF(MVT::v2f64), ShufMask);
4699 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
4700 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
4701 DAG.getIntPtrConstant(0));
4704 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4705 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4706 DebugLoc dl = Op.getDebugLoc();
4707 // FP constant to bias correct the final result.
4708 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4711 // Load the 32-bit value into an XMM register.
4712 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4713 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4715 DAG.getIntPtrConstant(0)));
4717 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4718 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
4719 DAG.getIntPtrConstant(0));
4721 // Or the load with the bias.
4722 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
4723 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4724 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4726 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4727 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4728 MVT::v2f64, Bias)));
4729 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4730 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
4731 DAG.getIntPtrConstant(0));
4733 // Subtract the bias.
4734 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
4736 // Handle final rounding.
4737 MVT DestVT = Op.getValueType();
4739 if (DestVT.bitsLT(MVT::f64)) {
4740 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
4741 DAG.getIntPtrConstant(0));
4742 } else if (DestVT.bitsGT(MVT::f64)) {
4743 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
4746 // Handle final rounding.
4750 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4751 SDValue N0 = Op.getOperand(0);
4752 DebugLoc dl = Op.getDebugLoc();
4754 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
4755 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
4756 // the optimization here.
4757 if (DAG.SignBitIsZero(N0))
4758 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
4760 MVT SrcVT = N0.getValueType();
4761 if (SrcVT == MVT::i64) {
4762 // We only handle SSE2 f64 target here; caller can expand the rest.
4763 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4766 return LowerUINT_TO_FP_i64(Op, DAG);
4767 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
4768 return LowerUINT_TO_FP_i32(Op, DAG);
4771 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
4773 // Make a 64-bit buffer, and use it to build an FILD.
4774 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
4775 SDValue WordOff = DAG.getConstant(4, getPointerTy());
4776 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
4777 getPointerTy(), StackSlot, WordOff);
4778 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4779 StackSlot, NULL, 0);
4780 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
4781 OffsetSlot, NULL, 0);
4782 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
4785 std::pair<SDValue,SDValue> X86TargetLowering::
4786 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
4787 DebugLoc dl = Op.getDebugLoc();
4789 MVT DstTy = Op.getValueType();
4792 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
4796 assert(DstTy.getSimpleVT() <= MVT::i64 &&
4797 DstTy.getSimpleVT() >= MVT::i16 &&
4798 "Unknown FP_TO_SINT to lower!");
4800 // These are really Legal.
4801 if (DstTy == MVT::i32 &&
4802 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4803 return std::make_pair(SDValue(), SDValue());
4804 if (Subtarget->is64Bit() &&
4805 DstTy == MVT::i64 &&
4806 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4807 return std::make_pair(SDValue(), SDValue());
4809 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4811 MachineFunction &MF = DAG.getMachineFunction();
4812 unsigned MemSize = DstTy.getSizeInBits()/8;
4813 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4814 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4817 switch (DstTy.getSimpleVT()) {
4818 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4819 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4820 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4821 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4824 SDValue Chain = DAG.getEntryNode();
4825 SDValue Value = Op.getOperand(0);
4826 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4827 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4828 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
4829 PseudoSourceValue::getFixedStack(SSFI), 0);
4830 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4832 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4834 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
4835 Chain = Value.getValue(1);
4836 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4837 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4840 // Build the FP_TO_INT*_IN_MEM
4841 SDValue Ops[] = { Chain, Value, StackSlot };
4842 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
4844 return std::make_pair(FIST, StackSlot);
4847 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4848 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
4849 SDValue FIST = Vals.first, StackSlot = Vals.second;
4850 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
4851 if (FIST.getNode() == 0) return Op;
4854 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
4855 FIST, StackSlot, NULL, 0);
4858 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
4859 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
4860 SDValue FIST = Vals.first, StackSlot = Vals.second;
4861 assert(FIST.getNode() && "Unexpected failure");
4864 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
4865 FIST, StackSlot, NULL, 0);
4868 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4869 DebugLoc dl = Op.getDebugLoc();
4870 MVT VT = Op.getValueType();
4873 EltVT = VT.getVectorElementType();
4874 std::vector<Constant*> CV;
4875 if (EltVT == MVT::f64) {
4876 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4880 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4886 Constant *C = ConstantVector::get(CV);
4887 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4888 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4889 PseudoSourceValue::getConstantPool(), 0,
4891 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
4894 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4895 DebugLoc dl = Op.getDebugLoc();
4896 MVT VT = Op.getValueType();
4898 unsigned EltNum = 1;
4899 if (VT.isVector()) {
4900 EltVT = VT.getVectorElementType();
4901 EltNum = VT.getVectorNumElements();
4903 std::vector<Constant*> CV;
4904 if (EltVT == MVT::f64) {
4905 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4909 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4915 Constant *C = ConstantVector::get(CV);
4916 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4917 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4918 PseudoSourceValue::getConstantPool(), 0,
4920 if (VT.isVector()) {
4921 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4922 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
4923 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4925 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
4927 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
4931 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4932 SDValue Op0 = Op.getOperand(0);
4933 SDValue Op1 = Op.getOperand(1);
4934 DebugLoc dl = Op.getDebugLoc();
4935 MVT VT = Op.getValueType();
4936 MVT SrcVT = Op1.getValueType();
4938 // If second operand is smaller, extend it first.
4939 if (SrcVT.bitsLT(VT)) {
4940 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
4943 // And if it is bigger, shrink it first.
4944 if (SrcVT.bitsGT(VT)) {
4945 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
4949 // At this point the operands and the result should have the same
4950 // type, and that won't be f80 since that is not custom lowered.
4952 // First get the sign bit of second operand.
4953 std::vector<Constant*> CV;
4954 if (SrcVT == MVT::f64) {
4955 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4956 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4958 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4959 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4960 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4961 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4963 Constant *C = ConstantVector::get(CV);
4964 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4965 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
4966 PseudoSourceValue::getConstantPool(), 0,
4968 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
4970 // Shift sign bit right or left if the two operands have different types.
4971 if (SrcVT.bitsGT(VT)) {
4972 // Op0 is MVT::f32, Op1 is MVT::f64.
4973 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
4974 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
4975 DAG.getConstant(32, MVT::i32));
4976 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
4977 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
4978 DAG.getIntPtrConstant(0));
4981 // Clear first operand sign bit.
4983 if (VT == MVT::f64) {
4984 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4985 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4987 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4988 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4989 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4990 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4992 C = ConstantVector::get(CV);
4993 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4994 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4995 PseudoSourceValue::getConstantPool(), 0,
4997 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
4999 // Or the value with the sign bit.
5000 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5003 /// Emit nodes that will be selected as "test Op0,Op0", or something
5005 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5006 SelectionDAG &DAG) {
5007 DebugLoc dl = Op.getDebugLoc();
5009 // CF and OF aren't always set the way we want. Determine which
5010 // of these we need.
5011 bool NeedCF = false;
5012 bool NeedOF = false;
5014 case X86::COND_A: case X86::COND_AE:
5015 case X86::COND_B: case X86::COND_BE:
5018 case X86::COND_G: case X86::COND_GE:
5019 case X86::COND_L: case X86::COND_LE:
5020 case X86::COND_O: case X86::COND_NO:
5026 // See if we can use the EFLAGS value from the operand instead of
5027 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5028 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5029 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5030 unsigned Opcode = 0;
5031 unsigned NumOperands = 0;
5032 switch (Op.getNode()->getOpcode()) {
5034 // Due to an isel shortcoming, be conservative if this add is likely to
5035 // be selected as part of a load-modify-store instruction. When the root
5036 // node in a match is a store, isel doesn't know how to remap non-chain
5037 // non-flag uses of other nodes in the match, such as the ADD in this
5038 // case. This leads to the ADD being left around and reselected, with
5039 // the result being two adds in the output.
5040 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5041 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5042 if (UI->getOpcode() == ISD::STORE)
5044 if (ConstantSDNode *C =
5045 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5046 // An add of one will be selected as an INC.
5047 if (C->getAPIntValue() == 1) {
5048 Opcode = X86ISD::INC;
5052 // An add of negative one (subtract of one) will be selected as a DEC.
5053 if (C->getAPIntValue().isAllOnesValue()) {
5054 Opcode = X86ISD::DEC;
5059 // Otherwise use a regular EFLAGS-setting add.
5060 Opcode = X86ISD::ADD;
5064 // Due to the ISEL shortcoming noted above, be conservative if this sub is
5065 // likely to be selected as part of a load-modify-store instruction.
5066 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5067 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5068 if (UI->getOpcode() == ISD::STORE)
5070 // Otherwise use a regular EFLAGS-setting sub.
5071 Opcode = X86ISD::SUB;
5078 return SDValue(Op.getNode(), 1);
5084 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5085 SmallVector<SDValue, 4> Ops;
5086 for (unsigned i = 0; i != NumOperands; ++i)
5087 Ops.push_back(Op.getOperand(i));
5088 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5089 DAG.ReplaceAllUsesWith(Op, New);
5090 return SDValue(New.getNode(), 1);
5094 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5095 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5096 DAG.getConstant(0, Op.getValueType()));
5099 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5101 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5102 SelectionDAG &DAG) {
5103 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5104 if (C->getAPIntValue() == 0)
5105 return EmitTest(Op0, X86CC, DAG);
5107 DebugLoc dl = Op0.getDebugLoc();
5108 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5111 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5112 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5113 SDValue Op0 = Op.getOperand(0);
5114 SDValue Op1 = Op.getOperand(1);
5115 DebugLoc dl = Op.getDebugLoc();
5116 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5118 // Lower (X & (1 << N)) == 0 to BT(X, N).
5119 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5120 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5121 if (Op0.getOpcode() == ISD::AND &&
5123 Op1.getOpcode() == ISD::Constant &&
5124 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5125 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5127 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5128 if (ConstantSDNode *Op010C =
5129 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5130 if (Op010C->getZExtValue() == 1) {
5131 LHS = Op0.getOperand(0);
5132 RHS = Op0.getOperand(1).getOperand(1);
5134 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5135 if (ConstantSDNode *Op000C =
5136 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5137 if (Op000C->getZExtValue() == 1) {
5138 LHS = Op0.getOperand(1);
5139 RHS = Op0.getOperand(0).getOperand(1);
5141 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5142 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5143 SDValue AndLHS = Op0.getOperand(0);
5144 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5145 LHS = AndLHS.getOperand(0);
5146 RHS = AndLHS.getOperand(1);
5150 if (LHS.getNode()) {
5151 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5152 // instruction. Since the shift amount is in-range-or-undefined, we know
5153 // that doing a bittest on the i16 value is ok. We extend to i32 because
5154 // the encoding for the i16 version is larger than the i32 version.
5155 if (LHS.getValueType() == MVT::i8)
5156 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5158 // If the operand types disagree, extend the shift amount to match. Since
5159 // BT ignores high bits (like shifts) we can use anyextend.
5160 if (LHS.getValueType() != RHS.getValueType())
5161 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5163 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5164 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5165 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5166 DAG.getConstant(Cond, MVT::i8), BT);
5170 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5171 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5173 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5174 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5175 DAG.getConstant(X86CC, MVT::i8), Cond);
5178 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5180 SDValue Op0 = Op.getOperand(0);
5181 SDValue Op1 = Op.getOperand(1);
5182 SDValue CC = Op.getOperand(2);
5183 MVT VT = Op.getValueType();
5184 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5185 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5186 DebugLoc dl = Op.getDebugLoc();
5190 MVT VT0 = Op0.getValueType();
5191 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5192 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5195 switch (SetCCOpcode) {
5198 case ISD::SETEQ: SSECC = 0; break;
5200 case ISD::SETGT: Swap = true; // Fallthrough
5202 case ISD::SETOLT: SSECC = 1; break;
5204 case ISD::SETGE: Swap = true; // Fallthrough
5206 case ISD::SETOLE: SSECC = 2; break;
5207 case ISD::SETUO: SSECC = 3; break;
5209 case ISD::SETNE: SSECC = 4; break;
5210 case ISD::SETULE: Swap = true;
5211 case ISD::SETUGE: SSECC = 5; break;
5212 case ISD::SETULT: Swap = true;
5213 case ISD::SETUGT: SSECC = 6; break;
5214 case ISD::SETO: SSECC = 7; break;
5217 std::swap(Op0, Op1);
5219 // In the two special cases we can't handle, emit two comparisons.
5221 if (SetCCOpcode == ISD::SETUEQ) {
5223 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5224 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5225 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5227 else if (SetCCOpcode == ISD::SETONE) {
5229 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5230 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5231 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5233 assert(0 && "Illegal FP comparison");
5235 // Handle all other FP comparisons here.
5236 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5239 // We are handling one of the integer comparisons here. Since SSE only has
5240 // GT and EQ comparisons for integer, swapping operands and multiple
5241 // operations may be required for some comparisons.
5242 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5243 bool Swap = false, Invert = false, FlipSigns = false;
5245 switch (VT.getSimpleVT()) {
5247 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5248 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5249 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5250 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5253 switch (SetCCOpcode) {
5255 case ISD::SETNE: Invert = true;
5256 case ISD::SETEQ: Opc = EQOpc; break;
5257 case ISD::SETLT: Swap = true;
5258 case ISD::SETGT: Opc = GTOpc; break;
5259 case ISD::SETGE: Swap = true;
5260 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5261 case ISD::SETULT: Swap = true;
5262 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5263 case ISD::SETUGE: Swap = true;
5264 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5267 std::swap(Op0, Op1);
5269 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5270 // bits of the inputs before performing those operations.
5272 MVT EltVT = VT.getVectorElementType();
5273 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5275 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5276 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5278 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5279 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5282 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5284 // If the logical-not of the result is required, perform that now.
5286 Result = DAG.getNOT(dl, Result, VT);
5291 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5292 static bool isX86LogicalCmp(SDValue Op) {
5293 unsigned Opc = Op.getNode()->getOpcode();
5294 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5296 if (Op.getResNo() == 1 &&
5297 (Opc == X86ISD::ADD ||
5298 Opc == X86ISD::SUB ||
5299 Opc == X86ISD::SMUL ||
5300 Opc == X86ISD::UMUL ||
5301 Opc == X86ISD::INC ||
5302 Opc == X86ISD::DEC))
5308 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5309 bool addTest = true;
5310 SDValue Cond = Op.getOperand(0);
5311 DebugLoc dl = Op.getDebugLoc();
5314 if (Cond.getOpcode() == ISD::SETCC)
5315 Cond = LowerSETCC(Cond, DAG);
5317 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5318 // setting operand in place of the X86ISD::SETCC.
5319 if (Cond.getOpcode() == X86ISD::SETCC) {
5320 CC = Cond.getOperand(0);
5322 SDValue Cmp = Cond.getOperand(1);
5323 unsigned Opc = Cmp.getOpcode();
5324 MVT VT = Op.getValueType();
5326 bool IllegalFPCMov = false;
5327 if (VT.isFloatingPoint() && !VT.isVector() &&
5328 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5329 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5331 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5332 Opc == X86ISD::BT) { // FIXME
5339 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5340 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5343 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
5344 SmallVector<SDValue, 4> Ops;
5345 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5346 // condition is true.
5347 Ops.push_back(Op.getOperand(2));
5348 Ops.push_back(Op.getOperand(1));
5350 Ops.push_back(Cond);
5351 return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size());
5354 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5355 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5356 // from the AND / OR.
5357 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5358 Opc = Op.getOpcode();
5359 if (Opc != ISD::OR && Opc != ISD::AND)
5361 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5362 Op.getOperand(0).hasOneUse() &&
5363 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5364 Op.getOperand(1).hasOneUse());
5367 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5368 // 1 and that the SETCC node has a single use.
5369 static bool isXor1OfSetCC(SDValue Op) {
5370 if (Op.getOpcode() != ISD::XOR)
5372 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5373 if (N1C && N1C->getAPIntValue() == 1) {
5374 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5375 Op.getOperand(0).hasOneUse();
5380 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5381 bool addTest = true;
5382 SDValue Chain = Op.getOperand(0);
5383 SDValue Cond = Op.getOperand(1);
5384 SDValue Dest = Op.getOperand(2);
5385 DebugLoc dl = Op.getDebugLoc();
5388 if (Cond.getOpcode() == ISD::SETCC)
5389 Cond = LowerSETCC(Cond, DAG);
5391 // FIXME: LowerXALUO doesn't handle these!!
5392 else if (Cond.getOpcode() == X86ISD::ADD ||
5393 Cond.getOpcode() == X86ISD::SUB ||
5394 Cond.getOpcode() == X86ISD::SMUL ||
5395 Cond.getOpcode() == X86ISD::UMUL)
5396 Cond = LowerXALUO(Cond, DAG);
5399 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5400 // setting operand in place of the X86ISD::SETCC.
5401 if (Cond.getOpcode() == X86ISD::SETCC) {
5402 CC = Cond.getOperand(0);
5404 SDValue Cmp = Cond.getOperand(1);
5405 unsigned Opc = Cmp.getOpcode();
5406 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5407 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5411 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5415 // These can only come from an arithmetic instruction with overflow,
5416 // e.g. SADDO, UADDO.
5417 Cond = Cond.getNode()->getOperand(1);
5424 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5425 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5426 if (CondOpc == ISD::OR) {
5427 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5428 // two branches instead of an explicit OR instruction with a
5430 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5431 isX86LogicalCmp(Cmp)) {
5432 CC = Cond.getOperand(0).getOperand(0);
5433 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5434 Chain, Dest, CC, Cmp);
5435 CC = Cond.getOperand(1).getOperand(0);
5439 } else { // ISD::AND
5440 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5441 // two branches instead of an explicit AND instruction with a
5442 // separate test. However, we only do this if this block doesn't
5443 // have a fall-through edge, because this requires an explicit
5444 // jmp when the condition is false.
5445 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5446 isX86LogicalCmp(Cmp) &&
5447 Op.getNode()->hasOneUse()) {
5448 X86::CondCode CCode =
5449 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5450 CCode = X86::GetOppositeBranchCondition(CCode);
5451 CC = DAG.getConstant(CCode, MVT::i8);
5452 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5453 // Look for an unconditional branch following this conditional branch.
5454 // We need this because we need to reverse the successors in order
5455 // to implement FCMP_OEQ.
5456 if (User.getOpcode() == ISD::BR) {
5457 SDValue FalseBB = User.getOperand(1);
5459 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5460 assert(NewBR == User);
5463 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5464 Chain, Dest, CC, Cmp);
5465 X86::CondCode CCode =
5466 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5467 CCode = X86::GetOppositeBranchCondition(CCode);
5468 CC = DAG.getConstant(CCode, MVT::i8);
5474 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5475 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5476 // It should be transformed during dag combiner except when the condition
5477 // is set by a arithmetics with overflow node.
5478 X86::CondCode CCode =
5479 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5480 CCode = X86::GetOppositeBranchCondition(CCode);
5481 CC = DAG.getConstant(CCode, MVT::i8);
5482 Cond = Cond.getOperand(0).getOperand(1);
5488 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5489 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5491 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5492 Chain, Dest, CC, Cond);
5496 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5497 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5498 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5499 // that the guard pages used by the OS virtual memory manager are allocated in
5500 // correct sequence.
5502 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5503 SelectionDAG &DAG) {
5504 assert(Subtarget->isTargetCygMing() &&
5505 "This should be used only on Cygwin/Mingw targets");
5506 DebugLoc dl = Op.getDebugLoc();
5509 SDValue Chain = Op.getOperand(0);
5510 SDValue Size = Op.getOperand(1);
5511 // FIXME: Ensure alignment here
5515 MVT IntPtr = getPointerTy();
5516 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5518 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5520 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5521 Flag = Chain.getValue(1);
5523 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5524 SDValue Ops[] = { Chain,
5525 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5526 DAG.getRegister(X86::EAX, IntPtr),
5527 DAG.getRegister(X86StackPtr, SPTy),
5529 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5530 Flag = Chain.getValue(1);
5532 Chain = DAG.getCALLSEQ_END(Chain,
5533 DAG.getIntPtrConstant(0, true),
5534 DAG.getIntPtrConstant(0, true),
5537 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5539 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5540 return DAG.getMergeValues(Ops1, 2, dl);
5544 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5546 SDValue Dst, SDValue Src,
5547 SDValue Size, unsigned Align,
5549 uint64_t DstSVOff) {
5550 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5552 // If not DWORD aligned or size is more than the threshold, call the library.
5553 // The libc version is likely to be faster for these cases. It can use the
5554 // address value and run time information about the CPU.
5555 if ((Align & 3) != 0 ||
5557 ConstantSize->getZExtValue() >
5558 getSubtarget()->getMaxInlineSizeThreshold()) {
5559 SDValue InFlag(0, 0);
5561 // Check to see if there is a specialized entry-point for memory zeroing.
5562 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5564 if (const char *bzeroEntry = V &&
5565 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5566 MVT IntPtr = getPointerTy();
5567 const Type *IntPtrTy = TD->getIntPtrType();
5568 TargetLowering::ArgListTy Args;
5569 TargetLowering::ArgListEntry Entry;
5571 Entry.Ty = IntPtrTy;
5572 Args.push_back(Entry);
5574 Args.push_back(Entry);
5575 std::pair<SDValue,SDValue> CallResult =
5576 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5577 CallingConv::C, false,
5578 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5579 return CallResult.second;
5582 // Otherwise have the target-independent code call memset.
5586 uint64_t SizeVal = ConstantSize->getZExtValue();
5587 SDValue InFlag(0, 0);
5590 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5591 unsigned BytesLeft = 0;
5592 bool TwoRepStos = false;
5595 uint64_t Val = ValC->getZExtValue() & 255;
5597 // If the value is a constant, then we can potentially use larger sets.
5598 switch (Align & 3) {
5599 case 2: // WORD aligned
5602 Val = (Val << 8) | Val;
5604 case 0: // DWORD aligned
5607 Val = (Val << 8) | Val;
5608 Val = (Val << 16) | Val;
5609 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5612 Val = (Val << 32) | Val;
5615 default: // Byte aligned
5618 Count = DAG.getIntPtrConstant(SizeVal);
5622 if (AVT.bitsGT(MVT::i8)) {
5623 unsigned UBytes = AVT.getSizeInBits() / 8;
5624 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5625 BytesLeft = SizeVal % UBytes;
5628 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
5630 InFlag = Chain.getValue(1);
5633 Count = DAG.getIntPtrConstant(SizeVal);
5634 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
5635 InFlag = Chain.getValue(1);
5638 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5641 InFlag = Chain.getValue(1);
5642 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5645 InFlag = Chain.getValue(1);
5647 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5648 SmallVector<SDValue, 8> Ops;
5649 Ops.push_back(Chain);
5650 Ops.push_back(DAG.getValueType(AVT));
5651 Ops.push_back(InFlag);
5652 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5655 InFlag = Chain.getValue(1);
5657 MVT CVT = Count.getValueType();
5658 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
5659 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5660 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
5663 InFlag = Chain.getValue(1);
5664 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5666 Ops.push_back(Chain);
5667 Ops.push_back(DAG.getValueType(MVT::i8));
5668 Ops.push_back(InFlag);
5669 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5670 } else if (BytesLeft) {
5671 // Handle the last 1 - 7 bytes.
5672 unsigned Offset = SizeVal - BytesLeft;
5673 MVT AddrVT = Dst.getValueType();
5674 MVT SizeVT = Size.getValueType();
5676 Chain = DAG.getMemset(Chain, dl,
5677 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
5678 DAG.getConstant(Offset, AddrVT)),
5680 DAG.getConstant(BytesLeft, SizeVT),
5681 Align, DstSV, DstSVOff + Offset);
5684 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5689 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
5690 SDValue Chain, SDValue Dst, SDValue Src,
5691 SDValue Size, unsigned Align,
5693 const Value *DstSV, uint64_t DstSVOff,
5694 const Value *SrcSV, uint64_t SrcSVOff) {
5695 // This requires the copy size to be a constant, preferrably
5696 // within a subtarget-specific limit.
5697 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5700 uint64_t SizeVal = ConstantSize->getZExtValue();
5701 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5704 /// If not DWORD aligned, call the library.
5705 if ((Align & 3) != 0)
5710 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5713 unsigned UBytes = AVT.getSizeInBits() / 8;
5714 unsigned CountVal = SizeVal / UBytes;
5715 SDValue Count = DAG.getIntPtrConstant(CountVal);
5716 unsigned BytesLeft = SizeVal % UBytes;
5718 SDValue InFlag(0, 0);
5719 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5722 InFlag = Chain.getValue(1);
5723 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5726 InFlag = Chain.getValue(1);
5727 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
5730 InFlag = Chain.getValue(1);
5732 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5733 SmallVector<SDValue, 8> Ops;
5734 Ops.push_back(Chain);
5735 Ops.push_back(DAG.getValueType(AVT));
5736 Ops.push_back(InFlag);
5737 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
5739 SmallVector<SDValue, 4> Results;
5740 Results.push_back(RepMovs);
5742 // Handle the last 1 - 7 bytes.
5743 unsigned Offset = SizeVal - BytesLeft;
5744 MVT DstVT = Dst.getValueType();
5745 MVT SrcVT = Src.getValueType();
5746 MVT SizeVT = Size.getValueType();
5747 Results.push_back(DAG.getMemcpy(Chain, dl,
5748 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
5749 DAG.getConstant(Offset, DstVT)),
5750 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
5751 DAG.getConstant(Offset, SrcVT)),
5752 DAG.getConstant(BytesLeft, SizeVT),
5753 Align, AlwaysInline,
5754 DstSV, DstSVOff + Offset,
5755 SrcSV, SrcSVOff + Offset));
5758 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5759 &Results[0], Results.size());
5762 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5763 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5764 DebugLoc dl = Op.getDebugLoc();
5766 if (!Subtarget->is64Bit()) {
5767 // vastart just stores the address of the VarArgsFrameIndex slot into the
5768 // memory location argument.
5769 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5770 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
5774 // gp_offset (0 - 6 * 8)
5775 // fp_offset (48 - 48 + 8 * 16)
5776 // overflow_arg_area (point to parameters coming in memory).
5778 SmallVector<SDValue, 8> MemOps;
5779 SDValue FIN = Op.getOperand(1);
5781 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
5782 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5784 MemOps.push_back(Store);
5787 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5788 FIN, DAG.getIntPtrConstant(4));
5789 Store = DAG.getStore(Op.getOperand(0), dl,
5790 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5792 MemOps.push_back(Store);
5794 // Store ptr to overflow_arg_area
5795 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5796 FIN, DAG.getIntPtrConstant(4));
5797 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5798 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
5799 MemOps.push_back(Store);
5801 // Store ptr to reg_save_area.
5802 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5803 FIN, DAG.getIntPtrConstant(8));
5804 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5805 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
5806 MemOps.push_back(Store);
5807 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5808 &MemOps[0], MemOps.size());
5811 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5812 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5813 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5814 SDValue Chain = Op.getOperand(0);
5815 SDValue SrcPtr = Op.getOperand(1);
5816 SDValue SrcSV = Op.getOperand(2);
5818 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5823 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5824 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5825 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5826 SDValue Chain = Op.getOperand(0);
5827 SDValue DstPtr = Op.getOperand(1);
5828 SDValue SrcPtr = Op.getOperand(2);
5829 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5830 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5831 DebugLoc dl = Op.getDebugLoc();
5833 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
5834 DAG.getIntPtrConstant(24), 8, false,
5835 DstSV, 0, SrcSV, 0);
5839 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5840 DebugLoc dl = Op.getDebugLoc();
5841 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5843 default: return SDValue(); // Don't custom lower most intrinsics.
5844 // Comparison intrinsics.
5845 case Intrinsic::x86_sse_comieq_ss:
5846 case Intrinsic::x86_sse_comilt_ss:
5847 case Intrinsic::x86_sse_comile_ss:
5848 case Intrinsic::x86_sse_comigt_ss:
5849 case Intrinsic::x86_sse_comige_ss:
5850 case Intrinsic::x86_sse_comineq_ss:
5851 case Intrinsic::x86_sse_ucomieq_ss:
5852 case Intrinsic::x86_sse_ucomilt_ss:
5853 case Intrinsic::x86_sse_ucomile_ss:
5854 case Intrinsic::x86_sse_ucomigt_ss:
5855 case Intrinsic::x86_sse_ucomige_ss:
5856 case Intrinsic::x86_sse_ucomineq_ss:
5857 case Intrinsic::x86_sse2_comieq_sd:
5858 case Intrinsic::x86_sse2_comilt_sd:
5859 case Intrinsic::x86_sse2_comile_sd:
5860 case Intrinsic::x86_sse2_comigt_sd:
5861 case Intrinsic::x86_sse2_comige_sd:
5862 case Intrinsic::x86_sse2_comineq_sd:
5863 case Intrinsic::x86_sse2_ucomieq_sd:
5864 case Intrinsic::x86_sse2_ucomilt_sd:
5865 case Intrinsic::x86_sse2_ucomile_sd:
5866 case Intrinsic::x86_sse2_ucomigt_sd:
5867 case Intrinsic::x86_sse2_ucomige_sd:
5868 case Intrinsic::x86_sse2_ucomineq_sd: {
5870 ISD::CondCode CC = ISD::SETCC_INVALID;
5873 case Intrinsic::x86_sse_comieq_ss:
5874 case Intrinsic::x86_sse2_comieq_sd:
5878 case Intrinsic::x86_sse_comilt_ss:
5879 case Intrinsic::x86_sse2_comilt_sd:
5883 case Intrinsic::x86_sse_comile_ss:
5884 case Intrinsic::x86_sse2_comile_sd:
5888 case Intrinsic::x86_sse_comigt_ss:
5889 case Intrinsic::x86_sse2_comigt_sd:
5893 case Intrinsic::x86_sse_comige_ss:
5894 case Intrinsic::x86_sse2_comige_sd:
5898 case Intrinsic::x86_sse_comineq_ss:
5899 case Intrinsic::x86_sse2_comineq_sd:
5903 case Intrinsic::x86_sse_ucomieq_ss:
5904 case Intrinsic::x86_sse2_ucomieq_sd:
5905 Opc = X86ISD::UCOMI;
5908 case Intrinsic::x86_sse_ucomilt_ss:
5909 case Intrinsic::x86_sse2_ucomilt_sd:
5910 Opc = X86ISD::UCOMI;
5913 case Intrinsic::x86_sse_ucomile_ss:
5914 case Intrinsic::x86_sse2_ucomile_sd:
5915 Opc = X86ISD::UCOMI;
5918 case Intrinsic::x86_sse_ucomigt_ss:
5919 case Intrinsic::x86_sse2_ucomigt_sd:
5920 Opc = X86ISD::UCOMI;
5923 case Intrinsic::x86_sse_ucomige_ss:
5924 case Intrinsic::x86_sse2_ucomige_sd:
5925 Opc = X86ISD::UCOMI;
5928 case Intrinsic::x86_sse_ucomineq_ss:
5929 case Intrinsic::x86_sse2_ucomineq_sd:
5930 Opc = X86ISD::UCOMI;
5935 SDValue LHS = Op.getOperand(1);
5936 SDValue RHS = Op.getOperand(2);
5937 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
5938 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
5939 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5940 DAG.getConstant(X86CC, MVT::i8), Cond);
5941 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
5944 // Fix vector shift instructions where the last operand is a non-immediate
5946 case Intrinsic::x86_sse2_pslli_w:
5947 case Intrinsic::x86_sse2_pslli_d:
5948 case Intrinsic::x86_sse2_pslli_q:
5949 case Intrinsic::x86_sse2_psrli_w:
5950 case Intrinsic::x86_sse2_psrli_d:
5951 case Intrinsic::x86_sse2_psrli_q:
5952 case Intrinsic::x86_sse2_psrai_w:
5953 case Intrinsic::x86_sse2_psrai_d:
5954 case Intrinsic::x86_mmx_pslli_w:
5955 case Intrinsic::x86_mmx_pslli_d:
5956 case Intrinsic::x86_mmx_pslli_q:
5957 case Intrinsic::x86_mmx_psrli_w:
5958 case Intrinsic::x86_mmx_psrli_d:
5959 case Intrinsic::x86_mmx_psrli_q:
5960 case Intrinsic::x86_mmx_psrai_w:
5961 case Intrinsic::x86_mmx_psrai_d: {
5962 SDValue ShAmt = Op.getOperand(2);
5963 if (isa<ConstantSDNode>(ShAmt))
5966 unsigned NewIntNo = 0;
5967 MVT ShAmtVT = MVT::v4i32;
5969 case Intrinsic::x86_sse2_pslli_w:
5970 NewIntNo = Intrinsic::x86_sse2_psll_w;
5972 case Intrinsic::x86_sse2_pslli_d:
5973 NewIntNo = Intrinsic::x86_sse2_psll_d;
5975 case Intrinsic::x86_sse2_pslli_q:
5976 NewIntNo = Intrinsic::x86_sse2_psll_q;
5978 case Intrinsic::x86_sse2_psrli_w:
5979 NewIntNo = Intrinsic::x86_sse2_psrl_w;
5981 case Intrinsic::x86_sse2_psrli_d:
5982 NewIntNo = Intrinsic::x86_sse2_psrl_d;
5984 case Intrinsic::x86_sse2_psrli_q:
5985 NewIntNo = Intrinsic::x86_sse2_psrl_q;
5987 case Intrinsic::x86_sse2_psrai_w:
5988 NewIntNo = Intrinsic::x86_sse2_psra_w;
5990 case Intrinsic::x86_sse2_psrai_d:
5991 NewIntNo = Intrinsic::x86_sse2_psra_d;
5994 ShAmtVT = MVT::v2i32;
5996 case Intrinsic::x86_mmx_pslli_w:
5997 NewIntNo = Intrinsic::x86_mmx_psll_w;
5999 case Intrinsic::x86_mmx_pslli_d:
6000 NewIntNo = Intrinsic::x86_mmx_psll_d;
6002 case Intrinsic::x86_mmx_pslli_q:
6003 NewIntNo = Intrinsic::x86_mmx_psll_q;
6005 case Intrinsic::x86_mmx_psrli_w:
6006 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6008 case Intrinsic::x86_mmx_psrli_d:
6009 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6011 case Intrinsic::x86_mmx_psrli_q:
6012 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6014 case Intrinsic::x86_mmx_psrai_w:
6015 NewIntNo = Intrinsic::x86_mmx_psra_w;
6017 case Intrinsic::x86_mmx_psrai_d:
6018 NewIntNo = Intrinsic::x86_mmx_psra_d;
6020 default: abort(); // Can't reach here.
6025 MVT VT = Op.getValueType();
6026 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6027 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6028 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6029 DAG.getConstant(NewIntNo, MVT::i32),
6030 Op.getOperand(1), ShAmt);
6035 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6036 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6037 DebugLoc dl = Op.getDebugLoc();
6040 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6042 DAG.getConstant(TD->getPointerSize(),
6043 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6044 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6045 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6050 // Just load the return address.
6051 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6052 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6053 RetAddrFI, NULL, 0);
6056 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6057 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6058 MFI->setFrameAddressIsTaken(true);
6059 MVT VT = Op.getValueType();
6060 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6061 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6062 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6063 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6065 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6069 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6070 SelectionDAG &DAG) {
6071 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6074 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6076 MachineFunction &MF = DAG.getMachineFunction();
6077 SDValue Chain = Op.getOperand(0);
6078 SDValue Offset = Op.getOperand(1);
6079 SDValue Handler = Op.getOperand(2);
6080 DebugLoc dl = Op.getDebugLoc();
6082 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6084 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6086 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6087 DAG.getIntPtrConstant(-TD->getPointerSize()));
6088 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6089 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6090 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6091 MF.getRegInfo().addLiveOut(StoreAddrReg);
6093 return DAG.getNode(X86ISD::EH_RETURN, dl,
6095 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6098 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6099 SelectionDAG &DAG) {
6100 SDValue Root = Op.getOperand(0);
6101 SDValue Trmp = Op.getOperand(1); // trampoline
6102 SDValue FPtr = Op.getOperand(2); // nested function
6103 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6104 DebugLoc dl = Op.getDebugLoc();
6106 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6108 const X86InstrInfo *TII =
6109 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6111 if (Subtarget->is64Bit()) {
6112 SDValue OutChains[6];
6114 // Large code-model.
6116 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6117 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6119 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6120 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6122 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6124 // Load the pointer to the nested function into R11.
6125 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6126 SDValue Addr = Trmp;
6127 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6130 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6131 DAG.getConstant(2, MVT::i64));
6132 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6134 // Load the 'nest' parameter value into R10.
6135 // R10 is specified in X86CallingConv.td
6136 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6137 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6138 DAG.getConstant(10, MVT::i64));
6139 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6140 Addr, TrmpAddr, 10);
6142 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6143 DAG.getConstant(12, MVT::i64));
6144 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6146 // Jump to the nested function.
6147 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6148 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6149 DAG.getConstant(20, MVT::i64));
6150 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6151 Addr, TrmpAddr, 20);
6153 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6154 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6155 DAG.getConstant(22, MVT::i64));
6156 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6160 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6161 return DAG.getMergeValues(Ops, 2, dl);
6163 const Function *Func =
6164 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6165 unsigned CC = Func->getCallingConv();
6170 assert(0 && "Unsupported calling convention");
6171 case CallingConv::C:
6172 case CallingConv::X86_StdCall: {
6173 // Pass 'nest' parameter in ECX.
6174 // Must be kept in sync with X86CallingConv.td
6177 // Check that ECX wasn't needed by an 'inreg' parameter.
6178 const FunctionType *FTy = Func->getFunctionType();
6179 const AttrListPtr &Attrs = Func->getAttributes();
6181 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6182 unsigned InRegCount = 0;
6185 for (FunctionType::param_iterator I = FTy->param_begin(),
6186 E = FTy->param_end(); I != E; ++I, ++Idx)
6187 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6188 // FIXME: should only count parameters that are lowered to integers.
6189 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6191 if (InRegCount > 2) {
6192 cerr << "Nest register in use - reduce number of inreg parameters!\n";
6198 case CallingConv::X86_FastCall:
6199 case CallingConv::Fast:
6200 // Pass 'nest' parameter in EAX.
6201 // Must be kept in sync with X86CallingConv.td
6206 SDValue OutChains[4];
6209 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6210 DAG.getConstant(10, MVT::i32));
6211 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6213 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6214 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6215 OutChains[0] = DAG.getStore(Root, dl,
6216 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6219 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6220 DAG.getConstant(1, MVT::i32));
6221 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6223 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6224 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6225 DAG.getConstant(5, MVT::i32));
6226 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6227 TrmpAddr, 5, false, 1);
6229 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6230 DAG.getConstant(6, MVT::i32));
6231 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6234 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6235 return DAG.getMergeValues(Ops, 2, dl);
6239 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6241 The rounding mode is in bits 11:10 of FPSR, and has the following
6248 FLT_ROUNDS, on the other hand, expects the following:
6255 To perform the conversion, we do:
6256 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6259 MachineFunction &MF = DAG.getMachineFunction();
6260 const TargetMachine &TM = MF.getTarget();
6261 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6262 unsigned StackAlignment = TFI.getStackAlignment();
6263 MVT VT = Op.getValueType();
6264 DebugLoc dl = Op.getDebugLoc();
6266 // Save FP Control Word to stack slot
6267 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6268 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6270 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6271 DAG.getEntryNode(), StackSlot);
6273 // Load FP Control Word from stack slot
6274 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6276 // Transform as necessary
6278 DAG.getNode(ISD::SRL, dl, MVT::i16,
6279 DAG.getNode(ISD::AND, dl, MVT::i16,
6280 CWD, DAG.getConstant(0x800, MVT::i16)),
6281 DAG.getConstant(11, MVT::i8));
6283 DAG.getNode(ISD::SRL, dl, MVT::i16,
6284 DAG.getNode(ISD::AND, dl, MVT::i16,
6285 CWD, DAG.getConstant(0x400, MVT::i16)),
6286 DAG.getConstant(9, MVT::i8));
6289 DAG.getNode(ISD::AND, dl, MVT::i16,
6290 DAG.getNode(ISD::ADD, dl, MVT::i16,
6291 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6292 DAG.getConstant(1, MVT::i16)),
6293 DAG.getConstant(3, MVT::i16));
6296 return DAG.getNode((VT.getSizeInBits() < 16 ?
6297 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6300 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6301 MVT VT = Op.getValueType();
6303 unsigned NumBits = VT.getSizeInBits();
6304 DebugLoc dl = Op.getDebugLoc();
6306 Op = Op.getOperand(0);
6307 if (VT == MVT::i8) {
6308 // Zero extend to i32 since there is not an i8 bsr.
6310 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6313 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6314 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6315 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6317 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6318 SmallVector<SDValue, 4> Ops;
6320 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6321 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6322 Ops.push_back(Op.getValue(1));
6323 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6325 // Finally xor with NumBits-1.
6326 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6329 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6333 SDValue X86TargetLowering::LowerCTTZ(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) {
6342 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6345 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6346 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6347 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6349 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6350 SmallVector<SDValue, 4> Ops;
6352 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6353 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6354 Ops.push_back(Op.getValue(1));
6355 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6358 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6362 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6363 MVT VT = Op.getValueType();
6364 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6365 DebugLoc dl = Op.getDebugLoc();
6367 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6368 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6369 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6370 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6371 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6373 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6374 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6375 // return AloBlo + AloBhi + AhiBlo;
6377 SDValue A = Op.getOperand(0);
6378 SDValue B = Op.getOperand(1);
6380 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6381 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6382 A, DAG.getConstant(32, MVT::i32));
6383 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6384 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6385 B, DAG.getConstant(32, MVT::i32));
6386 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6387 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6389 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6390 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6392 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6393 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6395 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6396 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6397 AloBhi, DAG.getConstant(32, MVT::i32));
6398 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6399 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6400 AhiBlo, DAG.getConstant(32, MVT::i32));
6401 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6402 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6407 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6408 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6409 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6410 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6411 // has only one use.
6412 SDNode *N = Op.getNode();
6413 SDValue LHS = N->getOperand(0);
6414 SDValue RHS = N->getOperand(1);
6415 unsigned BaseOp = 0;
6417 DebugLoc dl = Op.getDebugLoc();
6419 switch (Op.getOpcode()) {
6420 default: assert(0 && "Unknown ovf instruction!");
6422 // A subtract of one will be selected as a INC. Note that INC doesn't
6423 // set CF, so we can't do this for UADDO.
6424 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6425 if (C->getAPIntValue() == 1) {
6426 BaseOp = X86ISD::INC;
6430 BaseOp = X86ISD::ADD;
6434 BaseOp = X86ISD::ADD;
6438 // A subtract of one will be selected as a DEC. Note that DEC doesn't
6439 // set CF, so we can't do this for USUBO.
6440 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6441 if (C->getAPIntValue() == 1) {
6442 BaseOp = X86ISD::DEC;
6446 BaseOp = X86ISD::SUB;
6450 BaseOp = X86ISD::SUB;
6454 BaseOp = X86ISD::SMUL;
6458 BaseOp = X86ISD::UMUL;
6463 // Also sets EFLAGS.
6464 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6465 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6468 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6469 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6471 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6475 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6476 MVT T = Op.getValueType();
6477 DebugLoc dl = Op.getDebugLoc();
6480 switch(T.getSimpleVT()) {
6482 assert(false && "Invalid value type!");
6483 case MVT::i8: Reg = X86::AL; size = 1; break;
6484 case MVT::i16: Reg = X86::AX; size = 2; break;
6485 case MVT::i32: Reg = X86::EAX; size = 4; break;
6487 assert(Subtarget->is64Bit() && "Node not type legal!");
6488 Reg = X86::RAX; size = 8;
6491 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6492 Op.getOperand(2), SDValue());
6493 SDValue Ops[] = { cpIn.getValue(0),
6496 DAG.getTargetConstant(size, MVT::i8),
6498 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6499 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6501 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6505 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6506 SelectionDAG &DAG) {
6507 assert(Subtarget->is64Bit() && "Result not type legalized?");
6508 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6509 SDValue TheChain = Op.getOperand(0);
6510 DebugLoc dl = Op.getDebugLoc();
6511 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6512 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6513 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6515 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6516 DAG.getConstant(32, MVT::i8));
6518 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6521 return DAG.getMergeValues(Ops, 2, dl);
6524 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6525 SDNode *Node = Op.getNode();
6526 DebugLoc dl = Node->getDebugLoc();
6527 MVT T = Node->getValueType(0);
6528 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6529 DAG.getConstant(0, T), Node->getOperand(2));
6530 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6531 cast<AtomicSDNode>(Node)->getMemoryVT(),
6532 Node->getOperand(0),
6533 Node->getOperand(1), negOp,
6534 cast<AtomicSDNode>(Node)->getSrcValue(),
6535 cast<AtomicSDNode>(Node)->getAlignment());
6538 /// LowerOperation - Provide custom lowering hooks for some operations.
6540 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6541 switch (Op.getOpcode()) {
6542 default: assert(0 && "Should not custom lower this!");
6543 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6544 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6545 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6546 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6547 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6548 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6549 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6550 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6551 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6552 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6553 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6554 case ISD::SHL_PARTS:
6555 case ISD::SRA_PARTS:
6556 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6557 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6558 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6559 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6560 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
6561 case ISD::FABS: return LowerFABS(Op, DAG);
6562 case ISD::FNEG: return LowerFNEG(Op, DAG);
6563 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6564 case ISD::SETCC: return LowerSETCC(Op, DAG);
6565 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6566 case ISD::SELECT: return LowerSELECT(Op, DAG);
6567 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6568 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6569 case ISD::CALL: return LowerCALL(Op, DAG);
6570 case ISD::RET: return LowerRET(Op, DAG);
6571 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6572 case ISD::VASTART: return LowerVASTART(Op, DAG);
6573 case ISD::VAARG: return LowerVAARG(Op, DAG);
6574 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6575 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6576 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6577 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6578 case ISD::FRAME_TO_ARGS_OFFSET:
6579 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6580 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6581 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6582 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6583 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6584 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6585 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6586 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6592 case ISD::UMULO: return LowerXALUO(Op, DAG);
6593 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6597 void X86TargetLowering::
6598 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6599 SelectionDAG &DAG, unsigned NewOp) {
6600 MVT T = Node->getValueType(0);
6601 DebugLoc dl = Node->getDebugLoc();
6602 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6604 SDValue Chain = Node->getOperand(0);
6605 SDValue In1 = Node->getOperand(1);
6606 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6607 Node->getOperand(2), DAG.getIntPtrConstant(0));
6608 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6609 Node->getOperand(2), DAG.getIntPtrConstant(1));
6610 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6611 // have a MemOperand. Pass the info through as a normal operand.
6612 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6613 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6614 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6615 SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6616 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6617 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6618 Results.push_back(Result.getValue(2));
6621 /// ReplaceNodeResults - Replace a node with an illegal result type
6622 /// with a new node built out of custom code.
6623 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6624 SmallVectorImpl<SDValue>&Results,
6625 SelectionDAG &DAG) {
6626 DebugLoc dl = N->getDebugLoc();
6627 switch (N->getOpcode()) {
6629 assert(false && "Do not know how to custom type legalize this operation!");
6631 case ISD::FP_TO_SINT: {
6632 std::pair<SDValue,SDValue> Vals =
6633 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
6634 SDValue FIST = Vals.first, StackSlot = Vals.second;
6635 if (FIST.getNode() != 0) {
6636 MVT VT = N->getValueType(0);
6637 // Return a load from the stack slot.
6638 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
6642 case ISD::READCYCLECOUNTER: {
6643 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6644 SDValue TheChain = N->getOperand(0);
6645 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6646 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
6648 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
6650 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6651 SDValue Ops[] = { eax, edx };
6652 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
6653 Results.push_back(edx.getValue(1));
6656 case ISD::ATOMIC_CMP_SWAP: {
6657 MVT T = N->getValueType(0);
6658 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6659 SDValue cpInL, cpInH;
6660 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6661 DAG.getConstant(0, MVT::i32));
6662 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6663 DAG.getConstant(1, MVT::i32));
6664 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
6665 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
6667 SDValue swapInL, swapInH;
6668 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6669 DAG.getConstant(0, MVT::i32));
6670 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6671 DAG.getConstant(1, MVT::i32));
6672 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
6674 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
6675 swapInL.getValue(1));
6676 SDValue Ops[] = { swapInH.getValue(0),
6678 swapInH.getValue(1) };
6679 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6680 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
6681 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
6682 MVT::i32, Result.getValue(1));
6683 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
6684 MVT::i32, cpOutL.getValue(2));
6685 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6686 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6687 Results.push_back(cpOutH.getValue(1));
6690 case ISD::ATOMIC_LOAD_ADD:
6691 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6693 case ISD::ATOMIC_LOAD_AND:
6694 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6696 case ISD::ATOMIC_LOAD_NAND:
6697 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6699 case ISD::ATOMIC_LOAD_OR:
6700 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6702 case ISD::ATOMIC_LOAD_SUB:
6703 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6705 case ISD::ATOMIC_LOAD_XOR:
6706 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6708 case ISD::ATOMIC_SWAP:
6709 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6714 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6716 default: return NULL;
6717 case X86ISD::BSF: return "X86ISD::BSF";
6718 case X86ISD::BSR: return "X86ISD::BSR";
6719 case X86ISD::SHLD: return "X86ISD::SHLD";
6720 case X86ISD::SHRD: return "X86ISD::SHRD";
6721 case X86ISD::FAND: return "X86ISD::FAND";
6722 case X86ISD::FOR: return "X86ISD::FOR";
6723 case X86ISD::FXOR: return "X86ISD::FXOR";
6724 case X86ISD::FSRL: return "X86ISD::FSRL";
6725 case X86ISD::FILD: return "X86ISD::FILD";
6726 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6727 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6728 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6729 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6730 case X86ISD::FLD: return "X86ISD::FLD";
6731 case X86ISD::FST: return "X86ISD::FST";
6732 case X86ISD::CALL: return "X86ISD::CALL";
6733 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6734 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6735 case X86ISD::BT: return "X86ISD::BT";
6736 case X86ISD::CMP: return "X86ISD::CMP";
6737 case X86ISD::COMI: return "X86ISD::COMI";
6738 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6739 case X86ISD::SETCC: return "X86ISD::SETCC";
6740 case X86ISD::CMOV: return "X86ISD::CMOV";
6741 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6742 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6743 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6744 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6745 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6746 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6747 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6748 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6749 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6750 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6751 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6752 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
6753 case X86ISD::FMAX: return "X86ISD::FMAX";
6754 case X86ISD::FMIN: return "X86ISD::FMIN";
6755 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6756 case X86ISD::FRCP: return "X86ISD::FRCP";
6757 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6758 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
6759 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6760 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6761 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6762 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6763 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6764 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
6765 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
6766 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
6767 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
6768 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
6769 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
6770 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6771 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6772 case X86ISD::VSHL: return "X86ISD::VSHL";
6773 case X86ISD::VSRL: return "X86ISD::VSRL";
6774 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6775 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6776 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6777 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6778 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6779 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6780 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6781 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6782 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6783 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6784 case X86ISD::ADD: return "X86ISD::ADD";
6785 case X86ISD::SUB: return "X86ISD::SUB";
6786 case X86ISD::SMUL: return "X86ISD::SMUL";
6787 case X86ISD::UMUL: return "X86ISD::UMUL";
6788 case X86ISD::INC: return "X86ISD::INC";
6789 case X86ISD::DEC: return "X86ISD::DEC";
6790 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
6794 // isLegalAddressingMode - Return true if the addressing mode represented
6795 // by AM is legal for this target, for a load/store of the specified type.
6796 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6797 const Type *Ty) const {
6798 // X86 supports extremely general addressing modes.
6800 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6801 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6805 // We can only fold this if we don't need an extra load.
6806 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6808 // If BaseGV requires a register, we cannot also have a BaseReg.
6809 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
6813 // X86-64 only supports addr of globals in small code model.
6814 if (Subtarget->is64Bit()) {
6815 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6817 // If lower 4G is not available, then we must use rip-relative addressing.
6818 if (AM.BaseOffs || AM.Scale > 1)
6829 // These scales always work.
6834 // These scales are formed with basereg+scalereg. Only accept if there is
6839 default: // Other stuff never works.
6847 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6848 if (!Ty1->isInteger() || !Ty2->isInteger())
6850 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6851 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6852 if (NumBits1 <= NumBits2)
6854 return Subtarget->is64Bit() || NumBits1 < 64;
6857 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6858 if (!VT1.isInteger() || !VT2.isInteger())
6860 unsigned NumBits1 = VT1.getSizeInBits();
6861 unsigned NumBits2 = VT2.getSizeInBits();
6862 if (NumBits1 <= NumBits2)
6864 return Subtarget->is64Bit() || NumBits1 < 64;
6867 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
6868 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
6869 return Ty1 == Type::Int32Ty && Ty2 == Type::Int64Ty && Subtarget->is64Bit();
6872 bool X86TargetLowering::isZExtFree(MVT VT1, MVT VT2) const {
6873 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
6874 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
6877 bool X86TargetLowering::isNarrowingProfitable(MVT VT1, MVT VT2) const {
6878 // i16 instructions are longer (0x66 prefix) and potentially slower.
6879 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
6882 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6883 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6884 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6885 /// are assumed to be legal.
6887 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6889 // Only do shuffles on 128-bit vector types for now.
6890 if (VT.getSizeInBits() == 64)
6893 // FIXME: pshufb, blends, palignr, shifts.
6894 return (VT.getVectorNumElements() == 2 ||
6895 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6896 isMOVLMask(M, VT) ||
6897 isSHUFPMask(M, VT) ||
6898 isPSHUFDMask(M, VT) ||
6899 isPSHUFHWMask(M, VT) ||
6900 isPSHUFLWMask(M, VT) ||
6901 isUNPCKLMask(M, VT) ||
6902 isUNPCKHMask(M, VT) ||
6903 isUNPCKL_v_undef_Mask(M, VT) ||
6904 isUNPCKH_v_undef_Mask(M, VT));
6908 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
6910 unsigned NumElts = VT.getVectorNumElements();
6911 // FIXME: This collection of masks seems suspect.
6914 if (NumElts == 4 && VT.getSizeInBits() == 128) {
6915 return (isMOVLMask(Mask, VT) ||
6916 isCommutedMOVLMask(Mask, VT, true) ||
6917 isSHUFPMask(Mask, VT) ||
6918 isCommutedSHUFPMask(Mask, VT));
6923 //===----------------------------------------------------------------------===//
6924 // X86 Scheduler Hooks
6925 //===----------------------------------------------------------------------===//
6927 // private utility function
6929 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6930 MachineBasicBlock *MBB,
6938 TargetRegisterClass *RC,
6939 bool invSrc) const {
6940 // For the atomic bitwise operator, we generate
6943 // ld t1 = [bitinstr.addr]
6944 // op t2 = t1, [bitinstr.val]
6946 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6948 // fallthrough -->nextMBB
6949 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6950 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6951 MachineFunction::iterator MBBIter = MBB;
6954 /// First build the CFG
6955 MachineFunction *F = MBB->getParent();
6956 MachineBasicBlock *thisMBB = MBB;
6957 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6958 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6959 F->insert(MBBIter, newMBB);
6960 F->insert(MBBIter, nextMBB);
6962 // Move all successors to thisMBB to nextMBB
6963 nextMBB->transferSuccessors(thisMBB);
6965 // Update thisMBB to fall through to newMBB
6966 thisMBB->addSuccessor(newMBB);
6968 // newMBB jumps to itself and fall through to nextMBB
6969 newMBB->addSuccessor(nextMBB);
6970 newMBB->addSuccessor(newMBB);
6972 // Insert instructions into newMBB based on incoming instruction
6973 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
6974 "unexpected number of operands");
6975 DebugLoc dl = bInstr->getDebugLoc();
6976 MachineOperand& destOper = bInstr->getOperand(0);
6977 MachineOperand* argOpers[2 + X86AddrNumOperands];
6978 int numArgs = bInstr->getNumOperands() - 1;
6979 for (int i=0; i < numArgs; ++i)
6980 argOpers[i] = &bInstr->getOperand(i+1);
6982 // x86 address has 4 operands: base, index, scale, and displacement
6983 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
6984 int valArgIndx = lastAddrIndx + 1;
6986 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6987 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
6988 for (int i=0; i <= lastAddrIndx; ++i)
6989 (*MIB).addOperand(*argOpers[i]);
6991 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
6993 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
6998 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6999 assert((argOpers[valArgIndx]->isReg() ||
7000 argOpers[valArgIndx]->isImm()) &&
7002 if (argOpers[valArgIndx]->isReg())
7003 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7005 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7007 (*MIB).addOperand(*argOpers[valArgIndx]);
7009 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7012 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7013 for (int i=0; i <= lastAddrIndx; ++i)
7014 (*MIB).addOperand(*argOpers[i]);
7016 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7017 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7019 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7023 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7025 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7029 // private utility function: 64 bit atomics on 32 bit host.
7031 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7032 MachineBasicBlock *MBB,
7037 bool invSrc) const {
7038 // For the atomic bitwise operator, we generate
7039 // thisMBB (instructions are in pairs, except cmpxchg8b)
7040 // ld t1,t2 = [bitinstr.addr]
7042 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7043 // op t5, t6 <- out1, out2, [bitinstr.val]
7044 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7045 // mov ECX, EBX <- t5, t6
7046 // mov EAX, EDX <- t1, t2
7047 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7048 // mov t3, t4 <- EAX, EDX
7050 // result in out1, out2
7051 // fallthrough -->nextMBB
7053 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7054 const unsigned LoadOpc = X86::MOV32rm;
7055 const unsigned copyOpc = X86::MOV32rr;
7056 const unsigned NotOpc = X86::NOT32r;
7057 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7058 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7059 MachineFunction::iterator MBBIter = MBB;
7062 /// First build the CFG
7063 MachineFunction *F = MBB->getParent();
7064 MachineBasicBlock *thisMBB = MBB;
7065 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7066 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7067 F->insert(MBBIter, newMBB);
7068 F->insert(MBBIter, nextMBB);
7070 // Move all successors to thisMBB to nextMBB
7071 nextMBB->transferSuccessors(thisMBB);
7073 // Update thisMBB to fall through to newMBB
7074 thisMBB->addSuccessor(newMBB);
7076 // newMBB jumps to itself and fall through to nextMBB
7077 newMBB->addSuccessor(nextMBB);
7078 newMBB->addSuccessor(newMBB);
7080 DebugLoc dl = bInstr->getDebugLoc();
7081 // Insert instructions into newMBB based on incoming instruction
7082 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7083 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7084 "unexpected number of operands");
7085 MachineOperand& dest1Oper = bInstr->getOperand(0);
7086 MachineOperand& dest2Oper = bInstr->getOperand(1);
7087 MachineOperand* argOpers[2 + X86AddrNumOperands];
7088 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7089 argOpers[i] = &bInstr->getOperand(i+2);
7091 // x86 address has 4 operands: base, index, scale, and displacement
7092 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7094 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7095 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7096 for (int i=0; i <= lastAddrIndx; ++i)
7097 (*MIB).addOperand(*argOpers[i]);
7098 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7099 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7100 // add 4 to displacement.
7101 for (int i=0; i <= lastAddrIndx-2; ++i)
7102 (*MIB).addOperand(*argOpers[i]);
7103 MachineOperand newOp3 = *(argOpers[3]);
7105 newOp3.setImm(newOp3.getImm()+4);
7107 newOp3.setOffset(newOp3.getOffset()+4);
7108 (*MIB).addOperand(newOp3);
7109 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7111 // t3/4 are defined later, at the bottom of the loop
7112 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7113 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7114 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7115 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7116 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7117 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7119 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7120 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7122 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7123 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7129 int valArgIndx = lastAddrIndx + 1;
7130 assert((argOpers[valArgIndx]->isReg() ||
7131 argOpers[valArgIndx]->isImm()) &&
7133 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7134 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7135 if (argOpers[valArgIndx]->isReg())
7136 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7138 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7139 if (regOpcL != X86::MOV32rr)
7141 (*MIB).addOperand(*argOpers[valArgIndx]);
7142 assert(argOpers[valArgIndx + 1]->isReg() ==
7143 argOpers[valArgIndx]->isReg());
7144 assert(argOpers[valArgIndx + 1]->isImm() ==
7145 argOpers[valArgIndx]->isImm());
7146 if (argOpers[valArgIndx + 1]->isReg())
7147 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7149 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7150 if (regOpcH != X86::MOV32rr)
7152 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7154 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7156 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7159 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7161 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7164 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7165 for (int i=0; i <= lastAddrIndx; ++i)
7166 (*MIB).addOperand(*argOpers[i]);
7168 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7169 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7171 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7172 MIB.addReg(X86::EAX);
7173 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7174 MIB.addReg(X86::EDX);
7177 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7179 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7183 // private utility function
7185 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7186 MachineBasicBlock *MBB,
7187 unsigned cmovOpc) const {
7188 // For the atomic min/max operator, we generate
7191 // ld t1 = [min/max.addr]
7192 // mov t2 = [min/max.val]
7194 // cmov[cond] t2 = t1
7196 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7198 // fallthrough -->nextMBB
7200 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7201 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7202 MachineFunction::iterator MBBIter = MBB;
7205 /// First build the CFG
7206 MachineFunction *F = MBB->getParent();
7207 MachineBasicBlock *thisMBB = MBB;
7208 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7209 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7210 F->insert(MBBIter, newMBB);
7211 F->insert(MBBIter, nextMBB);
7213 // Move all successors to thisMBB to nextMBB
7214 nextMBB->transferSuccessors(thisMBB);
7216 // Update thisMBB to fall through to newMBB
7217 thisMBB->addSuccessor(newMBB);
7219 // newMBB jumps to newMBB and fall through to nextMBB
7220 newMBB->addSuccessor(nextMBB);
7221 newMBB->addSuccessor(newMBB);
7223 DebugLoc dl = mInstr->getDebugLoc();
7224 // Insert instructions into newMBB based on incoming instruction
7225 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7226 "unexpected number of operands");
7227 MachineOperand& destOper = mInstr->getOperand(0);
7228 MachineOperand* argOpers[2 + X86AddrNumOperands];
7229 int numArgs = mInstr->getNumOperands() - 1;
7230 for (int i=0; i < numArgs; ++i)
7231 argOpers[i] = &mInstr->getOperand(i+1);
7233 // x86 address has 4 operands: base, index, scale, and displacement
7234 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7235 int valArgIndx = lastAddrIndx + 1;
7237 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7238 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7239 for (int i=0; i <= lastAddrIndx; ++i)
7240 (*MIB).addOperand(*argOpers[i]);
7242 // We only support register and immediate values
7243 assert((argOpers[valArgIndx]->isReg() ||
7244 argOpers[valArgIndx]->isImm()) &&
7247 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7248 if (argOpers[valArgIndx]->isReg())
7249 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7251 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7252 (*MIB).addOperand(*argOpers[valArgIndx]);
7254 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7257 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7262 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7263 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7267 // Cmp and exchange if none has modified the memory location
7268 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7269 for (int i=0; i <= lastAddrIndx; ++i)
7270 (*MIB).addOperand(*argOpers[i]);
7272 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7273 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7275 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7276 MIB.addReg(X86::EAX);
7279 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7281 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7287 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7288 MachineBasicBlock *BB) const {
7289 DebugLoc dl = MI->getDebugLoc();
7290 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7291 switch (MI->getOpcode()) {
7292 default: assert(false && "Unexpected instr type to insert");
7293 case X86::CMOV_V1I64:
7294 case X86::CMOV_FR32:
7295 case X86::CMOV_FR64:
7296 case X86::CMOV_V4F32:
7297 case X86::CMOV_V2F64:
7298 case X86::CMOV_V2I64: {
7299 // To "insert" a SELECT_CC instruction, we actually have to insert the
7300 // diamond control-flow pattern. The incoming instruction knows the
7301 // destination vreg to set, the condition code register to branch on, the
7302 // true/false values to select between, and a branch opcode to use.
7303 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7304 MachineFunction::iterator It = BB;
7310 // cmpTY ccX, r1, r2
7312 // fallthrough --> copy0MBB
7313 MachineBasicBlock *thisMBB = BB;
7314 MachineFunction *F = BB->getParent();
7315 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7316 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7318 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7319 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7320 F->insert(It, copy0MBB);
7321 F->insert(It, sinkMBB);
7322 // Update machine-CFG edges by transferring all successors of the current
7323 // block to the new block which will contain the Phi node for the select.
7324 sinkMBB->transferSuccessors(BB);
7326 // Add the true and fallthrough blocks as its successors.
7327 BB->addSuccessor(copy0MBB);
7328 BB->addSuccessor(sinkMBB);
7331 // %FalseValue = ...
7332 // # fallthrough to sinkMBB
7335 // Update machine-CFG edges
7336 BB->addSuccessor(sinkMBB);
7339 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7342 BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7343 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7344 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7346 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7350 case X86::FP32_TO_INT16_IN_MEM:
7351 case X86::FP32_TO_INT32_IN_MEM:
7352 case X86::FP32_TO_INT64_IN_MEM:
7353 case X86::FP64_TO_INT16_IN_MEM:
7354 case X86::FP64_TO_INT32_IN_MEM:
7355 case X86::FP64_TO_INT64_IN_MEM:
7356 case X86::FP80_TO_INT16_IN_MEM:
7357 case X86::FP80_TO_INT32_IN_MEM:
7358 case X86::FP80_TO_INT64_IN_MEM: {
7359 // Change the floating point control register to use "round towards zero"
7360 // mode when truncating to an integer value.
7361 MachineFunction *F = BB->getParent();
7362 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7363 addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7365 // Load the old value of the high byte of the control word...
7367 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7368 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7371 // Set the high part to be round to zero...
7372 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7375 // Reload the modified control word now...
7376 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7378 // Restore the memory image of control word to original value
7379 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7382 // Get the X86 opcode to use.
7384 switch (MI->getOpcode()) {
7385 default: assert(0 && "illegal opcode!");
7386 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7387 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7388 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7389 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7390 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7391 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7392 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7393 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7394 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7398 MachineOperand &Op = MI->getOperand(0);
7400 AM.BaseType = X86AddressMode::RegBase;
7401 AM.Base.Reg = Op.getReg();
7403 AM.BaseType = X86AddressMode::FrameIndexBase;
7404 AM.Base.FrameIndex = Op.getIndex();
7406 Op = MI->getOperand(1);
7408 AM.Scale = Op.getImm();
7409 Op = MI->getOperand(2);
7411 AM.IndexReg = Op.getImm();
7412 Op = MI->getOperand(3);
7413 if (Op.isGlobal()) {
7414 AM.GV = Op.getGlobal();
7416 AM.Disp = Op.getImm();
7418 addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7419 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
7421 // Reload the original control word now.
7422 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7424 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7427 case X86::ATOMAND32:
7428 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7429 X86::AND32ri, X86::MOV32rm,
7430 X86::LCMPXCHG32, X86::MOV32rr,
7431 X86::NOT32r, X86::EAX,
7432 X86::GR32RegisterClass);
7434 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7435 X86::OR32ri, X86::MOV32rm,
7436 X86::LCMPXCHG32, X86::MOV32rr,
7437 X86::NOT32r, X86::EAX,
7438 X86::GR32RegisterClass);
7439 case X86::ATOMXOR32:
7440 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7441 X86::XOR32ri, X86::MOV32rm,
7442 X86::LCMPXCHG32, X86::MOV32rr,
7443 X86::NOT32r, X86::EAX,
7444 X86::GR32RegisterClass);
7445 case X86::ATOMNAND32:
7446 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7447 X86::AND32ri, X86::MOV32rm,
7448 X86::LCMPXCHG32, X86::MOV32rr,
7449 X86::NOT32r, X86::EAX,
7450 X86::GR32RegisterClass, true);
7451 case X86::ATOMMIN32:
7452 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7453 case X86::ATOMMAX32:
7454 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7455 case X86::ATOMUMIN32:
7456 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7457 case X86::ATOMUMAX32:
7458 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7460 case X86::ATOMAND16:
7461 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7462 X86::AND16ri, X86::MOV16rm,
7463 X86::LCMPXCHG16, X86::MOV16rr,
7464 X86::NOT16r, X86::AX,
7465 X86::GR16RegisterClass);
7467 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7468 X86::OR16ri, X86::MOV16rm,
7469 X86::LCMPXCHG16, X86::MOV16rr,
7470 X86::NOT16r, X86::AX,
7471 X86::GR16RegisterClass);
7472 case X86::ATOMXOR16:
7473 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7474 X86::XOR16ri, X86::MOV16rm,
7475 X86::LCMPXCHG16, X86::MOV16rr,
7476 X86::NOT16r, X86::AX,
7477 X86::GR16RegisterClass);
7478 case X86::ATOMNAND16:
7479 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7480 X86::AND16ri, X86::MOV16rm,
7481 X86::LCMPXCHG16, X86::MOV16rr,
7482 X86::NOT16r, X86::AX,
7483 X86::GR16RegisterClass, true);
7484 case X86::ATOMMIN16:
7485 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7486 case X86::ATOMMAX16:
7487 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7488 case X86::ATOMUMIN16:
7489 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7490 case X86::ATOMUMAX16:
7491 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7494 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7495 X86::AND8ri, X86::MOV8rm,
7496 X86::LCMPXCHG8, X86::MOV8rr,
7497 X86::NOT8r, X86::AL,
7498 X86::GR8RegisterClass);
7500 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7501 X86::OR8ri, X86::MOV8rm,
7502 X86::LCMPXCHG8, X86::MOV8rr,
7503 X86::NOT8r, X86::AL,
7504 X86::GR8RegisterClass);
7506 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7507 X86::XOR8ri, X86::MOV8rm,
7508 X86::LCMPXCHG8, X86::MOV8rr,
7509 X86::NOT8r, X86::AL,
7510 X86::GR8RegisterClass);
7511 case X86::ATOMNAND8:
7512 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7513 X86::AND8ri, X86::MOV8rm,
7514 X86::LCMPXCHG8, X86::MOV8rr,
7515 X86::NOT8r, X86::AL,
7516 X86::GR8RegisterClass, true);
7517 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7518 // This group is for 64-bit host.
7519 case X86::ATOMAND64:
7520 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7521 X86::AND64ri32, X86::MOV64rm,
7522 X86::LCMPXCHG64, X86::MOV64rr,
7523 X86::NOT64r, X86::RAX,
7524 X86::GR64RegisterClass);
7526 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7527 X86::OR64ri32, X86::MOV64rm,
7528 X86::LCMPXCHG64, X86::MOV64rr,
7529 X86::NOT64r, X86::RAX,
7530 X86::GR64RegisterClass);
7531 case X86::ATOMXOR64:
7532 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7533 X86::XOR64ri32, X86::MOV64rm,
7534 X86::LCMPXCHG64, X86::MOV64rr,
7535 X86::NOT64r, X86::RAX,
7536 X86::GR64RegisterClass);
7537 case X86::ATOMNAND64:
7538 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7539 X86::AND64ri32, X86::MOV64rm,
7540 X86::LCMPXCHG64, X86::MOV64rr,
7541 X86::NOT64r, X86::RAX,
7542 X86::GR64RegisterClass, true);
7543 case X86::ATOMMIN64:
7544 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7545 case X86::ATOMMAX64:
7546 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7547 case X86::ATOMUMIN64:
7548 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7549 case X86::ATOMUMAX64:
7550 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7552 // This group does 64-bit operations on a 32-bit host.
7553 case X86::ATOMAND6432:
7554 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7555 X86::AND32rr, X86::AND32rr,
7556 X86::AND32ri, X86::AND32ri,
7558 case X86::ATOMOR6432:
7559 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7560 X86::OR32rr, X86::OR32rr,
7561 X86::OR32ri, X86::OR32ri,
7563 case X86::ATOMXOR6432:
7564 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7565 X86::XOR32rr, X86::XOR32rr,
7566 X86::XOR32ri, X86::XOR32ri,
7568 case X86::ATOMNAND6432:
7569 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7570 X86::AND32rr, X86::AND32rr,
7571 X86::AND32ri, X86::AND32ri,
7573 case X86::ATOMADD6432:
7574 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7575 X86::ADD32rr, X86::ADC32rr,
7576 X86::ADD32ri, X86::ADC32ri,
7578 case X86::ATOMSUB6432:
7579 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7580 X86::SUB32rr, X86::SBB32rr,
7581 X86::SUB32ri, X86::SBB32ri,
7583 case X86::ATOMSWAP6432:
7584 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7585 X86::MOV32rr, X86::MOV32rr,
7586 X86::MOV32ri, X86::MOV32ri,
7591 //===----------------------------------------------------------------------===//
7592 // X86 Optimization Hooks
7593 //===----------------------------------------------------------------------===//
7595 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7599 const SelectionDAG &DAG,
7600 unsigned Depth) const {
7601 unsigned Opc = Op.getOpcode();
7602 assert((Opc >= ISD::BUILTIN_OP_END ||
7603 Opc == ISD::INTRINSIC_WO_CHAIN ||
7604 Opc == ISD::INTRINSIC_W_CHAIN ||
7605 Opc == ISD::INTRINSIC_VOID) &&
7606 "Should use MaskedValueIsZero if you don't know whether Op"
7607 " is a target node!");
7609 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7618 // These nodes' second result is a boolean.
7619 if (Op.getResNo() == 0)
7623 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7624 Mask.getBitWidth() - 1);
7629 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7630 /// node is a GlobalAddress + offset.
7631 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7632 GlobalValue* &GA, int64_t &Offset) const{
7633 if (N->getOpcode() == X86ISD::Wrapper) {
7634 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7635 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7636 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7640 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7643 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7644 const TargetLowering &TLI) {
7647 if (TLI.isGAPlusOffset(Base, GV, Offset))
7648 return (GV->getAlignment() >= N && (Offset % N) == 0);
7649 // DAG combine handles the stack object case.
7653 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
7654 MVT EVT, SDNode *&Base,
7655 SelectionDAG &DAG, MachineFrameInfo *MFI,
7656 const TargetLowering &TLI) {
7658 for (unsigned i = 0; i < NumElems; ++i) {
7659 if (N->getMaskElt(i) < 0) {
7665 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7666 if (!Elt.getNode() ||
7667 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7670 Base = Elt.getNode();
7671 if (Base->getOpcode() == ISD::UNDEF)
7675 if (Elt.getOpcode() == ISD::UNDEF)
7678 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
7679 EVT.getSizeInBits()/8, i, MFI))
7685 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7686 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7687 /// if the load addresses are consecutive, non-overlapping, and in the right
7688 /// order. In the case of v2i64, it will see if it can rewrite the
7689 /// shuffle to be an appropriate build vector so it can take advantage of
7690 // performBuildVectorCombine.
7691 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7692 const TargetLowering &TLI) {
7693 DebugLoc dl = N->getDebugLoc();
7694 MVT VT = N->getValueType(0);
7695 MVT EVT = VT.getVectorElementType();
7696 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7697 unsigned NumElems = VT.getVectorNumElements();
7699 // For x86-32 machines, if we see an insert and then a shuffle in a v2i64
7700 // where the upper half is 0, it is advantageous to rewrite it as a build
7701 // vector of (0, val) so it can use movq.
7702 if (VT == MVT::v2i64) {
7704 In[0] = N->getOperand(0);
7705 In[1] = N->getOperand(1);
7706 int Idx0 = SVN->getMaskElt(0);
7707 int Idx1 = SVN->getMaskElt(1);
7708 // FIXME: can we take advantage of undef index?
7709 if (Idx0 >= 0 && Idx1 >= 0 &&
7710 In[Idx0/2].getOpcode() == ISD::INSERT_VECTOR_ELT &&
7711 In[Idx1/2].getOpcode() == ISD::BUILD_VECTOR) {
7712 ConstantSDNode* InsertVecIdx =
7713 dyn_cast<ConstantSDNode>(In[Idx0/2].getOperand(2));
7715 InsertVecIdx->getZExtValue() == (unsigned)(Idx0 % 2) &&
7716 isZeroNode(In[Idx1/2].getOperand(Idx1 % 2))) {
7717 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7718 In[Idx0/2].getOperand(1),
7719 In[Idx1/2].getOperand(Idx1 % 2));
7724 // Try to combine a vector_shuffle into a 128-bit load.
7725 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7726 SDNode *Base = NULL;
7727 if (!EltsFromConsecutiveLoads(SVN, NumElems, EVT, Base, DAG, MFI, TLI))
7730 LoadSDNode *LD = cast<LoadSDNode>(Base);
7731 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
7732 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7733 LD->getSrcValue(), LD->getSrcValueOffset(),
7735 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7736 LD->getSrcValue(), LD->getSrcValueOffset(),
7737 LD->isVolatile(), LD->getAlignment());
7740 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
7741 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
7742 TargetLowering::DAGCombinerInfo &DCI,
7743 const X86Subtarget *Subtarget,
7744 const TargetLowering &TLI) {
7745 unsigned NumOps = N->getNumOperands();
7746 DebugLoc dl = N->getDebugLoc();
7748 // Ignore single operand BUILD_VECTOR.
7752 MVT VT = N->getValueType(0);
7753 MVT EVT = VT.getVectorElementType();
7754 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
7755 // We are looking for load i64 and zero extend. We want to transform
7756 // it before legalizer has a chance to expand it. Also look for i64
7757 // BUILD_PAIR bit casted to f64.
7759 // This must be an insertion into a zero vector.
7760 SDValue HighElt = N->getOperand(1);
7761 if (!isZeroNode(HighElt))
7764 // Value must be a load.
7765 SDNode *Base = N->getOperand(0).getNode();
7766 if (!isa<LoadSDNode>(Base)) {
7767 if (Base->getOpcode() != ISD::BIT_CONVERT)
7769 Base = Base->getOperand(0).getNode();
7770 if (!isa<LoadSDNode>(Base))
7774 // Transform it into VZEXT_LOAD addr.
7775 LoadSDNode *LD = cast<LoadSDNode>(Base);
7777 // Load must not be an extload.
7778 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
7781 // Load type should legal type so we don't have to legalize it.
7782 if (!TLI.isTypeLegal(VT))
7785 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7786 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7787 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
7788 TargetLowering::TargetLoweringOpt TLO(DAG);
7789 TLO.CombineTo(SDValue(Base, 1), ResNode.getValue(1));
7790 DCI.CommitTargetLoweringOpt(TLO);
7794 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7795 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7796 const X86Subtarget *Subtarget) {
7797 DebugLoc DL = N->getDebugLoc();
7798 SDValue Cond = N->getOperand(0);
7799 // Get the LHS/RHS of the select.
7800 SDValue LHS = N->getOperand(1);
7801 SDValue RHS = N->getOperand(2);
7803 // If we have SSE[12] support, try to form min/max nodes.
7804 if (Subtarget->hasSSE2() &&
7805 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
7806 Cond.getOpcode() == ISD::SETCC) {
7807 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7809 unsigned Opcode = 0;
7810 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7813 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7816 if (!UnsafeFPMath) break;
7818 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7820 Opcode = X86ISD::FMIN;
7823 case ISD::SETOGT: // (X > Y) ? X : Y -> max
7826 if (!UnsafeFPMath) break;
7828 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
7830 Opcode = X86ISD::FMAX;
7833 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7836 case ISD::SETOGT: // (X > Y) ? Y : X -> min
7839 if (!UnsafeFPMath) break;
7841 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
7843 Opcode = X86ISD::FMIN;
7846 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
7849 if (!UnsafeFPMath) break;
7851 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
7853 Opcode = X86ISD::FMAX;
7859 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
7862 // If this is a select between two integer constants, try to do some
7864 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
7865 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
7866 // Don't do this for crazy integer types.
7867 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
7868 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
7869 // so that TrueC (the true value) is larger than FalseC.
7870 bool NeedsCondInvert = false;
7872 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
7873 // Efficiently invertible.
7874 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
7875 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
7876 isa<ConstantSDNode>(Cond.getOperand(1))))) {
7877 NeedsCondInvert = true;
7878 std::swap(TrueC, FalseC);
7881 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
7882 if (FalseC->getAPIntValue() == 0 &&
7883 TrueC->getAPIntValue().isPowerOf2()) {
7884 if (NeedsCondInvert) // Invert the condition if needed.
7885 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7886 DAG.getConstant(1, Cond.getValueType()));
7888 // Zero extend the condition if needed.
7889 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
7891 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
7892 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
7893 DAG.getConstant(ShAmt, MVT::i8));
7896 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
7897 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
7898 if (NeedsCondInvert) // Invert the condition if needed.
7899 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7900 DAG.getConstant(1, Cond.getValueType()));
7902 // Zero extend the condition if needed.
7903 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
7904 FalseC->getValueType(0), Cond);
7905 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
7906 SDValue(FalseC, 0));
7909 // Optimize cases that will turn into an LEA instruction. This requires
7910 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
7911 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
7912 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
7913 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
7915 bool isFastMultiplier = false;
7917 switch ((unsigned char)Diff) {
7919 case 1: // result = add base, cond
7920 case 2: // result = lea base( , cond*2)
7921 case 3: // result = lea base(cond, cond*2)
7922 case 4: // result = lea base( , cond*4)
7923 case 5: // result = lea base(cond, cond*4)
7924 case 8: // result = lea base( , cond*8)
7925 case 9: // result = lea base(cond, cond*8)
7926 isFastMultiplier = true;
7931 if (isFastMultiplier) {
7932 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
7933 if (NeedsCondInvert) // Invert the condition if needed.
7934 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7935 DAG.getConstant(1, Cond.getValueType()));
7937 // Zero extend the condition if needed.
7938 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
7940 // Scale the condition by the difference.
7942 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
7943 DAG.getConstant(Diff, Cond.getValueType()));
7945 // Add the base if non-zero.
7946 if (FalseC->getAPIntValue() != 0)
7947 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
7948 SDValue(FalseC, 0));
7958 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
7959 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
7960 TargetLowering::DAGCombinerInfo &DCI) {
7961 DebugLoc DL = N->getDebugLoc();
7963 // If the flag operand isn't dead, don't touch this CMOV.
7964 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
7967 // If this is a select between two integer constants, try to do some
7968 // optimizations. Note that the operands are ordered the opposite of SELECT
7970 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7971 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7972 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
7973 // larger than FalseC (the false value).
7974 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
7976 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
7977 CC = X86::GetOppositeBranchCondition(CC);
7978 std::swap(TrueC, FalseC);
7981 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
7982 // This is efficient for any integer data type (including i8/i16) and
7984 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
7985 SDValue Cond = N->getOperand(3);
7986 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
7987 DAG.getConstant(CC, MVT::i8), Cond);
7989 // Zero extend the condition if needed.
7990 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
7992 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
7993 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
7994 DAG.getConstant(ShAmt, MVT::i8));
7995 if (N->getNumValues() == 2) // Dead flag value?
7996 return DCI.CombineTo(N, Cond, SDValue());
8000 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
8001 // for any integer data type, including i8/i16.
8002 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8003 SDValue Cond = N->getOperand(3);
8004 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8005 DAG.getConstant(CC, MVT::i8), Cond);
8007 // Zero extend the condition if needed.
8008 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8009 FalseC->getValueType(0), Cond);
8010 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8011 SDValue(FalseC, 0));
8013 if (N->getNumValues() == 2) // Dead flag value?
8014 return DCI.CombineTo(N, Cond, SDValue());
8018 // Optimize cases that will turn into an LEA instruction. This requires
8019 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8020 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8021 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8022 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8024 bool isFastMultiplier = false;
8026 switch ((unsigned char)Diff) {
8028 case 1: // result = add base, cond
8029 case 2: // result = lea base( , cond*2)
8030 case 3: // result = lea base(cond, cond*2)
8031 case 4: // result = lea base( , cond*4)
8032 case 5: // result = lea base(cond, cond*4)
8033 case 8: // result = lea base( , cond*8)
8034 case 9: // result = lea base(cond, cond*8)
8035 isFastMultiplier = true;
8040 if (isFastMultiplier) {
8041 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8042 SDValue Cond = N->getOperand(3);
8043 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8044 DAG.getConstant(CC, MVT::i8), Cond);
8045 // Zero extend the condition if needed.
8046 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8048 // Scale the condition by the difference.
8050 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8051 DAG.getConstant(Diff, Cond.getValueType()));
8053 // Add the base if non-zero.
8054 if (FalseC->getAPIntValue() != 0)
8055 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8056 SDValue(FalseC, 0));
8057 if (N->getNumValues() == 2) // Dead flag value?
8058 return DCI.CombineTo(N, Cond, SDValue());
8068 /// PerformMulCombine - Optimize a single multiply with constant into two
8069 /// in order to implement it with two cheaper instructions, e.g.
8070 /// LEA + SHL, LEA + LEA.
8071 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8072 TargetLowering::DAGCombinerInfo &DCI) {
8073 if (DAG.getMachineFunction().
8074 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8077 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8080 MVT VT = N->getValueType(0);
8084 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8087 uint64_t MulAmt = C->getZExtValue();
8088 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8091 uint64_t MulAmt1 = 0;
8092 uint64_t MulAmt2 = 0;
8093 if ((MulAmt % 9) == 0) {
8095 MulAmt2 = MulAmt / 9;
8096 } else if ((MulAmt % 5) == 0) {
8098 MulAmt2 = MulAmt / 5;
8099 } else if ((MulAmt % 3) == 0) {
8101 MulAmt2 = MulAmt / 3;
8104 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8105 DebugLoc DL = N->getDebugLoc();
8107 if (isPowerOf2_64(MulAmt2) &&
8108 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8109 // If second multiplifer is pow2, issue it first. We want the multiply by
8110 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8112 std::swap(MulAmt1, MulAmt2);
8115 if (isPowerOf2_64(MulAmt1))
8116 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8117 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8119 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8120 DAG.getConstant(MulAmt1, VT));
8122 if (isPowerOf2_64(MulAmt2))
8123 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8124 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8126 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8127 DAG.getConstant(MulAmt2, VT));
8129 // Do not add new nodes to DAG combiner worklist.
8130 DCI.CombineTo(N, NewMul, false);
8136 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8138 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8139 const X86Subtarget *Subtarget) {
8140 // On X86 with SSE2 support, we can transform this to a vector shift if
8141 // all elements are shifted by the same amount. We can't do this in legalize
8142 // because the a constant vector is typically transformed to a constant pool
8143 // so we have no knowledge of the shift amount.
8144 if (!Subtarget->hasSSE2())
8147 MVT VT = N->getValueType(0);
8148 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8151 SDValue ShAmtOp = N->getOperand(1);
8152 MVT EltVT = VT.getVectorElementType();
8153 DebugLoc DL = N->getDebugLoc();
8155 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8156 unsigned NumElts = VT.getVectorNumElements();
8158 for (; i != NumElts; ++i) {
8159 SDValue Arg = ShAmtOp.getOperand(i);
8160 if (Arg.getOpcode() == ISD::UNDEF) continue;
8164 for (; i != NumElts; ++i) {
8165 SDValue Arg = ShAmtOp.getOperand(i);
8166 if (Arg.getOpcode() == ISD::UNDEF) continue;
8167 if (Arg != BaseShAmt) {
8171 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8172 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
8173 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8174 DAG.getIntPtrConstant(0));
8178 if (EltVT.bitsGT(MVT::i32))
8179 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8180 else if (EltVT.bitsLT(MVT::i32))
8181 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, BaseShAmt);
8183 // The shift amount is identical so we can do a vector shift.
8184 SDValue ValOp = N->getOperand(0);
8185 switch (N->getOpcode()) {
8187 assert(0 && "Unknown shift opcode!");
8190 if (VT == MVT::v2i64)
8191 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8192 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8194 if (VT == MVT::v4i32)
8195 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8196 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8198 if (VT == MVT::v8i16)
8199 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8200 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8204 if (VT == MVT::v4i32)
8205 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8206 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8208 if (VT == MVT::v8i16)
8209 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8210 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8214 if (VT == MVT::v2i64)
8215 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8216 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8218 if (VT == MVT::v4i32)
8219 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8220 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8222 if (VT == MVT::v8i16)
8223 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8224 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8231 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8232 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8233 const X86Subtarget *Subtarget) {
8234 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
8235 // the FP state in cases where an emms may be missing.
8236 // A preferable solution to the general problem is to figure out the right
8237 // places to insert EMMS. This qualifies as a quick hack.
8239 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8240 StoreSDNode *St = cast<StoreSDNode>(N);
8241 MVT VT = St->getValue().getValueType();
8242 if (VT.getSizeInBits() != 64)
8245 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloat && Subtarget->hasSSE2();
8246 if ((VT.isVector() ||
8247 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8248 isa<LoadSDNode>(St->getValue()) &&
8249 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8250 St->getChain().hasOneUse() && !St->isVolatile()) {
8251 SDNode* LdVal = St->getValue().getNode();
8253 int TokenFactorIndex = -1;
8254 SmallVector<SDValue, 8> Ops;
8255 SDNode* ChainVal = St->getChain().getNode();
8256 // Must be a store of a load. We currently handle two cases: the load
8257 // is a direct child, and it's under an intervening TokenFactor. It is
8258 // possible to dig deeper under nested TokenFactors.
8259 if (ChainVal == LdVal)
8260 Ld = cast<LoadSDNode>(St->getChain());
8261 else if (St->getValue().hasOneUse() &&
8262 ChainVal->getOpcode() == ISD::TokenFactor) {
8263 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8264 if (ChainVal->getOperand(i).getNode() == LdVal) {
8265 TokenFactorIndex = i;
8266 Ld = cast<LoadSDNode>(St->getValue());
8268 Ops.push_back(ChainVal->getOperand(i));
8272 if (!Ld || !ISD::isNormalLoad(Ld))
8275 // If this is not the MMX case, i.e. we are just turning i64 load/store
8276 // into f64 load/store, avoid the transformation if there are multiple
8277 // uses of the loaded value.
8278 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
8281 DebugLoc LdDL = Ld->getDebugLoc();
8282 DebugLoc StDL = N->getDebugLoc();
8283 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
8284 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
8286 if (Subtarget->is64Bit() || F64IsLegal) {
8287 MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
8288 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
8289 Ld->getBasePtr(), Ld->getSrcValue(),
8290 Ld->getSrcValueOffset(), Ld->isVolatile(),
8291 Ld->getAlignment());
8292 SDValue NewChain = NewLd.getValue(1);
8293 if (TokenFactorIndex != -1) {
8294 Ops.push_back(NewChain);
8295 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8298 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
8299 St->getSrcValue(), St->getSrcValueOffset(),
8300 St->isVolatile(), St->getAlignment());
8303 // Otherwise, lower to two pairs of 32-bit loads / stores.
8304 SDValue LoAddr = Ld->getBasePtr();
8305 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
8306 DAG.getConstant(4, MVT::i32));
8308 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
8309 Ld->getSrcValue(), Ld->getSrcValueOffset(),
8310 Ld->isVolatile(), Ld->getAlignment());
8311 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
8312 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8314 MinAlign(Ld->getAlignment(), 4));
8316 SDValue NewChain = LoLd.getValue(1);
8317 if (TokenFactorIndex != -1) {
8318 Ops.push_back(LoLd);
8319 Ops.push_back(HiLd);
8320 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8324 LoAddr = St->getBasePtr();
8325 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
8326 DAG.getConstant(4, MVT::i32));
8328 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
8329 St->getSrcValue(), St->getSrcValueOffset(),
8330 St->isVolatile(), St->getAlignment());
8331 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
8333 St->getSrcValueOffset() + 4,
8335 MinAlign(St->getAlignment(), 4));
8336 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
8341 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8342 /// X86ISD::FXOR nodes.
8343 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8344 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8345 // F[X]OR(0.0, x) -> x
8346 // F[X]OR(x, 0.0) -> x
8347 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8348 if (C->getValueAPF().isPosZero())
8349 return N->getOperand(1);
8350 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8351 if (C->getValueAPF().isPosZero())
8352 return N->getOperand(0);
8356 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8357 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8358 // FAND(0.0, x) -> 0.0
8359 // FAND(x, 0.0) -> 0.0
8360 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8361 if (C->getValueAPF().isPosZero())
8362 return N->getOperand(0);
8363 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8364 if (C->getValueAPF().isPosZero())
8365 return N->getOperand(1);
8369 static SDValue PerformBTCombine(SDNode *N,
8371 TargetLowering::DAGCombinerInfo &DCI) {
8372 // BT ignores high bits in the bit index operand.
8373 SDValue Op1 = N->getOperand(1);
8374 if (Op1.hasOneUse()) {
8375 unsigned BitWidth = Op1.getValueSizeInBits();
8376 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8377 APInt KnownZero, KnownOne;
8378 TargetLowering::TargetLoweringOpt TLO(DAG);
8379 TargetLowering &TLI = DAG.getTargetLoweringInfo();
8380 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8381 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8382 DCI.CommitTargetLoweringOpt(TLO);
8387 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8388 DAGCombinerInfo &DCI) const {
8389 SelectionDAG &DAG = DCI.DAG;
8390 switch (N->getOpcode()) {
8392 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8393 case ISD::BUILD_VECTOR:
8394 return PerformBuildVectorCombine(N, DAG, DCI, Subtarget, *this);
8395 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
8396 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
8397 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
8400 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
8401 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
8403 case X86ISD::FOR: return PerformFORCombine(N, DAG);
8404 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
8405 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
8411 //===----------------------------------------------------------------------===//
8412 // X86 Inline Assembly Support
8413 //===----------------------------------------------------------------------===//
8415 /// getConstraintType - Given a constraint letter, return the type of
8416 /// constraint it is for this target.
8417 X86TargetLowering::ConstraintType
8418 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8419 if (Constraint.size() == 1) {
8420 switch (Constraint[0]) {
8432 return C_RegisterClass;
8440 return TargetLowering::getConstraintType(Constraint);
8443 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8444 /// with another that has more specific requirements based on the type of the
8445 /// corresponding operand.
8446 const char *X86TargetLowering::
8447 LowerXConstraint(MVT ConstraintVT) const {
8448 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8449 // 'f' like normal targets.
8450 if (ConstraintVT.isFloatingPoint()) {
8451 if (Subtarget->hasSSE2())
8453 if (Subtarget->hasSSE1())
8457 return TargetLowering::LowerXConstraint(ConstraintVT);
8460 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8461 /// vector. If it is invalid, don't add anything to Ops.
8462 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8465 std::vector<SDValue>&Ops,
8466 SelectionDAG &DAG) const {
8467 SDValue Result(0, 0);
8469 switch (Constraint) {
8472 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8473 if (C->getZExtValue() <= 31) {
8474 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8480 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8481 if (C->getZExtValue() <= 63) {
8482 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8488 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8489 if (C->getZExtValue() <= 255) {
8490 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8496 // 32-bit signed value
8497 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8498 const ConstantInt *CI = C->getConstantIntValue();
8499 if (CI->isValueValidForType(Type::Int32Ty, C->getSExtValue())) {
8500 // Widen to 64 bits here to get it sign extended.
8501 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
8504 // FIXME gcc accepts some relocatable values here too, but only in certain
8505 // memory models; it's complicated.
8510 // 32-bit unsigned value
8511 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8512 const ConstantInt *CI = C->getConstantIntValue();
8513 if (CI->isValueValidForType(Type::Int32Ty, C->getZExtValue())) {
8514 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8518 // FIXME gcc accepts some relocatable values here too, but only in certain
8519 // memory models; it's complicated.
8523 // Literal immediates are always ok.
8524 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8525 // Widen to 64 bits here to get it sign extended.
8526 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
8530 // If we are in non-pic codegen mode, we allow the address of a global (with
8531 // an optional displacement) to be used with 'i'.
8532 GlobalAddressSDNode *GA = 0;
8535 // Match either (GA), (GA+C), (GA+C1+C2), etc.
8537 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
8538 Offset += GA->getOffset();
8540 } else if (Op.getOpcode() == ISD::ADD) {
8541 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8542 Offset += C->getZExtValue();
8543 Op = Op.getOperand(0);
8546 } else if (Op.getOpcode() == ISD::SUB) {
8547 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8548 Offset += -C->getZExtValue();
8549 Op = Op.getOperand(0);
8554 // Otherwise, this isn't something we can handle, reject it.
8559 Op = LowerGlobalAddress(GA->getGlobal(), Op.getDebugLoc(), Offset, DAG);
8561 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8568 if (Result.getNode()) {
8569 Ops.push_back(Result);
8572 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8576 std::vector<unsigned> X86TargetLowering::
8577 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8579 if (Constraint.size() == 1) {
8580 // FIXME: not handling fp-stack yet!
8581 switch (Constraint[0]) { // GCC X86 Constraint Letters
8582 default: break; // Unknown constraint letter
8583 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
8586 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8587 else if (VT == MVT::i16)
8588 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8589 else if (VT == MVT::i8)
8590 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8591 else if (VT == MVT::i64)
8592 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8597 return std::vector<unsigned>();
8600 std::pair<unsigned, const TargetRegisterClass*>
8601 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8603 // First, see if this is a constraint that directly corresponds to an LLVM
8605 if (Constraint.size() == 1) {
8606 // GCC Constraint Letters
8607 switch (Constraint[0]) {
8609 case 'r': // GENERAL_REGS
8610 case 'R': // LEGACY_REGS
8611 case 'l': // INDEX_REGS
8613 return std::make_pair(0U, X86::GR8RegisterClass);
8615 return std::make_pair(0U, X86::GR16RegisterClass);
8616 if (VT == MVT::i32 || !Subtarget->is64Bit())
8617 return std::make_pair(0U, X86::GR32RegisterClass);
8618 return std::make_pair(0U, X86::GR64RegisterClass);
8619 case 'f': // FP Stack registers.
8620 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
8621 // value to the correct fpstack register class.
8622 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
8623 return std::make_pair(0U, X86::RFP32RegisterClass);
8624 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
8625 return std::make_pair(0U, X86::RFP64RegisterClass);
8626 return std::make_pair(0U, X86::RFP80RegisterClass);
8627 case 'y': // MMX_REGS if MMX allowed.
8628 if (!Subtarget->hasMMX()) break;
8629 return std::make_pair(0U, X86::VR64RegisterClass);
8630 case 'Y': // SSE_REGS if SSE2 allowed
8631 if (!Subtarget->hasSSE2()) break;
8633 case 'x': // SSE_REGS if SSE1 allowed
8634 if (!Subtarget->hasSSE1()) break;
8636 switch (VT.getSimpleVT()) {
8638 // Scalar SSE types.
8641 return std::make_pair(0U, X86::FR32RegisterClass);
8644 return std::make_pair(0U, X86::FR64RegisterClass);
8652 return std::make_pair(0U, X86::VR128RegisterClass);
8658 // Use the default implementation in TargetLowering to convert the register
8659 // constraint into a member of a register class.
8660 std::pair<unsigned, const TargetRegisterClass*> Res;
8661 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8663 // Not found as a standard register?
8664 if (Res.second == 0) {
8665 // GCC calls "st(0)" just plain "st".
8666 if (StringsEqualNoCase("{st}", Constraint)) {
8667 Res.first = X86::ST0;
8668 Res.second = X86::RFP80RegisterClass;
8670 // 'A' means EAX + EDX.
8671 if (Constraint == "A") {
8672 Res.first = X86::EAX;
8673 Res.second = X86::GRADRegisterClass;
8678 // Otherwise, check to see if this is a register class of the wrong value
8679 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
8680 // turn into {ax},{dx}.
8681 if (Res.second->hasType(VT))
8682 return Res; // Correct type already, nothing to do.
8684 // All of the single-register GCC register classes map their values onto
8685 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
8686 // really want an 8-bit or 32-bit register, map to the appropriate register
8687 // class and return the appropriate register.
8688 if (Res.second == X86::GR16RegisterClass) {
8689 if (VT == MVT::i8) {
8690 unsigned DestReg = 0;
8691 switch (Res.first) {
8693 case X86::AX: DestReg = X86::AL; break;
8694 case X86::DX: DestReg = X86::DL; break;
8695 case X86::CX: DestReg = X86::CL; break;
8696 case X86::BX: DestReg = X86::BL; break;
8699 Res.first = DestReg;
8700 Res.second = X86::GR8RegisterClass;
8702 } else if (VT == MVT::i32) {
8703 unsigned DestReg = 0;
8704 switch (Res.first) {
8706 case X86::AX: DestReg = X86::EAX; break;
8707 case X86::DX: DestReg = X86::EDX; break;
8708 case X86::CX: DestReg = X86::ECX; break;
8709 case X86::BX: DestReg = X86::EBX; break;
8710 case X86::SI: DestReg = X86::ESI; break;
8711 case X86::DI: DestReg = X86::EDI; break;
8712 case X86::BP: DestReg = X86::EBP; break;
8713 case X86::SP: DestReg = X86::ESP; break;
8716 Res.first = DestReg;
8717 Res.second = X86::GR32RegisterClass;
8719 } else if (VT == MVT::i64) {
8720 unsigned DestReg = 0;
8721 switch (Res.first) {
8723 case X86::AX: DestReg = X86::RAX; break;
8724 case X86::DX: DestReg = X86::RDX; break;
8725 case X86::CX: DestReg = X86::RCX; break;
8726 case X86::BX: DestReg = X86::RBX; break;
8727 case X86::SI: DestReg = X86::RSI; break;
8728 case X86::DI: DestReg = X86::RDI; break;
8729 case X86::BP: DestReg = X86::RBP; break;
8730 case X86::SP: DestReg = X86::RSP; break;
8733 Res.first = DestReg;
8734 Res.second = X86::GR64RegisterClass;
8737 } else if (Res.second == X86::FR32RegisterClass ||
8738 Res.second == X86::FR64RegisterClass ||
8739 Res.second == X86::VR128RegisterClass) {
8740 // Handle references to XMM physical registers that got mapped into the
8741 // wrong class. This can happen with constraints like {xmm0} where the
8742 // target independent register mapper will just pick the first match it can
8743 // find, ignoring the required type.
8745 Res.second = X86::FR32RegisterClass;
8746 else if (VT == MVT::f64)
8747 Res.second = X86::FR64RegisterClass;
8748 else if (X86::VR128RegisterClass->hasType(VT))
8749 Res.second = X86::VR128RegisterClass;
8755 //===----------------------------------------------------------------------===//
8756 // X86 Widen vector type
8757 //===----------------------------------------------------------------------===//
8759 /// getWidenVectorType: given a vector type, returns the type to widen
8760 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
8761 /// If there is no vector type that we want to widen to, returns MVT::Other
8762 /// When and where to widen is target dependent based on the cost of
8763 /// scalarizing vs using the wider vector type.
8765 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
8766 assert(VT.isVector());
8767 if (isTypeLegal(VT))
8770 // TODO: In computeRegisterProperty, we can compute the list of legal vector
8771 // type based on element type. This would speed up our search (though
8772 // it may not be worth it since the size of the list is relatively
8774 MVT EltVT = VT.getVectorElementType();
8775 unsigned NElts = VT.getVectorNumElements();
8777 // On X86, it make sense to widen any vector wider than 1
8781 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
8782 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
8783 MVT SVT = (MVT::SimpleValueType)nVT;
8785 if (isTypeLegal(SVT) &&
8786 SVT.getVectorElementType() == EltVT &&
8787 SVT.getVectorNumElements() > NElts)