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 "X86TargetObjectFile.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalAlias.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Function.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Intrinsics.h"
28 #include "llvm/LLVMContext.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/MCExpr.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/ADT/BitVector.h"
41 #include "llvm/ADT/SmallSet.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/ADT/VectorExtras.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/raw_ostream.h"
52 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
54 // Disable16Bit - 16-bit operations typically have a larger encoding than
55 // corresponding 32-bit instructions, and 16-bit code is slow on some
56 // processors. This is an experimental flag to disable 16-bit operations
57 // (which forces them to be Legalized to 32-bit operations).
59 Disable16Bit("disable-16bit", cl::Hidden,
60 cl::desc("Disable use of 16-bit instructions"));
62 // Forward declarations.
63 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
66 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
67 switch (TM.getSubtarget<X86Subtarget>().TargetType) {
68 default: llvm_unreachable("unknown subtarget type");
69 case X86Subtarget::isDarwin:
70 if (TM.getSubtarget<X86Subtarget>().is64Bit())
71 return new X8664_MachoTargetObjectFile();
72 return new X8632_MachoTargetObjectFile();
73 case X86Subtarget::isELF:
74 return new TargetLoweringObjectFileELF();
75 case X86Subtarget::isMingw:
76 case X86Subtarget::isCygwin:
77 case X86Subtarget::isWindows:
78 return new TargetLoweringObjectFileCOFF();
83 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
84 : TargetLowering(TM, createTLOF(TM)) {
85 Subtarget = &TM.getSubtarget<X86Subtarget>();
86 X86ScalarSSEf64 = Subtarget->hasSSE2();
87 X86ScalarSSEf32 = Subtarget->hasSSE1();
88 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
90 RegInfo = TM.getRegisterInfo();
93 // Set up the TargetLowering object.
95 // X86 is weird, it always uses i8 for shift amounts and setcc results.
96 setShiftAmountType(MVT::i8);
97 setBooleanContents(ZeroOrOneBooleanContent);
98 setSchedulingPreference(SchedulingForRegPressure);
99 setStackPointerRegisterToSaveRestore(X86StackPtr);
101 if (Subtarget->isTargetDarwin()) {
102 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
103 setUseUnderscoreSetJmp(false);
104 setUseUnderscoreLongJmp(false);
105 } else if (Subtarget->isTargetMingw()) {
106 // MS runtime is weird: it exports _setjmp, but longjmp!
107 setUseUnderscoreSetJmp(true);
108 setUseUnderscoreLongJmp(false);
110 setUseUnderscoreSetJmp(true);
111 setUseUnderscoreLongJmp(true);
114 // Set up the register classes.
115 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
117 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
118 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
119 if (Subtarget->is64Bit())
120 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
122 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
124 // We don't accept any truncstore of integer registers.
125 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
127 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
128 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
130 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
131 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
132 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
134 // SETOEQ and SETUNE require checking two conditions.
135 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
136 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
137 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
138 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
139 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
140 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
142 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
144 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
145 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
146 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
148 if (Subtarget->is64Bit()) {
149 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
150 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
151 } else if (!UseSoftFloat) {
152 if (X86ScalarSSEf64) {
153 // We have an impenetrably clever algorithm for ui64->double only.
154 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
156 // We have an algorithm for SSE2, and we turn this into a 64-bit
157 // FILD for other targets.
158 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
161 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
163 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
164 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
167 // SSE has no i16 to fp conversion, only i32
168 if (X86ScalarSSEf32) {
169 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
170 // f32 and f64 cases are Legal, f80 case is not
171 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
173 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
174 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
177 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
178 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
181 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
182 // are Legal, f80 is custom lowered.
183 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
184 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
186 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
188 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
189 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
191 if (X86ScalarSSEf32) {
192 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
193 // f32 and f64 cases are Legal, f80 case is not
194 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
196 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
197 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
200 // Handle FP_TO_UINT by promoting the destination to a larger signed
202 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
203 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
204 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
206 if (Subtarget->is64Bit()) {
207 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
208 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
209 } else if (!UseSoftFloat) {
210 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
211 // Expand FP_TO_UINT into a select.
212 // FIXME: We would like to use a Custom expander here eventually to do
213 // the optimal thing for SSE vs. the default expansion in the legalizer.
214 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
216 // With SSE3 we can use fisttpll to convert to a signed i64; without
217 // SSE, we're stuck with a fistpll.
218 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
221 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
222 if (!X86ScalarSSEf64) {
223 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
224 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
227 // Scalar integer divide and remainder are lowered to use operations that
228 // produce two results, to match the available instructions. This exposes
229 // the two-result form to trivial CSE, which is able to combine x/y and x%y
230 // into a single instruction.
232 // Scalar integer multiply-high is also lowered to use two-result
233 // operations, to match the available instructions. However, plain multiply
234 // (low) operations are left as Legal, as there are single-result
235 // instructions for this in x86. Using the two-result multiply instructions
236 // when both high and low results are needed must be arranged by dagcombine.
237 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
238 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
239 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
240 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
241 setOperationAction(ISD::SREM , MVT::i8 , Expand);
242 setOperationAction(ISD::UREM , MVT::i8 , Expand);
243 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
244 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
245 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
246 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
247 setOperationAction(ISD::SREM , MVT::i16 , Expand);
248 setOperationAction(ISD::UREM , MVT::i16 , Expand);
249 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
250 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
251 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
252 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
253 setOperationAction(ISD::SREM , MVT::i32 , Expand);
254 setOperationAction(ISD::UREM , MVT::i32 , Expand);
255 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
256 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
257 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
258 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
259 setOperationAction(ISD::SREM , MVT::i64 , Expand);
260 setOperationAction(ISD::UREM , MVT::i64 , Expand);
262 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
263 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
264 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
265 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
266 if (Subtarget->is64Bit())
267 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
268 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
269 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
270 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
271 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
272 setOperationAction(ISD::FREM , MVT::f32 , Expand);
273 setOperationAction(ISD::FREM , MVT::f64 , Expand);
274 setOperationAction(ISD::FREM , MVT::f80 , Expand);
275 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
277 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
278 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
279 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
280 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
282 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
283 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
285 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
286 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
288 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
289 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
290 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
291 if (Subtarget->is64Bit()) {
292 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
293 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
294 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
297 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
298 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
300 // These should be promoted to a larger select which is supported.
301 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
302 // X86 wants to expand cmov itself.
303 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
305 setOperationAction(ISD::SELECT , MVT::i16 , Expand);
307 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
308 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
309 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
310 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
311 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
312 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
314 setOperationAction(ISD::SETCC , MVT::i16 , Expand);
316 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
317 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
318 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
319 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
320 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
321 if (Subtarget->is64Bit()) {
322 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
323 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
325 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
328 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
329 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
330 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
331 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
332 if (Subtarget->is64Bit())
333 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
334 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
335 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
336 if (Subtarget->is64Bit()) {
337 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
338 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
339 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
340 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
341 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
343 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
344 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
345 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
346 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
347 if (Subtarget->is64Bit()) {
348 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
349 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
350 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
353 if (Subtarget->hasSSE1())
354 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
356 if (!Subtarget->hasSSE2())
357 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
359 // Expand certain atomics
360 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
361 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
362 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
363 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
365 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
366 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
367 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
368 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
370 if (!Subtarget->is64Bit()) {
371 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
372 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
373 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
374 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
375 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
376 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
377 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
380 // FIXME - use subtarget debug flags
381 if (!Subtarget->isTargetDarwin() &&
382 !Subtarget->isTargetELF() &&
383 !Subtarget->isTargetCygMing()) {
384 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
387 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
388 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
389 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
390 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
391 if (Subtarget->is64Bit()) {
392 setExceptionPointerRegister(X86::RAX);
393 setExceptionSelectorRegister(X86::RDX);
395 setExceptionPointerRegister(X86::EAX);
396 setExceptionSelectorRegister(X86::EDX);
398 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
399 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
401 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
403 setOperationAction(ISD::TRAP, MVT::Other, Legal);
405 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
406 setOperationAction(ISD::VASTART , MVT::Other, Custom);
407 setOperationAction(ISD::VAEND , MVT::Other, Expand);
408 if (Subtarget->is64Bit()) {
409 setOperationAction(ISD::VAARG , MVT::Other, Custom);
410 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
412 setOperationAction(ISD::VAARG , MVT::Other, Expand);
413 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
416 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
417 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
418 if (Subtarget->is64Bit())
419 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
420 if (Subtarget->isTargetCygMing())
421 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
423 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
425 if (!UseSoftFloat && X86ScalarSSEf64) {
426 // f32 and f64 use SSE.
427 // Set up the FP register classes.
428 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
429 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
431 // Use ANDPD to simulate FABS.
432 setOperationAction(ISD::FABS , MVT::f64, Custom);
433 setOperationAction(ISD::FABS , MVT::f32, Custom);
435 // Use XORP to simulate FNEG.
436 setOperationAction(ISD::FNEG , MVT::f64, Custom);
437 setOperationAction(ISD::FNEG , MVT::f32, Custom);
439 // Use ANDPD and ORPD to simulate FCOPYSIGN.
440 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
441 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
443 // We don't support sin/cos/fmod
444 setOperationAction(ISD::FSIN , MVT::f64, Expand);
445 setOperationAction(ISD::FCOS , MVT::f64, Expand);
446 setOperationAction(ISD::FSIN , MVT::f32, Expand);
447 setOperationAction(ISD::FCOS , MVT::f32, Expand);
449 // Expand FP immediates into loads from the stack, except for the special
451 addLegalFPImmediate(APFloat(+0.0)); // xorpd
452 addLegalFPImmediate(APFloat(+0.0f)); // xorps
453 } else if (!UseSoftFloat && X86ScalarSSEf32) {
454 // Use SSE for f32, x87 for f64.
455 // Set up the FP register classes.
456 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
457 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
459 // Use ANDPS to simulate FABS.
460 setOperationAction(ISD::FABS , MVT::f32, Custom);
462 // Use XORP to simulate FNEG.
463 setOperationAction(ISD::FNEG , MVT::f32, Custom);
465 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
467 // Use ANDPS and ORPS to simulate FCOPYSIGN.
468 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
469 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
471 // We don't support sin/cos/fmod
472 setOperationAction(ISD::FSIN , MVT::f32, Expand);
473 setOperationAction(ISD::FCOS , MVT::f32, Expand);
475 // Special cases we handle for FP constants.
476 addLegalFPImmediate(APFloat(+0.0f)); // xorps
477 addLegalFPImmediate(APFloat(+0.0)); // FLD0
478 addLegalFPImmediate(APFloat(+1.0)); // FLD1
479 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
480 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
483 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
484 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
486 } else if (!UseSoftFloat) {
487 // f32 and f64 in x87.
488 // Set up the FP register classes.
489 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
490 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
492 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
493 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
494 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
495 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
498 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
499 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
501 addLegalFPImmediate(APFloat(+0.0)); // FLD0
502 addLegalFPImmediate(APFloat(+1.0)); // FLD1
503 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
504 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
505 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
506 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
507 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
508 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
511 // Long double always uses X87.
513 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
514 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
515 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
518 APFloat TmpFlt(+0.0);
519 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
521 addLegalFPImmediate(TmpFlt); // FLD0
523 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
524 APFloat TmpFlt2(+1.0);
525 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
527 addLegalFPImmediate(TmpFlt2); // FLD1
528 TmpFlt2.changeSign();
529 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
533 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
534 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
538 // Always use a library call for pow.
539 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
540 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
541 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
543 setOperationAction(ISD::FLOG, MVT::f80, Expand);
544 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
545 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
546 setOperationAction(ISD::FEXP, MVT::f80, Expand);
547 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
549 // First set operation action for all vector types to either promote
550 // (for widening) or expand (for scalarization). Then we will selectively
551 // turn on ones that can be effectively codegen'd.
552 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
553 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
554 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
569 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
570 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
595 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
596 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
597 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
598 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
599 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
600 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
601 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
602 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
603 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
604 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
605 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
606 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
607 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
608 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
609 setTruncStoreAction((MVT::SimpleValueType)VT,
610 (MVT::SimpleValueType)InnerVT, Expand);
611 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
612 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
613 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
616 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
617 // with -msoft-float, disable use of MMX as well.
618 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
619 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
620 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
621 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
622 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
623 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
625 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
626 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
627 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
628 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
630 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
631 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
632 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
633 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
635 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
636 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
638 setOperationAction(ISD::AND, MVT::v8i8, Promote);
639 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
640 setOperationAction(ISD::AND, MVT::v4i16, Promote);
641 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
642 setOperationAction(ISD::AND, MVT::v2i32, Promote);
643 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
644 setOperationAction(ISD::AND, MVT::v1i64, Legal);
646 setOperationAction(ISD::OR, MVT::v8i8, Promote);
647 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
648 setOperationAction(ISD::OR, MVT::v4i16, Promote);
649 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
650 setOperationAction(ISD::OR, MVT::v2i32, Promote);
651 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
652 setOperationAction(ISD::OR, MVT::v1i64, Legal);
654 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
655 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
656 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
657 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
658 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
659 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
660 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
662 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
663 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
664 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
665 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
666 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
667 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
668 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
669 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
670 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
672 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
673 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
674 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
675 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
676 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
678 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
679 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
680 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
681 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
683 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
684 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
685 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
686 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
688 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
690 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
691 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
692 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
693 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
694 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
695 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
696 setOperationAction(ISD::VSETCC, MVT::v2i32, Custom);
699 if (!UseSoftFloat && Subtarget->hasSSE1()) {
700 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
702 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
703 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
704 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
705 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
706 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
707 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
708 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
709 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
710 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
711 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
712 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
713 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
716 if (!UseSoftFloat && Subtarget->hasSSE2()) {
717 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
719 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
720 // registers cannot be used even for integer operations.
721 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
722 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
723 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
724 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
726 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
727 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
728 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
729 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
730 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
731 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
732 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
733 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
734 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
735 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
736 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
737 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
738 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
739 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
740 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
741 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
743 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
744 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
745 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
746 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
748 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
749 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
750 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
751 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
752 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
754 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
755 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
756 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
757 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
758 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
760 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
761 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
762 EVT VT = (MVT::SimpleValueType)i;
763 // Do not attempt to custom lower non-power-of-2 vectors
764 if (!isPowerOf2_32(VT.getVectorNumElements()))
766 // Do not attempt to custom lower non-128-bit vectors
767 if (!VT.is128BitVector())
769 setOperationAction(ISD::BUILD_VECTOR,
770 VT.getSimpleVT().SimpleTy, Custom);
771 setOperationAction(ISD::VECTOR_SHUFFLE,
772 VT.getSimpleVT().SimpleTy, Custom);
773 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
774 VT.getSimpleVT().SimpleTy, Custom);
777 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
778 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
779 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
780 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
781 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
782 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
784 if (Subtarget->is64Bit()) {
785 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
786 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
789 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
790 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
791 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
794 // Do not attempt to promote non-128-bit vectors
795 if (!VT.is128BitVector()) {
798 setOperationAction(ISD::AND, SVT, Promote);
799 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
800 setOperationAction(ISD::OR, SVT, Promote);
801 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
802 setOperationAction(ISD::XOR, SVT, Promote);
803 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
804 setOperationAction(ISD::LOAD, SVT, Promote);
805 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
806 setOperationAction(ISD::SELECT, SVT, Promote);
807 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
810 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
812 // Custom lower v2i64 and v2f64 selects.
813 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
814 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
815 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
816 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
818 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
819 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
820 if (!DisableMMX && Subtarget->hasMMX()) {
821 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
822 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
826 if (Subtarget->hasSSE41()) {
827 // FIXME: Do we need to handle scalar-to-vector here?
828 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
830 // i8 and i16 vectors are custom , because the source register and source
831 // source memory operand types are not the same width. f32 vectors are
832 // custom since the immediate controlling the insert encodes additional
834 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
835 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
836 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
837 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
839 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
840 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
841 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
842 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
844 if (Subtarget->is64Bit()) {
845 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
846 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
850 if (Subtarget->hasSSE42()) {
851 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
854 if (!UseSoftFloat && Subtarget->hasAVX()) {
855 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
856 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
857 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
858 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
860 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
861 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
862 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
863 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
864 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
865 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
866 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
867 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
868 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
869 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
870 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
871 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
872 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
873 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
874 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
876 // Operations to consider commented out -v16i16 v32i8
877 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
878 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
879 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
880 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
881 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
882 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
883 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
884 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
885 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
886 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
887 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
888 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
889 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
890 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
892 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
893 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
894 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
895 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
897 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
898 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
899 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
900 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
901 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
903 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
904 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
905 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
906 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
907 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
908 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
911 // Not sure we want to do this since there are no 256-bit integer
914 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
915 // This includes 256-bit vectors
916 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
917 EVT VT = (MVT::SimpleValueType)i;
919 // Do not attempt to custom lower non-power-of-2 vectors
920 if (!isPowerOf2_32(VT.getVectorNumElements()))
923 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
924 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
925 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
928 if (Subtarget->is64Bit()) {
929 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
930 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
935 // Not sure we want to do this since there are no 256-bit integer
938 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
939 // Including 256-bit vectors
940 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
941 EVT VT = (MVT::SimpleValueType)i;
943 if (!VT.is256BitVector()) {
946 setOperationAction(ISD::AND, VT, Promote);
947 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
948 setOperationAction(ISD::OR, VT, Promote);
949 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
950 setOperationAction(ISD::XOR, VT, Promote);
951 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
952 setOperationAction(ISD::LOAD, VT, Promote);
953 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
954 setOperationAction(ISD::SELECT, VT, Promote);
955 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
958 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
962 // We want to custom lower some of our intrinsics.
963 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
965 // Add/Sub/Mul with overflow operations are custom lowered.
966 setOperationAction(ISD::SADDO, MVT::i32, Custom);
967 setOperationAction(ISD::SADDO, MVT::i64, Custom);
968 setOperationAction(ISD::UADDO, MVT::i32, Custom);
969 setOperationAction(ISD::UADDO, MVT::i64, Custom);
970 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
971 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
972 setOperationAction(ISD::USUBO, MVT::i32, Custom);
973 setOperationAction(ISD::USUBO, MVT::i64, Custom);
974 setOperationAction(ISD::SMULO, MVT::i32, Custom);
975 setOperationAction(ISD::SMULO, MVT::i64, Custom);
977 if (!Subtarget->is64Bit()) {
978 // These libcalls are not available in 32-bit.
979 setLibcallName(RTLIB::SHL_I128, 0);
980 setLibcallName(RTLIB::SRL_I128, 0);
981 setLibcallName(RTLIB::SRA_I128, 0);
984 // We have target-specific dag combine patterns for the following nodes:
985 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
986 setTargetDAGCombine(ISD::BUILD_VECTOR);
987 setTargetDAGCombine(ISD::SELECT);
988 setTargetDAGCombine(ISD::SHL);
989 setTargetDAGCombine(ISD::SRA);
990 setTargetDAGCombine(ISD::SRL);
991 setTargetDAGCombine(ISD::OR);
992 setTargetDAGCombine(ISD::STORE);
993 setTargetDAGCombine(ISD::MEMBARRIER);
994 setTargetDAGCombine(ISD::ZERO_EXTEND);
995 if (Subtarget->is64Bit())
996 setTargetDAGCombine(ISD::MUL);
998 computeRegisterProperties();
1000 // Divide and reminder operations have no vector equivalent and can
1001 // trap. Do a custom widening for these operations in which we never
1002 // generate more divides/remainder than the original vector width.
1003 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1004 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
1005 if (!isTypeLegal((MVT::SimpleValueType)VT)) {
1006 setOperationAction(ISD::SDIV, (MVT::SimpleValueType) VT, Custom);
1007 setOperationAction(ISD::UDIV, (MVT::SimpleValueType) VT, Custom);
1008 setOperationAction(ISD::SREM, (MVT::SimpleValueType) VT, Custom);
1009 setOperationAction(ISD::UREM, (MVT::SimpleValueType) VT, Custom);
1013 // FIXME: These should be based on subtarget info. Plus, the values should
1014 // be smaller when we are in optimizing for size mode.
1015 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1016 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
1017 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1018 setPrefLoopAlignment(16);
1019 benefitFromCodePlacementOpt = true;
1023 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1028 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1029 /// the desired ByVal argument alignment.
1030 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1033 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1034 if (VTy->getBitWidth() == 128)
1036 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1037 unsigned EltAlign = 0;
1038 getMaxByValAlign(ATy->getElementType(), EltAlign);
1039 if (EltAlign > MaxAlign)
1040 MaxAlign = EltAlign;
1041 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1042 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1043 unsigned EltAlign = 0;
1044 getMaxByValAlign(STy->getElementType(i), EltAlign);
1045 if (EltAlign > MaxAlign)
1046 MaxAlign = EltAlign;
1054 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1055 /// function arguments in the caller parameter area. For X86, aggregates
1056 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1057 /// are at 4-byte boundaries.
1058 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1059 if (Subtarget->is64Bit()) {
1060 // Max of 8 and alignment of type.
1061 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1068 if (Subtarget->hasSSE1())
1069 getMaxByValAlign(Ty, Align);
1073 /// getOptimalMemOpType - Returns the target specific optimal type for load
1074 /// and store operations as a result of memset, memcpy, and memmove
1075 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1078 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1079 bool isSrcConst, bool isSrcStr,
1080 SelectionDAG &DAG) const {
1081 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1082 // linux. This is because the stack realignment code can't handle certain
1083 // cases like PR2962. This should be removed when PR2962 is fixed.
1084 const Function *F = DAG.getMachineFunction().getFunction();
1085 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1086 if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1087 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1089 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1092 if (Subtarget->is64Bit() && Size >= 8)
1097 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1098 /// current function. The returned value is a member of the
1099 /// MachineJumpTableInfo::JTEntryKind enum.
1100 unsigned X86TargetLowering::getJumpTableEncoding() const {
1101 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1103 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1104 Subtarget->isPICStyleGOT())
1105 return MachineJumpTableInfo::EK_Custom32;
1107 // Otherwise, use the normal jump table encoding heuristics.
1108 return TargetLowering::getJumpTableEncoding();
1111 /// getPICBaseSymbol - Return the X86-32 PIC base.
1113 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1114 MCContext &Ctx) const {
1115 const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1116 return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1117 Twine(MF->getFunctionNumber())+"$pb");
1122 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1123 const MachineBasicBlock *MBB,
1124 unsigned uid,MCContext &Ctx) const{
1125 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1126 Subtarget->isPICStyleGOT());
1127 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1130 // FIXME: @GOTOFF should be a property of MCSymbolRefExpr not in the MCSymbol.
1131 std::string Name = MBB->getSymbol(Ctx)->getName() + "@GOTOFF";
1132 return MCSymbolRefExpr::Create(Ctx.GetOrCreateSymbol(StringRef(Name)), Ctx);
1135 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1137 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1138 SelectionDAG &DAG) const {
1139 if (!Subtarget->is64Bit())
1140 // This doesn't have DebugLoc associated with it, but is not really the
1141 // same as a Register.
1142 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1147 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1148 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1150 const MCExpr *X86TargetLowering::
1151 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1152 MCContext &Ctx) const {
1153 // X86-64 uses RIP relative addressing based on the jump table label.
1154 if (Subtarget->isPICStyleRIPRel())
1155 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1157 // Otherwise, the reference is relative to the PIC base.
1158 return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1161 /// getFunctionAlignment - Return the Log2 alignment of this function.
1162 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1163 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1166 //===----------------------------------------------------------------------===//
1167 // Return Value Calling Convention Implementation
1168 //===----------------------------------------------------------------------===//
1170 #include "X86GenCallingConv.inc"
1173 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1174 const SmallVectorImpl<EVT> &OutTys,
1175 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1176 SelectionDAG &DAG) {
1177 SmallVector<CCValAssign, 16> RVLocs;
1178 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1179 RVLocs, *DAG.getContext());
1180 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1184 X86TargetLowering::LowerReturn(SDValue Chain,
1185 CallingConv::ID CallConv, bool isVarArg,
1186 const SmallVectorImpl<ISD::OutputArg> &Outs,
1187 DebugLoc dl, SelectionDAG &DAG) {
1189 SmallVector<CCValAssign, 16> RVLocs;
1190 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1191 RVLocs, *DAG.getContext());
1192 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1194 // If this is the first return lowered for this function, add the regs to the
1195 // liveout set for the function.
1196 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1197 for (unsigned i = 0; i != RVLocs.size(); ++i)
1198 if (RVLocs[i].isRegLoc())
1199 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1204 SmallVector<SDValue, 6> RetOps;
1205 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1206 // Operand #1 = Bytes To Pop
1207 RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1209 // Copy the result values into the output registers.
1210 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1211 CCValAssign &VA = RVLocs[i];
1212 assert(VA.isRegLoc() && "Can only return in registers!");
1213 SDValue ValToCopy = Outs[i].Val;
1215 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1216 // the RET instruction and handled by the FP Stackifier.
1217 if (VA.getLocReg() == X86::ST0 ||
1218 VA.getLocReg() == X86::ST1) {
1219 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1220 // change the value to the FP stack register class.
1221 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1222 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1223 RetOps.push_back(ValToCopy);
1224 // Don't emit a copytoreg.
1228 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1229 // which is returned in RAX / RDX.
1230 if (Subtarget->is64Bit()) {
1231 EVT ValVT = ValToCopy.getValueType();
1232 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1233 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1234 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1235 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1239 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1240 Flag = Chain.getValue(1);
1243 // The x86-64 ABI for returning structs by value requires that we copy
1244 // the sret argument into %rax for the return. We saved the argument into
1245 // a virtual register in the entry block, so now we copy the value out
1247 if (Subtarget->is64Bit() &&
1248 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1249 MachineFunction &MF = DAG.getMachineFunction();
1250 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1251 unsigned Reg = FuncInfo->getSRetReturnReg();
1253 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1254 FuncInfo->setSRetReturnReg(Reg);
1256 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1258 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1259 Flag = Chain.getValue(1);
1261 // RAX now acts like a return value.
1262 MF.getRegInfo().addLiveOut(X86::RAX);
1265 RetOps[0] = Chain; // Update chain.
1267 // Add the flag if we have it.
1269 RetOps.push_back(Flag);
1271 return DAG.getNode(X86ISD::RET_FLAG, dl,
1272 MVT::Other, &RetOps[0], RetOps.size());
1275 /// LowerCallResult - Lower the result values of a call into the
1276 /// appropriate copies out of appropriate physical registers.
1279 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1280 CallingConv::ID CallConv, bool isVarArg,
1281 const SmallVectorImpl<ISD::InputArg> &Ins,
1282 DebugLoc dl, SelectionDAG &DAG,
1283 SmallVectorImpl<SDValue> &InVals) {
1285 // Assign locations to each value returned by this call.
1286 SmallVector<CCValAssign, 16> RVLocs;
1287 bool Is64Bit = Subtarget->is64Bit();
1288 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1289 RVLocs, *DAG.getContext());
1290 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1292 // Copy all of the result registers out of their specified physreg.
1293 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1294 CCValAssign &VA = RVLocs[i];
1295 EVT CopyVT = VA.getValVT();
1297 // If this is x86-64, and we disabled SSE, we can't return FP values
1298 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1299 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1300 llvm_report_error("SSE register return with SSE disabled");
1303 // If this is a call to a function that returns an fp value on the floating
1304 // point stack, but where we prefer to use the value in xmm registers, copy
1305 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1306 if ((VA.getLocReg() == X86::ST0 ||
1307 VA.getLocReg() == X86::ST1) &&
1308 isScalarFPTypeInSSEReg(VA.getValVT())) {
1313 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1314 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1315 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1316 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1317 MVT::v2i64, InFlag).getValue(1);
1318 Val = Chain.getValue(0);
1319 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1320 Val, DAG.getConstant(0, MVT::i64));
1322 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1323 MVT::i64, InFlag).getValue(1);
1324 Val = Chain.getValue(0);
1326 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1328 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1329 CopyVT, InFlag).getValue(1);
1330 Val = Chain.getValue(0);
1332 InFlag = Chain.getValue(2);
1334 if (CopyVT != VA.getValVT()) {
1335 // Round the F80 the right size, which also moves to the appropriate xmm
1337 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1338 // This truncation won't change the value.
1339 DAG.getIntPtrConstant(1));
1342 InVals.push_back(Val);
1349 //===----------------------------------------------------------------------===//
1350 // C & StdCall & Fast Calling Convention implementation
1351 //===----------------------------------------------------------------------===//
1352 // StdCall calling convention seems to be standard for many Windows' API
1353 // routines and around. It differs from C calling convention just a little:
1354 // callee should clean up the stack, not caller. Symbols should be also
1355 // decorated in some fancy way :) It doesn't support any vector arguments.
1356 // For info on fast calling convention see Fast Calling Convention (tail call)
1357 // implementation LowerX86_32FastCCCallTo.
1359 /// CallIsStructReturn - Determines whether a call uses struct return
1361 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1365 return Outs[0].Flags.isSRet();
1368 /// ArgsAreStructReturn - Determines whether a function uses struct
1369 /// return semantics.
1371 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1375 return Ins[0].Flags.isSRet();
1378 /// IsCalleePop - Determines whether the callee is required to pop its
1379 /// own arguments. Callee pop is necessary to support tail calls.
1380 bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1384 switch (CallingConv) {
1387 case CallingConv::X86_StdCall:
1388 return !Subtarget->is64Bit();
1389 case CallingConv::X86_FastCall:
1390 return !Subtarget->is64Bit();
1391 case CallingConv::Fast:
1392 return PerformTailCallOpt;
1396 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1397 /// given CallingConvention value.
1398 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1399 if (Subtarget->is64Bit()) {
1400 if (Subtarget->isTargetWin64())
1401 return CC_X86_Win64_C;
1406 if (CC == CallingConv::X86_FastCall)
1407 return CC_X86_32_FastCall;
1408 else if (CC == CallingConv::Fast)
1409 return CC_X86_32_FastCC;
1414 /// NameDecorationForCallConv - Selects the appropriate decoration to
1415 /// apply to a MachineFunction containing a given calling convention.
1417 X86TargetLowering::NameDecorationForCallConv(CallingConv::ID CallConv) {
1418 if (CallConv == CallingConv::X86_FastCall)
1420 else if (CallConv == CallingConv::X86_StdCall)
1426 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1427 /// by "Src" to address "Dst" with size and alignment information specified by
1428 /// the specific parameter attribute. The copy will be passed as a byval
1429 /// function parameter.
1431 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1432 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1434 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1435 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1436 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1440 X86TargetLowering::LowerMemArgument(SDValue Chain,
1441 CallingConv::ID CallConv,
1442 const SmallVectorImpl<ISD::InputArg> &Ins,
1443 DebugLoc dl, SelectionDAG &DAG,
1444 const CCValAssign &VA,
1445 MachineFrameInfo *MFI,
1448 // Create the nodes corresponding to a load from this parameter slot.
1449 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1450 bool AlwaysUseMutable = X86::IsEligibleForTailCallOpt(CallConv);
1451 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1454 // If value is passed by pointer we have address passed instead of the value
1456 if (VA.getLocInfo() == CCValAssign::Indirect)
1457 ValVT = VA.getLocVT();
1459 ValVT = VA.getValVT();
1461 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1462 // changed with more analysis.
1463 // In case of tail call optimization mark all arguments mutable. Since they
1464 // could be overwritten by lowering of arguments in case of a tail call.
1465 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1466 VA.getLocMemOffset(), isImmutable, false);
1467 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1468 if (Flags.isByVal())
1470 return DAG.getLoad(ValVT, dl, Chain, FIN,
1471 PseudoSourceValue::getFixedStack(FI), 0);
1475 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1476 CallingConv::ID CallConv,
1478 const SmallVectorImpl<ISD::InputArg> &Ins,
1481 SmallVectorImpl<SDValue> &InVals) {
1483 MachineFunction &MF = DAG.getMachineFunction();
1484 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1486 const Function* Fn = MF.getFunction();
1487 if (Fn->hasExternalLinkage() &&
1488 Subtarget->isTargetCygMing() &&
1489 Fn->getName() == "main")
1490 FuncInfo->setForceFramePointer(true);
1492 // Decorate the function name.
1493 FuncInfo->setDecorationStyle(NameDecorationForCallConv(CallConv));
1495 MachineFrameInfo *MFI = MF.getFrameInfo();
1496 bool Is64Bit = Subtarget->is64Bit();
1497 bool IsWin64 = Subtarget->isTargetWin64();
1499 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1500 "Var args not supported with calling convention fastcc");
1502 // Assign locations to all of the incoming arguments.
1503 SmallVector<CCValAssign, 16> ArgLocs;
1504 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1505 ArgLocs, *DAG.getContext());
1506 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1508 unsigned LastVal = ~0U;
1510 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1511 CCValAssign &VA = ArgLocs[i];
1512 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1514 assert(VA.getValNo() != LastVal &&
1515 "Don't support value assigned to multiple locs yet");
1516 LastVal = VA.getValNo();
1518 if (VA.isRegLoc()) {
1519 EVT RegVT = VA.getLocVT();
1520 TargetRegisterClass *RC = NULL;
1521 if (RegVT == MVT::i32)
1522 RC = X86::GR32RegisterClass;
1523 else if (Is64Bit && RegVT == MVT::i64)
1524 RC = X86::GR64RegisterClass;
1525 else if (RegVT == MVT::f32)
1526 RC = X86::FR32RegisterClass;
1527 else if (RegVT == MVT::f64)
1528 RC = X86::FR64RegisterClass;
1529 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1530 RC = X86::VR128RegisterClass;
1531 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1532 RC = X86::VR64RegisterClass;
1534 llvm_unreachable("Unknown argument type!");
1536 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1537 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1539 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1540 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1542 if (VA.getLocInfo() == CCValAssign::SExt)
1543 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1544 DAG.getValueType(VA.getValVT()));
1545 else if (VA.getLocInfo() == CCValAssign::ZExt)
1546 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1547 DAG.getValueType(VA.getValVT()));
1548 else if (VA.getLocInfo() == CCValAssign::BCvt)
1549 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1551 if (VA.isExtInLoc()) {
1552 // Handle MMX values passed in XMM regs.
1553 if (RegVT.isVector()) {
1554 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1555 ArgValue, DAG.getConstant(0, MVT::i64));
1556 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1558 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1561 assert(VA.isMemLoc());
1562 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1565 // If value is passed via pointer - do a load.
1566 if (VA.getLocInfo() == CCValAssign::Indirect)
1567 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0);
1569 InVals.push_back(ArgValue);
1572 // The x86-64 ABI for returning structs by value requires that we copy
1573 // the sret argument into %rax for the return. Save the argument into
1574 // a virtual register so that we can access it from the return points.
1575 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1576 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1577 unsigned Reg = FuncInfo->getSRetReturnReg();
1579 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1580 FuncInfo->setSRetReturnReg(Reg);
1582 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1583 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1586 unsigned StackSize = CCInfo.getNextStackOffset();
1587 // align stack specially for tail calls
1588 if (X86::IsEligibleForTailCallOpt(CallConv))
1589 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1591 // If the function takes variable number of arguments, make a frame index for
1592 // the start of the first vararg value... for expansion of llvm.va_start.
1594 if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1595 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize, true, false);
1598 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1600 // FIXME: We should really autogenerate these arrays
1601 static const unsigned GPR64ArgRegsWin64[] = {
1602 X86::RCX, X86::RDX, X86::R8, X86::R9
1604 static const unsigned XMMArgRegsWin64[] = {
1605 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1607 static const unsigned GPR64ArgRegs64Bit[] = {
1608 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1610 static const unsigned XMMArgRegs64Bit[] = {
1611 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1612 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1614 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1617 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1618 GPR64ArgRegs = GPR64ArgRegsWin64;
1619 XMMArgRegs = XMMArgRegsWin64;
1621 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1622 GPR64ArgRegs = GPR64ArgRegs64Bit;
1623 XMMArgRegs = XMMArgRegs64Bit;
1625 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1627 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1630 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1631 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1632 "SSE register cannot be used when SSE is disabled!");
1633 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1634 "SSE register cannot be used when SSE is disabled!");
1635 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1636 // Kernel mode asks for SSE to be disabled, so don't push them
1638 TotalNumXMMRegs = 0;
1640 // For X86-64, if there are vararg parameters that are passed via
1641 // registers, then we must store them to their spots on the stack so they
1642 // may be loaded by deferencing the result of va_next.
1643 VarArgsGPOffset = NumIntRegs * 8;
1644 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1645 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1646 TotalNumXMMRegs * 16, 16,
1649 // Store the integer parameter registers.
1650 SmallVector<SDValue, 8> MemOps;
1651 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1652 unsigned Offset = VarArgsGPOffset;
1653 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1654 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1655 DAG.getIntPtrConstant(Offset));
1656 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1657 X86::GR64RegisterClass);
1658 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1660 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1661 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1663 MemOps.push_back(Store);
1667 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1668 // Now store the XMM (fp + vector) parameter registers.
1669 SmallVector<SDValue, 11> SaveXMMOps;
1670 SaveXMMOps.push_back(Chain);
1672 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1673 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1674 SaveXMMOps.push_back(ALVal);
1676 SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1677 SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1679 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1680 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1681 X86::VR128RegisterClass);
1682 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1683 SaveXMMOps.push_back(Val);
1685 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1687 &SaveXMMOps[0], SaveXMMOps.size()));
1690 if (!MemOps.empty())
1691 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1692 &MemOps[0], MemOps.size());
1696 // Some CCs need callee pop.
1697 if (IsCalleePop(isVarArg, CallConv)) {
1698 BytesToPopOnReturn = StackSize; // Callee pops everything.
1700 BytesToPopOnReturn = 0; // Callee pops nothing.
1701 // If this is an sret function, the return should pop the hidden pointer.
1702 if (!Is64Bit && CallConv != CallingConv::Fast && ArgsAreStructReturn(Ins))
1703 BytesToPopOnReturn = 4;
1707 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1708 if (CallConv == CallingConv::X86_FastCall)
1709 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1712 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1718 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1719 SDValue StackPtr, SDValue Arg,
1720 DebugLoc dl, SelectionDAG &DAG,
1721 const CCValAssign &VA,
1722 ISD::ArgFlagsTy Flags) {
1723 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1724 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1725 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1726 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1727 if (Flags.isByVal()) {
1728 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1730 return DAG.getStore(Chain, dl, Arg, PtrOff,
1731 PseudoSourceValue::getStack(), LocMemOffset);
1734 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1735 /// optimization is performed and it is required.
1737 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1738 SDValue &OutRetAddr, SDValue Chain,
1739 bool IsTailCall, bool Is64Bit,
1740 int FPDiff, DebugLoc dl) {
1741 if (!IsTailCall || FPDiff==0) return Chain;
1743 // Adjust the Return address stack slot.
1744 EVT VT = getPointerTy();
1745 OutRetAddr = getReturnAddressFrameIndex(DAG);
1747 // Load the "old" Return address.
1748 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1749 return SDValue(OutRetAddr.getNode(), 1);
1752 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1753 /// optimization is performed and it is required (FPDiff!=0).
1755 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1756 SDValue Chain, SDValue RetAddrFrIdx,
1757 bool Is64Bit, int FPDiff, DebugLoc dl) {
1758 // Store the return address to the appropriate stack slot.
1759 if (!FPDiff) return Chain;
1760 // Calculate the new stack slot for the return address.
1761 int SlotSize = Is64Bit ? 8 : 4;
1762 int NewReturnAddrFI =
1763 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, true,false);
1764 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1765 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1766 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1767 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1772 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1773 CallingConv::ID CallConv, bool isVarArg,
1775 const SmallVectorImpl<ISD::OutputArg> &Outs,
1776 const SmallVectorImpl<ISD::InputArg> &Ins,
1777 DebugLoc dl, SelectionDAG &DAG,
1778 SmallVectorImpl<SDValue> &InVals) {
1780 MachineFunction &MF = DAG.getMachineFunction();
1781 bool Is64Bit = Subtarget->is64Bit();
1782 bool IsStructRet = CallIsStructReturn(Outs);
1784 assert((!isTailCall || X86::IsEligibleForTailCallOpt(CallConv)) &&
1785 "Call is not eligible for tail call optimization!");
1786 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1787 "Var args not supported with calling convention fastcc");
1789 // Analyze operands of the call, assigning locations to each operand.
1790 SmallVector<CCValAssign, 16> ArgLocs;
1791 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1792 ArgLocs, *DAG.getContext());
1793 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1795 // Get a count of how many bytes are to be pushed on the stack.
1796 unsigned NumBytes = CCInfo.getNextStackOffset();
1797 if (X86::IsEligibleForTailCallOpt(CallConv))
1798 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1802 // Lower arguments at fp - stackoffset + fpdiff.
1803 unsigned NumBytesCallerPushed =
1804 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1805 FPDiff = NumBytesCallerPushed - NumBytes;
1807 // Set the delta of movement of the returnaddr stackslot.
1808 // But only set if delta is greater than previous delta.
1809 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1810 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1813 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1815 SDValue RetAddrFrIdx;
1816 // Load return adress for tail calls.
1817 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, Is64Bit,
1820 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1821 SmallVector<SDValue, 8> MemOpChains;
1824 // Walk the register/memloc assignments, inserting copies/loads. In the case
1825 // of tail call optimization arguments are handle later.
1826 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1827 CCValAssign &VA = ArgLocs[i];
1828 EVT RegVT = VA.getLocVT();
1829 SDValue Arg = Outs[i].Val;
1830 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1831 bool isByVal = Flags.isByVal();
1833 // Promote the value if needed.
1834 switch (VA.getLocInfo()) {
1835 default: llvm_unreachable("Unknown loc info!");
1836 case CCValAssign::Full: break;
1837 case CCValAssign::SExt:
1838 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1840 case CCValAssign::ZExt:
1841 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1843 case CCValAssign::AExt:
1844 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1845 // Special case: passing MMX values in XMM registers.
1846 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1847 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1848 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1850 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1852 case CCValAssign::BCvt:
1853 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1855 case CCValAssign::Indirect: {
1856 // Store the argument.
1857 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1858 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1859 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1860 PseudoSourceValue::getFixedStack(FI), 0);
1866 if (VA.isRegLoc()) {
1867 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1869 if (!isTailCall || (isTailCall && isByVal)) {
1870 assert(VA.isMemLoc());
1871 if (StackPtr.getNode() == 0)
1872 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1874 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1875 dl, DAG, VA, Flags));
1880 if (!MemOpChains.empty())
1881 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1882 &MemOpChains[0], MemOpChains.size());
1884 // Build a sequence of copy-to-reg nodes chained together with token chain
1885 // and flag operands which copy the outgoing args into registers.
1887 // Tail call byval lowering might overwrite argument registers so in case of
1888 // tail call optimization the copies to registers are lowered later.
1890 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1891 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1892 RegsToPass[i].second, InFlag);
1893 InFlag = Chain.getValue(1);
1897 if (Subtarget->isPICStyleGOT()) {
1898 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1901 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1902 DAG.getNode(X86ISD::GlobalBaseReg,
1903 DebugLoc::getUnknownLoc(),
1906 InFlag = Chain.getValue(1);
1908 // If we are tail calling and generating PIC/GOT style code load the
1909 // address of the callee into ECX. The value in ecx is used as target of
1910 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1911 // for tail calls on PIC/GOT architectures. Normally we would just put the
1912 // address of GOT into ebx and then call target@PLT. But for tail calls
1913 // ebx would be restored (since ebx is callee saved) before jumping to the
1916 // Note: The actual moving to ECX is done further down.
1917 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1918 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1919 !G->getGlobal()->hasProtectedVisibility())
1920 Callee = LowerGlobalAddress(Callee, DAG);
1921 else if (isa<ExternalSymbolSDNode>(Callee))
1922 Callee = LowerExternalSymbol(Callee, DAG);
1926 if (Is64Bit && isVarArg) {
1927 // From AMD64 ABI document:
1928 // For calls that may call functions that use varargs or stdargs
1929 // (prototype-less calls or calls to functions containing ellipsis (...) in
1930 // the declaration) %al is used as hidden argument to specify the number
1931 // of SSE registers used. The contents of %al do not need to match exactly
1932 // the number of registers, but must be an ubound on the number of SSE
1933 // registers used and is in the range 0 - 8 inclusive.
1935 // FIXME: Verify this on Win64
1936 // Count the number of XMM registers allocated.
1937 static const unsigned XMMArgRegs[] = {
1938 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1939 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1941 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1942 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1943 && "SSE registers cannot be used when SSE is disabled");
1945 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1946 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1947 InFlag = Chain.getValue(1);
1951 // For tail calls lower the arguments to the 'real' stack slot.
1953 // Force all the incoming stack arguments to be loaded from the stack
1954 // before any new outgoing arguments are stored to the stack, because the
1955 // outgoing stack slots may alias the incoming argument stack slots, and
1956 // the alias isn't otherwise explicit. This is slightly more conservative
1957 // than necessary, because it means that each store effectively depends
1958 // on every argument instead of just those arguments it would clobber.
1959 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1961 SmallVector<SDValue, 8> MemOpChains2;
1964 // Do not flag preceeding copytoreg stuff together with the following stuff.
1966 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1967 CCValAssign &VA = ArgLocs[i];
1968 if (!VA.isRegLoc()) {
1969 assert(VA.isMemLoc());
1970 SDValue Arg = Outs[i].Val;
1971 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1972 // Create frame index.
1973 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1974 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1975 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
1976 FIN = DAG.getFrameIndex(FI, getPointerTy());
1978 if (Flags.isByVal()) {
1979 // Copy relative to framepointer.
1980 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1981 if (StackPtr.getNode() == 0)
1982 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1984 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1986 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
1990 // Store relative to framepointer.
1991 MemOpChains2.push_back(
1992 DAG.getStore(ArgChain, dl, Arg, FIN,
1993 PseudoSourceValue::getFixedStack(FI), 0));
1998 if (!MemOpChains2.empty())
1999 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2000 &MemOpChains2[0], MemOpChains2.size());
2002 // Copy arguments to their registers.
2003 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2004 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2005 RegsToPass[i].second, InFlag);
2006 InFlag = Chain.getValue(1);
2010 // Store the return address to the appropriate stack slot.
2011 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2015 bool WasGlobalOrExternal = false;
2016 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2017 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2018 // In the 64-bit large code model, we have to make all calls
2019 // through a register, since the call instruction's 32-bit
2020 // pc-relative offset may not be large enough to hold the whole
2022 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2023 WasGlobalOrExternal = true;
2024 // If the callee is a GlobalAddress node (quite common, every direct call
2025 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2028 // We should use extra load for direct calls to dllimported functions in
2030 GlobalValue *GV = G->getGlobal();
2031 if (!GV->hasDLLImportLinkage()) {
2032 unsigned char OpFlags = 0;
2034 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2035 // external symbols most go through the PLT in PIC mode. If the symbol
2036 // has hidden or protected visibility, or if it is static or local, then
2037 // we don't need to use the PLT - we can directly call it.
2038 if (Subtarget->isTargetELF() &&
2039 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2040 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2041 OpFlags = X86II::MO_PLT;
2042 } else if (Subtarget->isPICStyleStubAny() &&
2043 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2044 Subtarget->getDarwinVers() < 9) {
2045 // PC-relative references to external symbols should go through $stub,
2046 // unless we're building with the leopard linker or later, which
2047 // automatically synthesizes these stubs.
2048 OpFlags = X86II::MO_DARWIN_STUB;
2051 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2052 G->getOffset(), OpFlags);
2054 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2055 WasGlobalOrExternal = true;
2056 unsigned char OpFlags = 0;
2058 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2059 // symbols should go through the PLT.
2060 if (Subtarget->isTargetELF() &&
2061 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2062 OpFlags = X86II::MO_PLT;
2063 } else if (Subtarget->isPICStyleStubAny() &&
2064 Subtarget->getDarwinVers() < 9) {
2065 // PC-relative references to external symbols should go through $stub,
2066 // unless we're building with the leopard linker or later, which
2067 // automatically synthesizes these stubs.
2068 OpFlags = X86II::MO_DARWIN_STUB;
2071 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2075 if (isTailCall && !WasGlobalOrExternal) {
2076 unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
2078 Chain = DAG.getCopyToReg(Chain, dl,
2079 DAG.getRegister(Opc, getPointerTy()),
2081 Callee = DAG.getRegister(Opc, getPointerTy());
2082 // Add register as live out.
2083 MF.getRegInfo().addLiveOut(Opc);
2086 // Returns a chain & a flag for retval copy to use.
2087 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2088 SmallVector<SDValue, 8> Ops;
2091 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2092 DAG.getIntPtrConstant(0, true), InFlag);
2093 InFlag = Chain.getValue(1);
2096 Ops.push_back(Chain);
2097 Ops.push_back(Callee);
2100 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2102 // Add argument registers to the end of the list so that they are known live
2104 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2105 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2106 RegsToPass[i].second.getValueType()));
2108 // Add an implicit use GOT pointer in EBX.
2109 if (!isTailCall && Subtarget->isPICStyleGOT())
2110 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2112 // Add an implicit use of AL for x86 vararg functions.
2113 if (Is64Bit && isVarArg)
2114 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2116 if (InFlag.getNode())
2117 Ops.push_back(InFlag);
2120 // If this is the first return lowered for this function, add the regs
2121 // to the liveout set for the function.
2122 if (MF.getRegInfo().liveout_empty()) {
2123 SmallVector<CCValAssign, 16> RVLocs;
2124 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2126 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2127 for (unsigned i = 0; i != RVLocs.size(); ++i)
2128 if (RVLocs[i].isRegLoc())
2129 MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2132 assert(((Callee.getOpcode() == ISD::Register &&
2133 (cast<RegisterSDNode>(Callee)->getReg() == X86::EAX ||
2134 cast<RegisterSDNode>(Callee)->getReg() == X86::R11)) ||
2135 Callee.getOpcode() == ISD::TargetExternalSymbol ||
2136 Callee.getOpcode() == ISD::TargetGlobalAddress) &&
2137 "Expecting a global address, external symbol, or scratch register");
2139 return DAG.getNode(X86ISD::TC_RETURN, dl,
2140 NodeTys, &Ops[0], Ops.size());
2143 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2144 InFlag = Chain.getValue(1);
2146 // Create the CALLSEQ_END node.
2147 unsigned NumBytesForCalleeToPush;
2148 if (IsCalleePop(isVarArg, CallConv))
2149 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2150 else if (!Is64Bit && CallConv != CallingConv::Fast && IsStructRet)
2151 // If this is is a call to a struct-return function, the callee
2152 // pops the hidden struct pointer, so we have to push it back.
2153 // This is common for Darwin/X86, Linux & Mingw32 targets.
2154 NumBytesForCalleeToPush = 4;
2156 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2158 // Returns a flag for retval copy to use.
2159 Chain = DAG.getCALLSEQ_END(Chain,
2160 DAG.getIntPtrConstant(NumBytes, true),
2161 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2164 InFlag = Chain.getValue(1);
2166 // Handle result values, copying them out of physregs into vregs that we
2168 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2169 Ins, dl, DAG, InVals);
2173 //===----------------------------------------------------------------------===//
2174 // Fast Calling Convention (tail call) implementation
2175 //===----------------------------------------------------------------------===//
2177 // Like std call, callee cleans arguments, convention except that ECX is
2178 // reserved for storing the tail called function address. Only 2 registers are
2179 // free for argument passing (inreg). Tail call optimization is performed
2181 // * tailcallopt is enabled
2182 // * caller/callee are fastcc
2183 // On X86_64 architecture with GOT-style position independent code only local
2184 // (within module) calls are supported at the moment.
2185 // To keep the stack aligned according to platform abi the function
2186 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2187 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2188 // If a tail called function callee has more arguments than the caller the
2189 // caller needs to make sure that there is room to move the RETADDR to. This is
2190 // achieved by reserving an area the size of the argument delta right after the
2191 // original REtADDR, but before the saved framepointer or the spilled registers
2192 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2204 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2205 /// for a 16 byte align requirement.
2206 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2207 SelectionDAG& DAG) {
2208 MachineFunction &MF = DAG.getMachineFunction();
2209 const TargetMachine &TM = MF.getTarget();
2210 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2211 unsigned StackAlignment = TFI.getStackAlignment();
2212 uint64_t AlignMask = StackAlignment - 1;
2213 int64_t Offset = StackSize;
2214 uint64_t SlotSize = TD->getPointerSize();
2215 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2216 // Number smaller than 12 so just add the difference.
2217 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2219 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2220 Offset = ((~AlignMask) & Offset) + StackAlignment +
2221 (StackAlignment-SlotSize);
2226 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2227 /// for tail call optimization. Targets which want to do tail call
2228 /// optimization should implement this function.
2230 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2231 CallingConv::ID CalleeCC,
2233 const SmallVectorImpl<ISD::InputArg> &Ins,
2234 SelectionDAG& DAG) const {
2235 return X86::IsEligibleForTailCallOpt(CalleeCC) &&
2236 DAG.getMachineFunction().getFunction()->getCallingConv() == CalleeCC;
2240 X86TargetLowering::createFastISel(MachineFunction &mf, MachineModuleInfo *mmo,
2242 DenseMap<const Value *, unsigned> &vm,
2243 DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2244 DenseMap<const AllocaInst *, int> &am
2246 , SmallSet<Instruction*, 8> &cil
2249 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2257 //===----------------------------------------------------------------------===//
2258 // Other Lowering Hooks
2259 //===----------------------------------------------------------------------===//
2262 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2263 MachineFunction &MF = DAG.getMachineFunction();
2264 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2265 int ReturnAddrIndex = FuncInfo->getRAIndex();
2267 if (ReturnAddrIndex == 0) {
2268 // Set up a frame object for the return address.
2269 uint64_t SlotSize = TD->getPointerSize();
2270 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2272 FuncInfo->setRAIndex(ReturnAddrIndex);
2275 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2279 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2280 bool hasSymbolicDisplacement) {
2281 // Offset should fit into 32 bit immediate field.
2282 if (!isInt32(Offset))
2285 // If we don't have a symbolic displacement - we don't have any extra
2287 if (!hasSymbolicDisplacement)
2290 // FIXME: Some tweaks might be needed for medium code model.
2291 if (M != CodeModel::Small && M != CodeModel::Kernel)
2294 // For small code model we assume that latest object is 16MB before end of 31
2295 // bits boundary. We may also accept pretty large negative constants knowing
2296 // that all objects are in the positive half of address space.
2297 if (M == CodeModel::Small && Offset < 16*1024*1024)
2300 // For kernel code model we know that all object resist in the negative half
2301 // of 32bits address space. We may not accept negative offsets, since they may
2302 // be just off and we may accept pretty large positive ones.
2303 if (M == CodeModel::Kernel && Offset > 0)
2309 bool X86::IsEligibleForTailCallOpt(CallingConv::ID CC) {
2310 return PerformTailCallOpt && CC == CallingConv::Fast;
2313 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2314 /// specific condition code, returning the condition code and the LHS/RHS of the
2315 /// comparison to make.
2316 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2317 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2319 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2320 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2321 // X > -1 -> X == 0, jump !sign.
2322 RHS = DAG.getConstant(0, RHS.getValueType());
2323 return X86::COND_NS;
2324 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2325 // X < 0 -> X == 0, jump on sign.
2327 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2329 RHS = DAG.getConstant(0, RHS.getValueType());
2330 return X86::COND_LE;
2334 switch (SetCCOpcode) {
2335 default: llvm_unreachable("Invalid integer condition!");
2336 case ISD::SETEQ: return X86::COND_E;
2337 case ISD::SETGT: return X86::COND_G;
2338 case ISD::SETGE: return X86::COND_GE;
2339 case ISD::SETLT: return X86::COND_L;
2340 case ISD::SETLE: return X86::COND_LE;
2341 case ISD::SETNE: return X86::COND_NE;
2342 case ISD::SETULT: return X86::COND_B;
2343 case ISD::SETUGT: return X86::COND_A;
2344 case ISD::SETULE: return X86::COND_BE;
2345 case ISD::SETUGE: return X86::COND_AE;
2349 // First determine if it is required or is profitable to flip the operands.
2351 // If LHS is a foldable load, but RHS is not, flip the condition.
2352 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2353 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2354 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2355 std::swap(LHS, RHS);
2358 switch (SetCCOpcode) {
2364 std::swap(LHS, RHS);
2368 // On a floating point condition, the flags are set as follows:
2370 // 0 | 0 | 0 | X > Y
2371 // 0 | 0 | 1 | X < Y
2372 // 1 | 0 | 0 | X == Y
2373 // 1 | 1 | 1 | unordered
2374 switch (SetCCOpcode) {
2375 default: llvm_unreachable("Condcode should be pre-legalized away");
2377 case ISD::SETEQ: return X86::COND_E;
2378 case ISD::SETOLT: // flipped
2380 case ISD::SETGT: return X86::COND_A;
2381 case ISD::SETOLE: // flipped
2383 case ISD::SETGE: return X86::COND_AE;
2384 case ISD::SETUGT: // flipped
2386 case ISD::SETLT: return X86::COND_B;
2387 case ISD::SETUGE: // flipped
2389 case ISD::SETLE: return X86::COND_BE;
2391 case ISD::SETNE: return X86::COND_NE;
2392 case ISD::SETUO: return X86::COND_P;
2393 case ISD::SETO: return X86::COND_NP;
2395 case ISD::SETUNE: return X86::COND_INVALID;
2399 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2400 /// code. Current x86 isa includes the following FP cmov instructions:
2401 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2402 static bool hasFPCMov(unsigned X86CC) {
2418 /// isFPImmLegal - Returns true if the target can instruction select the
2419 /// specified FP immediate natively. If false, the legalizer will
2420 /// materialize the FP immediate as a load from a constant pool.
2421 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2422 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2423 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2429 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2430 /// the specified range (L, H].
2431 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2432 return (Val < 0) || (Val >= Low && Val < Hi);
2435 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2436 /// specified value.
2437 static bool isUndefOrEqual(int Val, int CmpVal) {
2438 if (Val < 0 || Val == CmpVal)
2443 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2444 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2445 /// the second operand.
2446 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2447 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2448 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2449 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2450 return (Mask[0] < 2 && Mask[1] < 2);
2454 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2455 SmallVector<int, 8> M;
2457 return ::isPSHUFDMask(M, N->getValueType(0));
2460 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2461 /// is suitable for input to PSHUFHW.
2462 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2463 if (VT != MVT::v8i16)
2466 // Lower quadword copied in order or undef.
2467 for (int i = 0; i != 4; ++i)
2468 if (Mask[i] >= 0 && Mask[i] != i)
2471 // Upper quadword shuffled.
2472 for (int i = 4; i != 8; ++i)
2473 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2479 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2480 SmallVector<int, 8> M;
2482 return ::isPSHUFHWMask(M, N->getValueType(0));
2485 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2486 /// is suitable for input to PSHUFLW.
2487 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2488 if (VT != MVT::v8i16)
2491 // Upper quadword copied in order.
2492 for (int i = 4; i != 8; ++i)
2493 if (Mask[i] >= 0 && Mask[i] != i)
2496 // Lower quadword shuffled.
2497 for (int i = 0; i != 4; ++i)
2504 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2505 SmallVector<int, 8> M;
2507 return ::isPSHUFLWMask(M, N->getValueType(0));
2510 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2511 /// is suitable for input to PALIGNR.
2512 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2514 int i, e = VT.getVectorNumElements();
2516 // Do not handle v2i64 / v2f64 shuffles with palignr.
2517 if (e < 4 || !hasSSSE3)
2520 for (i = 0; i != e; ++i)
2524 // All undef, not a palignr.
2528 // Determine if it's ok to perform a palignr with only the LHS, since we
2529 // don't have access to the actual shuffle elements to see if RHS is undef.
2530 bool Unary = Mask[i] < (int)e;
2531 bool NeedsUnary = false;
2533 int s = Mask[i] - i;
2535 // Check the rest of the elements to see if they are consecutive.
2536 for (++i; i != e; ++i) {
2541 Unary = Unary && (m < (int)e);
2542 NeedsUnary = NeedsUnary || (m < s);
2544 if (NeedsUnary && !Unary)
2546 if (Unary && m != ((s+i) & (e-1)))
2548 if (!Unary && m != (s+i))
2554 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2555 SmallVector<int, 8> M;
2557 return ::isPALIGNRMask(M, N->getValueType(0), true);
2560 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2561 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2562 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2563 int NumElems = VT.getVectorNumElements();
2564 if (NumElems != 2 && NumElems != 4)
2567 int Half = NumElems / 2;
2568 for (int i = 0; i < Half; ++i)
2569 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2571 for (int i = Half; i < NumElems; ++i)
2572 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2578 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2579 SmallVector<int, 8> M;
2581 return ::isSHUFPMask(M, N->getValueType(0));
2584 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2585 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2586 /// half elements to come from vector 1 (which would equal the dest.) and
2587 /// the upper half to come from vector 2.
2588 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2589 int NumElems = VT.getVectorNumElements();
2591 if (NumElems != 2 && NumElems != 4)
2594 int Half = NumElems / 2;
2595 for (int i = 0; i < Half; ++i)
2596 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2598 for (int i = Half; i < NumElems; ++i)
2599 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2604 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2605 SmallVector<int, 8> M;
2607 return isCommutedSHUFPMask(M, N->getValueType(0));
2610 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2611 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2612 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2613 if (N->getValueType(0).getVectorNumElements() != 4)
2616 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2617 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2618 isUndefOrEqual(N->getMaskElt(1), 7) &&
2619 isUndefOrEqual(N->getMaskElt(2), 2) &&
2620 isUndefOrEqual(N->getMaskElt(3), 3);
2623 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2624 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2626 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2627 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2632 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2633 isUndefOrEqual(N->getMaskElt(1), 3) &&
2634 isUndefOrEqual(N->getMaskElt(2), 2) &&
2635 isUndefOrEqual(N->getMaskElt(3), 3);
2638 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2639 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2640 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2641 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2643 if (NumElems != 2 && NumElems != 4)
2646 for (unsigned i = 0; i < NumElems/2; ++i)
2647 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2650 for (unsigned i = NumElems/2; i < NumElems; ++i)
2651 if (!isUndefOrEqual(N->getMaskElt(i), i))
2657 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2658 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2659 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2660 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2662 if (NumElems != 2 && NumElems != 4)
2665 for (unsigned i = 0; i < NumElems/2; ++i)
2666 if (!isUndefOrEqual(N->getMaskElt(i), i))
2669 for (unsigned i = 0; i < NumElems/2; ++i)
2670 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2676 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2677 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2678 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2679 bool V2IsSplat = false) {
2680 int NumElts = VT.getVectorNumElements();
2681 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2684 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2686 int BitI1 = Mask[i+1];
2687 if (!isUndefOrEqual(BitI, j))
2690 if (!isUndefOrEqual(BitI1, NumElts))
2693 if (!isUndefOrEqual(BitI1, j + NumElts))
2700 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2701 SmallVector<int, 8> M;
2703 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2706 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2707 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2708 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2709 bool V2IsSplat = false) {
2710 int NumElts = VT.getVectorNumElements();
2711 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2714 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2716 int BitI1 = Mask[i+1];
2717 if (!isUndefOrEqual(BitI, j + NumElts/2))
2720 if (isUndefOrEqual(BitI1, NumElts))
2723 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2730 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2731 SmallVector<int, 8> M;
2733 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2736 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2737 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2739 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2740 int NumElems = VT.getVectorNumElements();
2741 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2744 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2746 int BitI1 = Mask[i+1];
2747 if (!isUndefOrEqual(BitI, j))
2749 if (!isUndefOrEqual(BitI1, j))
2755 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2756 SmallVector<int, 8> M;
2758 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2761 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2762 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2764 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2765 int NumElems = VT.getVectorNumElements();
2766 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2769 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2771 int BitI1 = Mask[i+1];
2772 if (!isUndefOrEqual(BitI, j))
2774 if (!isUndefOrEqual(BitI1, j))
2780 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2781 SmallVector<int, 8> M;
2783 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2786 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2787 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2788 /// MOVSD, and MOVD, i.e. setting the lowest element.
2789 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2790 if (VT.getVectorElementType().getSizeInBits() < 32)
2793 int NumElts = VT.getVectorNumElements();
2795 if (!isUndefOrEqual(Mask[0], NumElts))
2798 for (int i = 1; i < NumElts; ++i)
2799 if (!isUndefOrEqual(Mask[i], i))
2805 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2806 SmallVector<int, 8> M;
2808 return ::isMOVLMask(M, N->getValueType(0));
2811 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2812 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2813 /// element of vector 2 and the other elements to come from vector 1 in order.
2814 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2815 bool V2IsSplat = false, bool V2IsUndef = false) {
2816 int NumOps = VT.getVectorNumElements();
2817 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2820 if (!isUndefOrEqual(Mask[0], 0))
2823 for (int i = 1; i < NumOps; ++i)
2824 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2825 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2826 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2832 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2833 bool V2IsUndef = false) {
2834 SmallVector<int, 8> M;
2836 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2839 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2840 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2841 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2842 if (N->getValueType(0).getVectorNumElements() != 4)
2845 // Expect 1, 1, 3, 3
2846 for (unsigned i = 0; i < 2; ++i) {
2847 int Elt = N->getMaskElt(i);
2848 if (Elt >= 0 && Elt != 1)
2853 for (unsigned i = 2; i < 4; ++i) {
2854 int Elt = N->getMaskElt(i);
2855 if (Elt >= 0 && Elt != 3)
2860 // Don't use movshdup if it can be done with a shufps.
2861 // FIXME: verify that matching u, u, 3, 3 is what we want.
2865 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2866 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2867 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2868 if (N->getValueType(0).getVectorNumElements() != 4)
2871 // Expect 0, 0, 2, 2
2872 for (unsigned i = 0; i < 2; ++i)
2873 if (N->getMaskElt(i) > 0)
2877 for (unsigned i = 2; i < 4; ++i) {
2878 int Elt = N->getMaskElt(i);
2879 if (Elt >= 0 && Elt != 2)
2884 // Don't use movsldup if it can be done with a shufps.
2888 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2889 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2890 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2891 int e = N->getValueType(0).getVectorNumElements() / 2;
2893 for (int i = 0; i < e; ++i)
2894 if (!isUndefOrEqual(N->getMaskElt(i), i))
2896 for (int i = 0; i < e; ++i)
2897 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2902 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2903 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
2904 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2905 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2906 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2908 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2910 for (int i = 0; i < NumOperands; ++i) {
2911 int Val = SVOp->getMaskElt(NumOperands-i-1);
2912 if (Val < 0) Val = 0;
2913 if (Val >= NumOperands) Val -= NumOperands;
2915 if (i != NumOperands - 1)
2921 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2922 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
2923 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2924 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2926 // 8 nodes, but we only care about the last 4.
2927 for (unsigned i = 7; i >= 4; --i) {
2928 int Val = SVOp->getMaskElt(i);
2937 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2938 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
2939 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2940 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2942 // 8 nodes, but we only care about the first 4.
2943 for (int i = 3; i >= 0; --i) {
2944 int Val = SVOp->getMaskElt(i);
2953 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
2954 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
2955 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
2956 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2957 EVT VVT = N->getValueType(0);
2958 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
2962 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
2963 Val = SVOp->getMaskElt(i);
2967 return (Val - i) * EltSize;
2970 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2972 bool X86::isZeroNode(SDValue Elt) {
2973 return ((isa<ConstantSDNode>(Elt) &&
2974 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2975 (isa<ConstantFPSDNode>(Elt) &&
2976 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2979 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2980 /// their permute mask.
2981 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2982 SelectionDAG &DAG) {
2983 EVT VT = SVOp->getValueType(0);
2984 unsigned NumElems = VT.getVectorNumElements();
2985 SmallVector<int, 8> MaskVec;
2987 for (unsigned i = 0; i != NumElems; ++i) {
2988 int idx = SVOp->getMaskElt(i);
2990 MaskVec.push_back(idx);
2991 else if (idx < (int)NumElems)
2992 MaskVec.push_back(idx + NumElems);
2994 MaskVec.push_back(idx - NumElems);
2996 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2997 SVOp->getOperand(0), &MaskVec[0]);
3000 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3001 /// the two vector operands have swapped position.
3002 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3003 unsigned NumElems = VT.getVectorNumElements();
3004 for (unsigned i = 0; i != NumElems; ++i) {
3008 else if (idx < (int)NumElems)
3009 Mask[i] = idx + NumElems;
3011 Mask[i] = idx - NumElems;
3015 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3016 /// match movhlps. The lower half elements should come from upper half of
3017 /// V1 (and in order), and the upper half elements should come from the upper
3018 /// half of V2 (and in order).
3019 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3020 if (Op->getValueType(0).getVectorNumElements() != 4)
3022 for (unsigned i = 0, e = 2; i != e; ++i)
3023 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3025 for (unsigned i = 2; i != 4; ++i)
3026 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3031 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3032 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3034 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3035 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3037 N = N->getOperand(0).getNode();
3038 if (!ISD::isNON_EXTLoad(N))
3041 *LD = cast<LoadSDNode>(N);
3045 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3046 /// match movlp{s|d}. The lower half elements should come from lower half of
3047 /// V1 (and in order), and the upper half elements should come from the upper
3048 /// half of V2 (and in order). And since V1 will become the source of the
3049 /// MOVLP, it must be either a vector load or a scalar load to vector.
3050 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3051 ShuffleVectorSDNode *Op) {
3052 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3054 // Is V2 is a vector load, don't do this transformation. We will try to use
3055 // load folding shufps op.
3056 if (ISD::isNON_EXTLoad(V2))
3059 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3061 if (NumElems != 2 && NumElems != 4)
3063 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3064 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3066 for (unsigned i = NumElems/2; i != NumElems; ++i)
3067 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3072 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3074 static bool isSplatVector(SDNode *N) {
3075 if (N->getOpcode() != ISD::BUILD_VECTOR)
3078 SDValue SplatValue = N->getOperand(0);
3079 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3080 if (N->getOperand(i) != SplatValue)
3085 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3086 /// to an zero vector.
3087 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3088 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3089 SDValue V1 = N->getOperand(0);
3090 SDValue V2 = N->getOperand(1);
3091 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3092 for (unsigned i = 0; i != NumElems; ++i) {
3093 int Idx = N->getMaskElt(i);
3094 if (Idx >= (int)NumElems) {
3095 unsigned Opc = V2.getOpcode();
3096 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3098 if (Opc != ISD::BUILD_VECTOR ||
3099 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3101 } else if (Idx >= 0) {
3102 unsigned Opc = V1.getOpcode();
3103 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3105 if (Opc != ISD::BUILD_VECTOR ||
3106 !X86::isZeroNode(V1.getOperand(Idx)))
3113 /// getZeroVector - Returns a vector of specified type with all zero elements.
3115 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3117 assert(VT.isVector() && "Expected a vector type");
3119 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3120 // type. This ensures they get CSE'd.
3122 if (VT.getSizeInBits() == 64) { // MMX
3123 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3124 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3125 } else if (HasSSE2) { // SSE2
3126 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3127 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3129 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3130 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3132 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3135 /// getOnesVector - Returns a vector of specified type with all bits set.
3137 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3138 assert(VT.isVector() && "Expected a vector type");
3140 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3141 // type. This ensures they get CSE'd.
3142 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3144 if (VT.getSizeInBits() == 64) // MMX
3145 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3147 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3148 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3152 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3153 /// that point to V2 points to its first element.
3154 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3155 EVT VT = SVOp->getValueType(0);
3156 unsigned NumElems = VT.getVectorNumElements();
3158 bool Changed = false;
3159 SmallVector<int, 8> MaskVec;
3160 SVOp->getMask(MaskVec);
3162 for (unsigned i = 0; i != NumElems; ++i) {
3163 if (MaskVec[i] > (int)NumElems) {
3164 MaskVec[i] = NumElems;
3169 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3170 SVOp->getOperand(1), &MaskVec[0]);
3171 return SDValue(SVOp, 0);
3174 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3175 /// operation of specified width.
3176 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3178 unsigned NumElems = VT.getVectorNumElements();
3179 SmallVector<int, 8> Mask;
3180 Mask.push_back(NumElems);
3181 for (unsigned i = 1; i != NumElems; ++i)
3183 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3186 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3187 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3189 unsigned NumElems = VT.getVectorNumElements();
3190 SmallVector<int, 8> Mask;
3191 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3193 Mask.push_back(i + NumElems);
3195 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3198 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3199 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3201 unsigned NumElems = VT.getVectorNumElements();
3202 unsigned Half = NumElems/2;
3203 SmallVector<int, 8> Mask;
3204 for (unsigned i = 0; i != Half; ++i) {
3205 Mask.push_back(i + Half);
3206 Mask.push_back(i + NumElems + Half);
3208 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3211 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3212 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3214 if (SV->getValueType(0).getVectorNumElements() <= 4)
3215 return SDValue(SV, 0);
3217 EVT PVT = MVT::v4f32;
3218 EVT VT = SV->getValueType(0);
3219 DebugLoc dl = SV->getDebugLoc();
3220 SDValue V1 = SV->getOperand(0);
3221 int NumElems = VT.getVectorNumElements();
3222 int EltNo = SV->getSplatIndex();
3224 // unpack elements to the correct location
3225 while (NumElems > 4) {
3226 if (EltNo < NumElems/2) {
3227 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3229 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3230 EltNo -= NumElems/2;
3235 // Perform the splat.
3236 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3237 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3238 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3239 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3242 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3243 /// vector of zero or undef vector. This produces a shuffle where the low
3244 /// element of V2 is swizzled into the zero/undef vector, landing at element
3245 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3246 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3247 bool isZero, bool HasSSE2,
3248 SelectionDAG &DAG) {
3249 EVT VT = V2.getValueType();
3251 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3252 unsigned NumElems = VT.getVectorNumElements();
3253 SmallVector<int, 16> MaskVec;
3254 for (unsigned i = 0; i != NumElems; ++i)
3255 // If this is the insertion idx, put the low elt of V2 here.
3256 MaskVec.push_back(i == Idx ? NumElems : i);
3257 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3260 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3261 /// a shuffle that is zero.
3263 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3264 bool Low, SelectionDAG &DAG) {
3265 unsigned NumZeros = 0;
3266 for (int i = 0; i < NumElems; ++i) {
3267 unsigned Index = Low ? i : NumElems-i-1;
3268 int Idx = SVOp->getMaskElt(Index);
3273 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3274 if (Elt.getNode() && X86::isZeroNode(Elt))
3282 /// isVectorShift - Returns true if the shuffle can be implemented as a
3283 /// logical left or right shift of a vector.
3284 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3285 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3286 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3287 int NumElems = SVOp->getValueType(0).getVectorNumElements();
3290 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3293 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3297 bool SeenV1 = false;
3298 bool SeenV2 = false;
3299 for (int i = NumZeros; i < NumElems; ++i) {
3300 int Val = isLeft ? (i - NumZeros) : i;
3301 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3313 if (SeenV1 && SeenV2)
3316 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3322 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3324 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3325 unsigned NumNonZero, unsigned NumZero,
3326 SelectionDAG &DAG, TargetLowering &TLI) {
3330 DebugLoc dl = Op.getDebugLoc();
3333 for (unsigned i = 0; i < 16; ++i) {
3334 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3335 if (ThisIsNonZero && First) {
3337 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3339 V = DAG.getUNDEF(MVT::v8i16);
3344 SDValue ThisElt(0, 0), LastElt(0, 0);
3345 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3346 if (LastIsNonZero) {
3347 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3348 MVT::i16, Op.getOperand(i-1));
3350 if (ThisIsNonZero) {
3351 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3352 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3353 ThisElt, DAG.getConstant(8, MVT::i8));
3355 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3359 if (ThisElt.getNode())
3360 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3361 DAG.getIntPtrConstant(i/2));
3365 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3368 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3370 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3371 unsigned NumNonZero, unsigned NumZero,
3372 SelectionDAG &DAG, TargetLowering &TLI) {
3376 DebugLoc dl = Op.getDebugLoc();
3379 for (unsigned i = 0; i < 8; ++i) {
3380 bool isNonZero = (NonZeros & (1 << i)) != 0;
3384 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3386 V = DAG.getUNDEF(MVT::v8i16);
3389 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3390 MVT::v8i16, V, Op.getOperand(i),
3391 DAG.getIntPtrConstant(i));
3398 /// getVShift - Return a vector logical shift node.
3400 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3401 unsigned NumBits, SelectionDAG &DAG,
3402 const TargetLowering &TLI, DebugLoc dl) {
3403 bool isMMX = VT.getSizeInBits() == 64;
3404 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3405 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3406 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3407 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3408 DAG.getNode(Opc, dl, ShVT, SrcOp,
3409 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3413 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3414 SelectionDAG &DAG) {
3416 // Check if the scalar load can be widened into a vector load. And if
3417 // the address is "base + cst" see if the cst can be "absorbed" into
3418 // the shuffle mask.
3419 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3420 SDValue Ptr = LD->getBasePtr();
3421 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3423 EVT PVT = LD->getValueType(0);
3424 if (PVT != MVT::i32 && PVT != MVT::f32)
3429 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3430 FI = FINode->getIndex();
3432 } else if (Ptr.getOpcode() == ISD::ADD &&
3433 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3434 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3435 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3436 Offset = Ptr.getConstantOperandVal(1);
3437 Ptr = Ptr.getOperand(0);
3442 SDValue Chain = LD->getChain();
3443 // Make sure the stack object alignment is at least 16.
3444 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3445 if (DAG.InferPtrAlignment(Ptr) < 16) {
3446 if (MFI->isFixedObjectIndex(FI)) {
3447 // Can't change the alignment. FIXME: It's possible to compute
3448 // the exact stack offset and reference FI + adjust offset instead.
3449 // If someone *really* cares about this. That's the way to implement it.
3452 MFI->setObjectAlignment(FI, 16);
3456 // (Offset % 16) must be multiple of 4. Then address is then
3457 // Ptr + (Offset & ~15).
3460 if ((Offset % 16) & 3)
3462 int64_t StartOffset = Offset & ~15;
3464 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3465 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3467 int EltNo = (Offset - StartOffset) >> 2;
3468 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3469 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3470 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0);
3471 // Canonicalize it to a v4i32 shuffle.
3472 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3473 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3474 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3475 DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3482 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3483 DebugLoc dl = Op.getDebugLoc();
3484 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3485 if (ISD::isBuildVectorAllZeros(Op.getNode())
3486 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3487 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3488 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3489 // eliminated on x86-32 hosts.
3490 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3493 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3494 return getOnesVector(Op.getValueType(), DAG, dl);
3495 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3498 EVT VT = Op.getValueType();
3499 EVT ExtVT = VT.getVectorElementType();
3500 unsigned EVTBits = ExtVT.getSizeInBits();
3502 unsigned NumElems = Op.getNumOperands();
3503 unsigned NumZero = 0;
3504 unsigned NumNonZero = 0;
3505 unsigned NonZeros = 0;
3506 bool IsAllConstants = true;
3507 SmallSet<SDValue, 8> Values;
3508 for (unsigned i = 0; i < NumElems; ++i) {
3509 SDValue Elt = Op.getOperand(i);
3510 if (Elt.getOpcode() == ISD::UNDEF)
3513 if (Elt.getOpcode() != ISD::Constant &&
3514 Elt.getOpcode() != ISD::ConstantFP)
3515 IsAllConstants = false;
3516 if (X86::isZeroNode(Elt))
3519 NonZeros |= (1 << i);
3524 if (NumNonZero == 0) {
3525 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3526 return DAG.getUNDEF(VT);
3529 // Special case for single non-zero, non-undef, element.
3530 if (NumNonZero == 1) {
3531 unsigned Idx = CountTrailingZeros_32(NonZeros);
3532 SDValue Item = Op.getOperand(Idx);
3534 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3535 // the value are obviously zero, truncate the value to i32 and do the
3536 // insertion that way. Only do this if the value is non-constant or if the
3537 // value is a constant being inserted into element 0. It is cheaper to do
3538 // a constant pool load than it is to do a movd + shuffle.
3539 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3540 (!IsAllConstants || Idx == 0)) {
3541 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3542 // Handle MMX and SSE both.
3543 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3544 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3546 // Truncate the value (which may itself be a constant) to i32, and
3547 // convert it to a vector with movd (S2V+shuffle to zero extend).
3548 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3549 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3550 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3551 Subtarget->hasSSE2(), DAG);
3553 // Now we have our 32-bit value zero extended in the low element of
3554 // a vector. If Idx != 0, swizzle it into place.
3556 SmallVector<int, 4> Mask;
3557 Mask.push_back(Idx);
3558 for (unsigned i = 1; i != VecElts; ++i)
3560 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3561 DAG.getUNDEF(Item.getValueType()),
3564 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3568 // If we have a constant or non-constant insertion into the low element of
3569 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3570 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3571 // depending on what the source datatype is.
3574 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3575 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3576 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3577 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3578 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3579 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3581 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3582 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3583 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3584 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3585 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3586 Subtarget->hasSSE2(), DAG);
3587 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3591 // Is it a vector logical left shift?
3592 if (NumElems == 2 && Idx == 1 &&
3593 X86::isZeroNode(Op.getOperand(0)) &&
3594 !X86::isZeroNode(Op.getOperand(1))) {
3595 unsigned NumBits = VT.getSizeInBits();
3596 return getVShift(true, VT,
3597 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3598 VT, Op.getOperand(1)),
3599 NumBits/2, DAG, *this, dl);
3602 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3605 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3606 // is a non-constant being inserted into an element other than the low one,
3607 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3608 // movd/movss) to move this into the low element, then shuffle it into
3610 if (EVTBits == 32) {
3611 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3613 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3614 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3615 Subtarget->hasSSE2(), DAG);
3616 SmallVector<int, 8> MaskVec;
3617 for (unsigned i = 0; i < NumElems; i++)
3618 MaskVec.push_back(i == Idx ? 0 : 1);
3619 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3623 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3624 if (Values.size() == 1) {
3625 if (EVTBits == 32) {
3626 // Instead of a shuffle like this:
3627 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3628 // Check if it's possible to issue this instead.
3629 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3630 unsigned Idx = CountTrailingZeros_32(NonZeros);
3631 SDValue Item = Op.getOperand(Idx);
3632 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3633 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3638 // A vector full of immediates; various special cases are already
3639 // handled, so this is best done with a single constant-pool load.
3643 // Let legalizer expand 2-wide build_vectors.
3644 if (EVTBits == 64) {
3645 if (NumNonZero == 1) {
3646 // One half is zero or undef.
3647 unsigned Idx = CountTrailingZeros_32(NonZeros);
3648 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3649 Op.getOperand(Idx));
3650 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3651 Subtarget->hasSSE2(), DAG);
3656 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3657 if (EVTBits == 8 && NumElems == 16) {
3658 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3660 if (V.getNode()) return V;
3663 if (EVTBits == 16 && NumElems == 8) {
3664 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3666 if (V.getNode()) return V;
3669 // If element VT is == 32 bits, turn it into a number of shuffles.
3670 SmallVector<SDValue, 8> V;
3672 if (NumElems == 4 && NumZero > 0) {
3673 for (unsigned i = 0; i < 4; ++i) {
3674 bool isZero = !(NonZeros & (1 << i));
3676 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3678 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3681 for (unsigned i = 0; i < 2; ++i) {
3682 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3685 V[i] = V[i*2]; // Must be a zero vector.
3688 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3691 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3694 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3699 SmallVector<int, 8> MaskVec;
3700 bool Reverse = (NonZeros & 0x3) == 2;
3701 for (unsigned i = 0; i < 2; ++i)
3702 MaskVec.push_back(Reverse ? 1-i : i);
3703 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3704 for (unsigned i = 0; i < 2; ++i)
3705 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3706 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3709 if (Values.size() > 2) {
3710 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3711 // values to be inserted is equal to the number of elements, in which case
3712 // use the unpack code below in the hopes of matching the consecutive elts
3713 // load merge pattern for shuffles.
3714 // FIXME: We could probably just check that here directly.
3715 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3716 getSubtarget()->hasSSE41()) {
3717 V[0] = DAG.getUNDEF(VT);
3718 for (unsigned i = 0; i < NumElems; ++i)
3719 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3720 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3721 Op.getOperand(i), DAG.getIntPtrConstant(i));
3724 // Expand into a number of unpckl*.
3726 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3727 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3728 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3729 for (unsigned i = 0; i < NumElems; ++i)
3730 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3732 while (NumElems != 0) {
3733 for (unsigned i = 0; i < NumElems; ++i)
3734 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3744 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
3745 // We support concatenate two MMX registers and place them in a MMX
3746 // register. This is better than doing a stack convert.
3747 DebugLoc dl = Op.getDebugLoc();
3748 EVT ResVT = Op.getValueType();
3749 assert(Op.getNumOperands() == 2);
3750 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
3751 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
3753 SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
3754 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3755 InVec = Op.getOperand(1);
3756 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
3757 unsigned NumElts = ResVT.getVectorNumElements();
3758 VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3759 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
3760 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
3762 InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
3763 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3764 Mask[0] = 0; Mask[1] = 2;
3765 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
3767 return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3770 // v8i16 shuffles - Prefer shuffles in the following order:
3771 // 1. [all] pshuflw, pshufhw, optional move
3772 // 2. [ssse3] 1 x pshufb
3773 // 3. [ssse3] 2 x pshufb + 1 x por
3774 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3776 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3777 SelectionDAG &DAG, X86TargetLowering &TLI) {
3778 SDValue V1 = SVOp->getOperand(0);
3779 SDValue V2 = SVOp->getOperand(1);
3780 DebugLoc dl = SVOp->getDebugLoc();
3781 SmallVector<int, 8> MaskVals;
3783 // Determine if more than 1 of the words in each of the low and high quadwords
3784 // of the result come from the same quadword of one of the two inputs. Undef
3785 // mask values count as coming from any quadword, for better codegen.
3786 SmallVector<unsigned, 4> LoQuad(4);
3787 SmallVector<unsigned, 4> HiQuad(4);
3788 BitVector InputQuads(4);
3789 for (unsigned i = 0; i < 8; ++i) {
3790 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3791 int EltIdx = SVOp->getMaskElt(i);
3792 MaskVals.push_back(EltIdx);
3801 InputQuads.set(EltIdx / 4);
3804 int BestLoQuad = -1;
3805 unsigned MaxQuad = 1;
3806 for (unsigned i = 0; i < 4; ++i) {
3807 if (LoQuad[i] > MaxQuad) {
3809 MaxQuad = LoQuad[i];
3813 int BestHiQuad = -1;
3815 for (unsigned i = 0; i < 4; ++i) {
3816 if (HiQuad[i] > MaxQuad) {
3818 MaxQuad = HiQuad[i];
3822 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3823 // of the two input vectors, shuffle them into one input vector so only a
3824 // single pshufb instruction is necessary. If There are more than 2 input
3825 // quads, disable the next transformation since it does not help SSSE3.
3826 bool V1Used = InputQuads[0] || InputQuads[1];
3827 bool V2Used = InputQuads[2] || InputQuads[3];
3828 if (TLI.getSubtarget()->hasSSSE3()) {
3829 if (InputQuads.count() == 2 && V1Used && V2Used) {
3830 BestLoQuad = InputQuads.find_first();
3831 BestHiQuad = InputQuads.find_next(BestLoQuad);
3833 if (InputQuads.count() > 2) {
3839 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3840 // the shuffle mask. If a quad is scored as -1, that means that it contains
3841 // words from all 4 input quadwords.
3843 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3844 SmallVector<int, 8> MaskV;
3845 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3846 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3847 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3848 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3849 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3850 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3852 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3853 // source words for the shuffle, to aid later transformations.
3854 bool AllWordsInNewV = true;
3855 bool InOrder[2] = { true, true };
3856 for (unsigned i = 0; i != 8; ++i) {
3857 int idx = MaskVals[i];
3859 InOrder[i/4] = false;
3860 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3862 AllWordsInNewV = false;
3866 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3867 if (AllWordsInNewV) {
3868 for (int i = 0; i != 8; ++i) {
3869 int idx = MaskVals[i];
3872 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3873 if ((idx != i) && idx < 4)
3875 if ((idx != i) && idx > 3)
3884 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3885 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3886 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3887 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3888 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3892 // If we have SSSE3, and all words of the result are from 1 input vector,
3893 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3894 // is present, fall back to case 4.
3895 if (TLI.getSubtarget()->hasSSSE3()) {
3896 SmallVector<SDValue,16> pshufbMask;
3898 // If we have elements from both input vectors, set the high bit of the
3899 // shuffle mask element to zero out elements that come from V2 in the V1
3900 // mask, and elements that come from V1 in the V2 mask, so that the two
3901 // results can be OR'd together.
3902 bool TwoInputs = V1Used && V2Used;
3903 for (unsigned i = 0; i != 8; ++i) {
3904 int EltIdx = MaskVals[i] * 2;
3905 if (TwoInputs && (EltIdx >= 16)) {
3906 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3907 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3910 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3911 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3913 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3914 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3915 DAG.getNode(ISD::BUILD_VECTOR, dl,
3916 MVT::v16i8, &pshufbMask[0], 16));
3918 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3920 // Calculate the shuffle mask for the second input, shuffle it, and
3921 // OR it with the first shuffled input.
3923 for (unsigned i = 0; i != 8; ++i) {
3924 int EltIdx = MaskVals[i] * 2;
3926 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3927 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3930 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3931 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3933 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3934 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3935 DAG.getNode(ISD::BUILD_VECTOR, dl,
3936 MVT::v16i8, &pshufbMask[0], 16));
3937 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3938 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3941 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3942 // and update MaskVals with new element order.
3943 BitVector InOrder(8);
3944 if (BestLoQuad >= 0) {
3945 SmallVector<int, 8> MaskV;
3946 for (int i = 0; i != 4; ++i) {
3947 int idx = MaskVals[i];
3949 MaskV.push_back(-1);
3951 } else if ((idx / 4) == BestLoQuad) {
3952 MaskV.push_back(idx & 3);
3955 MaskV.push_back(-1);
3958 for (unsigned i = 4; i != 8; ++i)
3960 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3964 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3965 // and update MaskVals with the new element order.
3966 if (BestHiQuad >= 0) {
3967 SmallVector<int, 8> MaskV;
3968 for (unsigned i = 0; i != 4; ++i)
3970 for (unsigned i = 4; i != 8; ++i) {
3971 int idx = MaskVals[i];
3973 MaskV.push_back(-1);
3975 } else if ((idx / 4) == BestHiQuad) {
3976 MaskV.push_back((idx & 3) + 4);
3979 MaskV.push_back(-1);
3982 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3986 // In case BestHi & BestLo were both -1, which means each quadword has a word
3987 // from each of the four input quadwords, calculate the InOrder bitvector now
3988 // before falling through to the insert/extract cleanup.
3989 if (BestLoQuad == -1 && BestHiQuad == -1) {
3991 for (int i = 0; i != 8; ++i)
3992 if (MaskVals[i] < 0 || MaskVals[i] == i)
3996 // The other elements are put in the right place using pextrw and pinsrw.
3997 for (unsigned i = 0; i != 8; ++i) {
4000 int EltIdx = MaskVals[i];
4003 SDValue ExtOp = (EltIdx < 8)
4004 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4005 DAG.getIntPtrConstant(EltIdx))
4006 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4007 DAG.getIntPtrConstant(EltIdx - 8));
4008 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4009 DAG.getIntPtrConstant(i));
4014 // v16i8 shuffles - Prefer shuffles in the following order:
4015 // 1. [ssse3] 1 x pshufb
4016 // 2. [ssse3] 2 x pshufb + 1 x por
4017 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4019 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4020 SelectionDAG &DAG, X86TargetLowering &TLI) {
4021 SDValue V1 = SVOp->getOperand(0);
4022 SDValue V2 = SVOp->getOperand(1);
4023 DebugLoc dl = SVOp->getDebugLoc();
4024 SmallVector<int, 16> MaskVals;
4025 SVOp->getMask(MaskVals);
4027 // If we have SSSE3, case 1 is generated when all result bytes come from
4028 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4029 // present, fall back to case 3.
4030 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4033 for (unsigned i = 0; i < 16; ++i) {
4034 int EltIdx = MaskVals[i];
4043 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4044 if (TLI.getSubtarget()->hasSSSE3()) {
4045 SmallVector<SDValue,16> pshufbMask;
4047 // If all result elements are from one input vector, then only translate
4048 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4050 // Otherwise, we have elements from both input vectors, and must zero out
4051 // elements that come from V2 in the first mask, and V1 in the second mask
4052 // so that we can OR them together.
4053 bool TwoInputs = !(V1Only || V2Only);
4054 for (unsigned i = 0; i != 16; ++i) {
4055 int EltIdx = MaskVals[i];
4056 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4057 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4060 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4062 // If all the elements are from V2, assign it to V1 and return after
4063 // building the first pshufb.
4066 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4067 DAG.getNode(ISD::BUILD_VECTOR, dl,
4068 MVT::v16i8, &pshufbMask[0], 16));
4072 // Calculate the shuffle mask for the second input, shuffle it, and
4073 // OR it with the first shuffled input.
4075 for (unsigned i = 0; i != 16; ++i) {
4076 int EltIdx = MaskVals[i];
4078 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4081 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4083 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4084 DAG.getNode(ISD::BUILD_VECTOR, dl,
4085 MVT::v16i8, &pshufbMask[0], 16));
4086 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4089 // No SSSE3 - Calculate in place words and then fix all out of place words
4090 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4091 // the 16 different words that comprise the two doublequadword input vectors.
4092 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4093 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4094 SDValue NewV = V2Only ? V2 : V1;
4095 for (int i = 0; i != 8; ++i) {
4096 int Elt0 = MaskVals[i*2];
4097 int Elt1 = MaskVals[i*2+1];
4099 // This word of the result is all undef, skip it.
4100 if (Elt0 < 0 && Elt1 < 0)
4103 // This word of the result is already in the correct place, skip it.
4104 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4106 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4109 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4110 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4113 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4114 // using a single extract together, load it and store it.
4115 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4116 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4117 DAG.getIntPtrConstant(Elt1 / 2));
4118 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4119 DAG.getIntPtrConstant(i));
4123 // If Elt1 is defined, extract it from the appropriate source. If the
4124 // source byte is not also odd, shift the extracted word left 8 bits
4125 // otherwise clear the bottom 8 bits if we need to do an or.
4127 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4128 DAG.getIntPtrConstant(Elt1 / 2));
4129 if ((Elt1 & 1) == 0)
4130 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4131 DAG.getConstant(8, TLI.getShiftAmountTy()));
4133 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4134 DAG.getConstant(0xFF00, MVT::i16));
4136 // If Elt0 is defined, extract it from the appropriate source. If the
4137 // source byte is not also even, shift the extracted word right 8 bits. If
4138 // Elt1 was also defined, OR the extracted values together before
4139 // inserting them in the result.
4141 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4142 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4143 if ((Elt0 & 1) != 0)
4144 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4145 DAG.getConstant(8, TLI.getShiftAmountTy()));
4147 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4148 DAG.getConstant(0x00FF, MVT::i16));
4149 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4152 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4153 DAG.getIntPtrConstant(i));
4155 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4158 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4159 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4160 /// done when every pair / quad of shuffle mask elements point to elements in
4161 /// the right sequence. e.g.
4162 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4164 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4166 TargetLowering &TLI, DebugLoc dl) {
4167 EVT VT = SVOp->getValueType(0);
4168 SDValue V1 = SVOp->getOperand(0);
4169 SDValue V2 = SVOp->getOperand(1);
4170 unsigned NumElems = VT.getVectorNumElements();
4171 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4172 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4173 EVT MaskEltVT = MaskVT.getVectorElementType();
4175 switch (VT.getSimpleVT().SimpleTy) {
4176 default: assert(false && "Unexpected!");
4177 case MVT::v4f32: NewVT = MVT::v2f64; break;
4178 case MVT::v4i32: NewVT = MVT::v2i64; break;
4179 case MVT::v8i16: NewVT = MVT::v4i32; break;
4180 case MVT::v16i8: NewVT = MVT::v4i32; break;
4183 if (NewWidth == 2) {
4189 int Scale = NumElems / NewWidth;
4190 SmallVector<int, 8> MaskVec;
4191 for (unsigned i = 0; i < NumElems; i += Scale) {
4193 for (int j = 0; j < Scale; ++j) {
4194 int EltIdx = SVOp->getMaskElt(i+j);
4198 StartIdx = EltIdx - (EltIdx % Scale);
4199 if (EltIdx != StartIdx + j)
4203 MaskVec.push_back(-1);
4205 MaskVec.push_back(StartIdx / Scale);
4208 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4209 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4210 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4213 /// getVZextMovL - Return a zero-extending vector move low node.
4215 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4216 SDValue SrcOp, SelectionDAG &DAG,
4217 const X86Subtarget *Subtarget, DebugLoc dl) {
4218 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4219 LoadSDNode *LD = NULL;
4220 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4221 LD = dyn_cast<LoadSDNode>(SrcOp);
4223 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4225 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4226 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4227 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4228 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4229 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4231 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4232 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4233 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4234 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4242 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4243 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4244 DAG.getNode(ISD::BIT_CONVERT, dl,
4248 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4251 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4252 SDValue V1 = SVOp->getOperand(0);
4253 SDValue V2 = SVOp->getOperand(1);
4254 DebugLoc dl = SVOp->getDebugLoc();
4255 EVT VT = SVOp->getValueType(0);
4257 SmallVector<std::pair<int, int>, 8> Locs;
4259 SmallVector<int, 8> Mask1(4U, -1);
4260 SmallVector<int, 8> PermMask;
4261 SVOp->getMask(PermMask);
4265 for (unsigned i = 0; i != 4; ++i) {
4266 int Idx = PermMask[i];
4268 Locs[i] = std::make_pair(-1, -1);
4270 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4272 Locs[i] = std::make_pair(0, NumLo);
4276 Locs[i] = std::make_pair(1, NumHi);
4278 Mask1[2+NumHi] = Idx;
4284 if (NumLo <= 2 && NumHi <= 2) {
4285 // If no more than two elements come from either vector. This can be
4286 // implemented with two shuffles. First shuffle gather the elements.
4287 // The second shuffle, which takes the first shuffle as both of its
4288 // vector operands, put the elements into the right order.
4289 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4291 SmallVector<int, 8> Mask2(4U, -1);
4293 for (unsigned i = 0; i != 4; ++i) {
4294 if (Locs[i].first == -1)
4297 unsigned Idx = (i < 2) ? 0 : 4;
4298 Idx += Locs[i].first * 2 + Locs[i].second;
4303 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4304 } else if (NumLo == 3 || NumHi == 3) {
4305 // Otherwise, we must have three elements from one vector, call it X, and
4306 // one element from the other, call it Y. First, use a shufps to build an
4307 // intermediate vector with the one element from Y and the element from X
4308 // that will be in the same half in the final destination (the indexes don't
4309 // matter). Then, use a shufps to build the final vector, taking the half
4310 // containing the element from Y from the intermediate, and the other half
4313 // Normalize it so the 3 elements come from V1.
4314 CommuteVectorShuffleMask(PermMask, VT);
4318 // Find the element from V2.
4320 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4321 int Val = PermMask[HiIndex];
4328 Mask1[0] = PermMask[HiIndex];
4330 Mask1[2] = PermMask[HiIndex^1];
4332 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4335 Mask1[0] = PermMask[0];
4336 Mask1[1] = PermMask[1];
4337 Mask1[2] = HiIndex & 1 ? 6 : 4;
4338 Mask1[3] = HiIndex & 1 ? 4 : 6;
4339 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4341 Mask1[0] = HiIndex & 1 ? 2 : 0;
4342 Mask1[1] = HiIndex & 1 ? 0 : 2;
4343 Mask1[2] = PermMask[2];
4344 Mask1[3] = PermMask[3];
4349 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4353 // Break it into (shuffle shuffle_hi, shuffle_lo).
4355 SmallVector<int,8> LoMask(4U, -1);
4356 SmallVector<int,8> HiMask(4U, -1);
4358 SmallVector<int,8> *MaskPtr = &LoMask;
4359 unsigned MaskIdx = 0;
4362 for (unsigned i = 0; i != 4; ++i) {
4369 int Idx = PermMask[i];
4371 Locs[i] = std::make_pair(-1, -1);
4372 } else if (Idx < 4) {
4373 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4374 (*MaskPtr)[LoIdx] = Idx;
4377 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4378 (*MaskPtr)[HiIdx] = Idx;
4383 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4384 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4385 SmallVector<int, 8> MaskOps;
4386 for (unsigned i = 0; i != 4; ++i) {
4387 if (Locs[i].first == -1) {
4388 MaskOps.push_back(-1);
4390 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4391 MaskOps.push_back(Idx);
4394 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4398 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4399 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4400 SDValue V1 = Op.getOperand(0);
4401 SDValue V2 = Op.getOperand(1);
4402 EVT VT = Op.getValueType();
4403 DebugLoc dl = Op.getDebugLoc();
4404 unsigned NumElems = VT.getVectorNumElements();
4405 bool isMMX = VT.getSizeInBits() == 64;
4406 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4407 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4408 bool V1IsSplat = false;
4409 bool V2IsSplat = false;
4411 if (isZeroShuffle(SVOp))
4412 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4414 // Promote splats to v4f32.
4415 if (SVOp->isSplat()) {
4416 if (isMMX || NumElems < 4)
4418 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4421 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4423 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4424 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4425 if (NewOp.getNode())
4426 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4427 LowerVECTOR_SHUFFLE(NewOp, DAG));
4428 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4429 // FIXME: Figure out a cleaner way to do this.
4430 // Try to make use of movq to zero out the top part.
4431 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4432 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4433 if (NewOp.getNode()) {
4434 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4435 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4436 DAG, Subtarget, dl);
4438 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4439 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4440 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4441 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4442 DAG, Subtarget, dl);
4446 if (X86::isPSHUFDMask(SVOp))
4449 // Check if this can be converted into a logical shift.
4450 bool isLeft = false;
4453 bool isShift = getSubtarget()->hasSSE2() &&
4454 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4455 if (isShift && ShVal.hasOneUse()) {
4456 // If the shifted value has multiple uses, it may be cheaper to use
4457 // v_set0 + movlhps or movhlps, etc.
4458 EVT EltVT = VT.getVectorElementType();
4459 ShAmt *= EltVT.getSizeInBits();
4460 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4463 if (X86::isMOVLMask(SVOp)) {
4466 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4467 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4472 // FIXME: fold these into legal mask.
4473 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4474 X86::isMOVSLDUPMask(SVOp) ||
4475 X86::isMOVHLPSMask(SVOp) ||
4476 X86::isMOVLHPSMask(SVOp) ||
4477 X86::isMOVLPMask(SVOp)))
4480 if (ShouldXformToMOVHLPS(SVOp) ||
4481 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4482 return CommuteVectorShuffle(SVOp, DAG);
4485 // No better options. Use a vshl / vsrl.
4486 EVT EltVT = VT.getVectorElementType();
4487 ShAmt *= EltVT.getSizeInBits();
4488 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4491 bool Commuted = false;
4492 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4493 // 1,1,1,1 -> v8i16 though.
4494 V1IsSplat = isSplatVector(V1.getNode());
4495 V2IsSplat = isSplatVector(V2.getNode());
4497 // Canonicalize the splat or undef, if present, to be on the RHS.
4498 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4499 Op = CommuteVectorShuffle(SVOp, DAG);
4500 SVOp = cast<ShuffleVectorSDNode>(Op);
4501 V1 = SVOp->getOperand(0);
4502 V2 = SVOp->getOperand(1);
4503 std::swap(V1IsSplat, V2IsSplat);
4504 std::swap(V1IsUndef, V2IsUndef);
4508 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4509 // Shuffling low element of v1 into undef, just return v1.
4512 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4513 // the instruction selector will not match, so get a canonical MOVL with
4514 // swapped operands to undo the commute.
4515 return getMOVL(DAG, dl, VT, V2, V1);
4518 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4519 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4520 X86::isUNPCKLMask(SVOp) ||
4521 X86::isUNPCKHMask(SVOp))
4525 // Normalize mask so all entries that point to V2 points to its first
4526 // element then try to match unpck{h|l} again. If match, return a
4527 // new vector_shuffle with the corrected mask.
4528 SDValue NewMask = NormalizeMask(SVOp, DAG);
4529 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4530 if (NSVOp != SVOp) {
4531 if (X86::isUNPCKLMask(NSVOp, true)) {
4533 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4540 // Commute is back and try unpck* again.
4541 // FIXME: this seems wrong.
4542 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4543 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4544 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4545 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4546 X86::isUNPCKLMask(NewSVOp) ||
4547 X86::isUNPCKHMask(NewSVOp))
4551 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4553 // Normalize the node to match x86 shuffle ops if needed
4554 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4555 return CommuteVectorShuffle(SVOp, DAG);
4557 // Check for legal shuffle and return?
4558 SmallVector<int, 16> PermMask;
4559 SVOp->getMask(PermMask);
4560 if (isShuffleMaskLegal(PermMask, VT))
4563 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4564 if (VT == MVT::v8i16) {
4565 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4566 if (NewOp.getNode())
4570 if (VT == MVT::v16i8) {
4571 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4572 if (NewOp.getNode())
4576 // Handle all 4 wide cases with a number of shuffles except for MMX.
4577 if (NumElems == 4 && !isMMX)
4578 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4584 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4585 SelectionDAG &DAG) {
4586 EVT VT = Op.getValueType();
4587 DebugLoc dl = Op.getDebugLoc();
4588 if (VT.getSizeInBits() == 8) {
4589 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4590 Op.getOperand(0), Op.getOperand(1));
4591 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4592 DAG.getValueType(VT));
4593 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4594 } else if (VT.getSizeInBits() == 16) {
4595 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4596 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4598 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4599 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4600 DAG.getNode(ISD::BIT_CONVERT, dl,
4604 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4605 Op.getOperand(0), Op.getOperand(1));
4606 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4607 DAG.getValueType(VT));
4608 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4609 } else if (VT == MVT::f32) {
4610 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4611 // the result back to FR32 register. It's only worth matching if the
4612 // result has a single use which is a store or a bitcast to i32. And in
4613 // the case of a store, it's not worth it if the index is a constant 0,
4614 // because a MOVSSmr can be used instead, which is smaller and faster.
4615 if (!Op.hasOneUse())
4617 SDNode *User = *Op.getNode()->use_begin();
4618 if ((User->getOpcode() != ISD::STORE ||
4619 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4620 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4621 (User->getOpcode() != ISD::BIT_CONVERT ||
4622 User->getValueType(0) != MVT::i32))
4624 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4625 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4628 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4629 } else if (VT == MVT::i32) {
4630 // ExtractPS works with constant index.
4631 if (isa<ConstantSDNode>(Op.getOperand(1)))
4639 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4640 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4643 if (Subtarget->hasSSE41()) {
4644 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4649 EVT VT = Op.getValueType();
4650 DebugLoc dl = Op.getDebugLoc();
4651 // TODO: handle v16i8.
4652 if (VT.getSizeInBits() == 16) {
4653 SDValue Vec = Op.getOperand(0);
4654 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4656 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4657 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4658 DAG.getNode(ISD::BIT_CONVERT, dl,
4661 // Transform it so it match pextrw which produces a 32-bit result.
4662 EVT EltVT = MVT::i32;
4663 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4664 Op.getOperand(0), Op.getOperand(1));
4665 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4666 DAG.getValueType(VT));
4667 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4668 } else if (VT.getSizeInBits() == 32) {
4669 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4673 // SHUFPS the element to the lowest double word, then movss.
4674 int Mask[4] = { Idx, -1, -1, -1 };
4675 EVT VVT = Op.getOperand(0).getValueType();
4676 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4677 DAG.getUNDEF(VVT), Mask);
4678 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4679 DAG.getIntPtrConstant(0));
4680 } else if (VT.getSizeInBits() == 64) {
4681 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4682 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4683 // to match extract_elt for f64.
4684 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4688 // UNPCKHPD the element to the lowest double word, then movsd.
4689 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4690 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4691 int Mask[2] = { 1, -1 };
4692 EVT VVT = Op.getOperand(0).getValueType();
4693 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4694 DAG.getUNDEF(VVT), Mask);
4695 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4696 DAG.getIntPtrConstant(0));
4703 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4704 EVT VT = Op.getValueType();
4705 EVT EltVT = VT.getVectorElementType();
4706 DebugLoc dl = Op.getDebugLoc();
4708 SDValue N0 = Op.getOperand(0);
4709 SDValue N1 = Op.getOperand(1);
4710 SDValue N2 = Op.getOperand(2);
4712 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4713 isa<ConstantSDNode>(N2)) {
4714 unsigned Opc = (EltVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4716 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4718 if (N1.getValueType() != MVT::i32)
4719 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4720 if (N2.getValueType() != MVT::i32)
4721 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4722 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4723 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4724 // Bits [7:6] of the constant are the source select. This will always be
4725 // zero here. The DAG Combiner may combine an extract_elt index into these
4726 // bits. For example (insert (extract, 3), 2) could be matched by putting
4727 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4728 // Bits [5:4] of the constant are the destination select. This is the
4729 // value of the incoming immediate.
4730 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4731 // combine either bitwise AND or insert of float 0.0 to set these bits.
4732 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4733 // Create this as a scalar to vector..
4734 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4735 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4736 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4737 // PINSR* works with constant index.
4744 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4745 EVT VT = Op.getValueType();
4746 EVT EltVT = VT.getVectorElementType();
4748 if (Subtarget->hasSSE41())
4749 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4751 if (EltVT == MVT::i8)
4754 DebugLoc dl = Op.getDebugLoc();
4755 SDValue N0 = Op.getOperand(0);
4756 SDValue N1 = Op.getOperand(1);
4757 SDValue N2 = Op.getOperand(2);
4759 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4760 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4761 // as its second argument.
4762 if (N1.getValueType() != MVT::i32)
4763 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4764 if (N2.getValueType() != MVT::i32)
4765 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4766 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4772 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4773 DebugLoc dl = Op.getDebugLoc();
4774 if (Op.getValueType() == MVT::v2f32)
4775 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4776 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4777 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4778 Op.getOperand(0))));
4780 if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4781 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4783 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4784 EVT VT = MVT::v2i32;
4785 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4792 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4793 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4796 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4797 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4798 // one of the above mentioned nodes. It has to be wrapped because otherwise
4799 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4800 // be used to form addressing mode. These wrapped nodes will be selected
4803 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4804 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4806 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4808 unsigned char OpFlag = 0;
4809 unsigned WrapperKind = X86ISD::Wrapper;
4810 CodeModel::Model M = getTargetMachine().getCodeModel();
4812 if (Subtarget->isPICStyleRIPRel() &&
4813 (M == CodeModel::Small || M == CodeModel::Kernel))
4814 WrapperKind = X86ISD::WrapperRIP;
4815 else if (Subtarget->isPICStyleGOT())
4816 OpFlag = X86II::MO_GOTOFF;
4817 else if (Subtarget->isPICStyleStubPIC())
4818 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4820 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4822 CP->getOffset(), OpFlag);
4823 DebugLoc DL = CP->getDebugLoc();
4824 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4825 // With PIC, the address is actually $g + Offset.
4827 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4828 DAG.getNode(X86ISD::GlobalBaseReg,
4829 DebugLoc::getUnknownLoc(), getPointerTy()),
4836 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4837 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4839 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4841 unsigned char OpFlag = 0;
4842 unsigned WrapperKind = X86ISD::Wrapper;
4843 CodeModel::Model M = getTargetMachine().getCodeModel();
4845 if (Subtarget->isPICStyleRIPRel() &&
4846 (M == CodeModel::Small || M == CodeModel::Kernel))
4847 WrapperKind = X86ISD::WrapperRIP;
4848 else if (Subtarget->isPICStyleGOT())
4849 OpFlag = X86II::MO_GOTOFF;
4850 else if (Subtarget->isPICStyleStubPIC())
4851 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4853 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4855 DebugLoc DL = JT->getDebugLoc();
4856 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4858 // With PIC, the address is actually $g + Offset.
4860 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4861 DAG.getNode(X86ISD::GlobalBaseReg,
4862 DebugLoc::getUnknownLoc(), getPointerTy()),
4870 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4871 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4873 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4875 unsigned char OpFlag = 0;
4876 unsigned WrapperKind = X86ISD::Wrapper;
4877 CodeModel::Model M = getTargetMachine().getCodeModel();
4879 if (Subtarget->isPICStyleRIPRel() &&
4880 (M == CodeModel::Small || M == CodeModel::Kernel))
4881 WrapperKind = X86ISD::WrapperRIP;
4882 else if (Subtarget->isPICStyleGOT())
4883 OpFlag = X86II::MO_GOTOFF;
4884 else if (Subtarget->isPICStyleStubPIC())
4885 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4887 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
4889 DebugLoc DL = Op.getDebugLoc();
4890 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4893 // With PIC, the address is actually $g + Offset.
4894 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4895 !Subtarget->is64Bit()) {
4896 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4897 DAG.getNode(X86ISD::GlobalBaseReg,
4898 DebugLoc::getUnknownLoc(),
4907 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
4908 // Create the TargetBlockAddressAddress node.
4909 unsigned char OpFlags =
4910 Subtarget->ClassifyBlockAddressReference();
4911 CodeModel::Model M = getTargetMachine().getCodeModel();
4912 BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4913 DebugLoc dl = Op.getDebugLoc();
4914 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
4915 /*isTarget=*/true, OpFlags);
4917 if (Subtarget->isPICStyleRIPRel() &&
4918 (M == CodeModel::Small || M == CodeModel::Kernel))
4919 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4921 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4923 // With PIC, the address is actually $g + Offset.
4924 if (isGlobalRelativeToPICBase(OpFlags)) {
4925 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4926 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4934 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4936 SelectionDAG &DAG) const {
4937 // Create the TargetGlobalAddress node, folding in the constant
4938 // offset if it is legal.
4939 unsigned char OpFlags =
4940 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4941 CodeModel::Model M = getTargetMachine().getCodeModel();
4943 if (OpFlags == X86II::MO_NO_FLAG &&
4944 X86::isOffsetSuitableForCodeModel(Offset, M)) {
4945 // A direct static reference to a global.
4946 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4949 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
4952 if (Subtarget->isPICStyleRIPRel() &&
4953 (M == CodeModel::Small || M == CodeModel::Kernel))
4954 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4956 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4958 // With PIC, the address is actually $g + Offset.
4959 if (isGlobalRelativeToPICBase(OpFlags)) {
4960 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4961 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4965 // For globals that require a load from a stub to get the address, emit the
4967 if (isGlobalStubReference(OpFlags))
4968 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4969 PseudoSourceValue::getGOT(), 0);
4971 // If there was a non-zero offset that we didn't fold, create an explicit
4974 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4975 DAG.getConstant(Offset, getPointerTy()));
4981 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4982 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4983 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4984 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4988 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4989 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
4990 unsigned char OperandFlags) {
4991 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4992 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4993 DebugLoc dl = GA->getDebugLoc();
4994 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4995 GA->getValueType(0),
4999 SDValue Ops[] = { Chain, TGA, *InFlag };
5000 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5002 SDValue Ops[] = { Chain, TGA };
5003 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5006 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5007 MFI->setHasCalls(true);
5009 SDValue Flag = Chain.getValue(1);
5010 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5013 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5015 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5018 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
5019 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5020 DAG.getNode(X86ISD::GlobalBaseReg,
5021 DebugLoc::getUnknownLoc(),
5023 InFlag = Chain.getValue(1);
5025 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5028 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5030 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5032 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5033 X86::RAX, X86II::MO_TLSGD);
5036 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5037 // "local exec" model.
5038 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5039 const EVT PtrVT, TLSModel::Model model,
5041 DebugLoc dl = GA->getDebugLoc();
5042 // Get the Thread Pointer
5043 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5044 DebugLoc::getUnknownLoc(), PtrVT,
5045 DAG.getRegister(is64Bit? X86::FS : X86::GS,
5048 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5051 unsigned char OperandFlags = 0;
5052 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
5054 unsigned WrapperKind = X86ISD::Wrapper;
5055 if (model == TLSModel::LocalExec) {
5056 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5057 } else if (is64Bit) {
5058 assert(model == TLSModel::InitialExec);
5059 OperandFlags = X86II::MO_GOTTPOFF;
5060 WrapperKind = X86ISD::WrapperRIP;
5062 assert(model == TLSModel::InitialExec);
5063 OperandFlags = X86II::MO_INDNTPOFF;
5066 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5068 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5069 GA->getOffset(), OperandFlags);
5070 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5072 if (model == TLSModel::InitialExec)
5073 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5074 PseudoSourceValue::getGOT(), 0);
5076 // The address of the thread local variable is the add of the thread
5077 // pointer with the offset of the variable.
5078 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5082 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
5083 // TODO: implement the "local dynamic" model
5084 // TODO: implement the "initial exec"model for pic executables
5085 assert(Subtarget->isTargetELF() &&
5086 "TLS not implemented for non-ELF targets");
5087 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5088 const GlobalValue *GV = GA->getGlobal();
5090 // If GV is an alias then use the aliasee for determining
5091 // thread-localness.
5092 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5093 GV = GA->resolveAliasedGlobal(false);
5095 TLSModel::Model model = getTLSModel(GV,
5096 getTargetMachine().getRelocationModel());
5099 case TLSModel::GeneralDynamic:
5100 case TLSModel::LocalDynamic: // not implemented
5101 if (Subtarget->is64Bit())
5102 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5103 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5105 case TLSModel::InitialExec:
5106 case TLSModel::LocalExec:
5107 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5108 Subtarget->is64Bit());
5111 llvm_unreachable("Unreachable");
5116 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5117 /// take a 2 x i32 value to shift plus a shift amount.
5118 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
5119 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5120 EVT VT = Op.getValueType();
5121 unsigned VTBits = VT.getSizeInBits();
5122 DebugLoc dl = Op.getDebugLoc();
5123 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5124 SDValue ShOpLo = Op.getOperand(0);
5125 SDValue ShOpHi = Op.getOperand(1);
5126 SDValue ShAmt = Op.getOperand(2);
5127 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5128 DAG.getConstant(VTBits - 1, MVT::i8))
5129 : DAG.getConstant(0, VT);
5132 if (Op.getOpcode() == ISD::SHL_PARTS) {
5133 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5134 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5136 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5137 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5140 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5141 DAG.getConstant(VTBits, MVT::i8));
5142 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
5143 AndNode, DAG.getConstant(0, MVT::i8));
5146 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5147 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5148 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5150 if (Op.getOpcode() == ISD::SHL_PARTS) {
5151 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5152 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5154 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5155 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5158 SDValue Ops[2] = { Lo, Hi };
5159 return DAG.getMergeValues(Ops, 2, dl);
5162 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5163 EVT SrcVT = Op.getOperand(0).getValueType();
5165 if (SrcVT.isVector()) {
5166 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5172 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5173 "Unknown SINT_TO_FP to lower!");
5175 // These are really Legal; return the operand so the caller accepts it as
5177 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5179 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5180 Subtarget->is64Bit()) {
5184 DebugLoc dl = Op.getDebugLoc();
5185 unsigned Size = SrcVT.getSizeInBits()/8;
5186 MachineFunction &MF = DAG.getMachineFunction();
5187 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5188 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5189 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5191 PseudoSourceValue::getFixedStack(SSFI), 0);
5192 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5195 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5197 SelectionDAG &DAG) {
5199 DebugLoc dl = Op.getDebugLoc();
5201 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5203 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5205 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5206 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5207 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5208 Tys, Ops, array_lengthof(Ops));
5211 Chain = Result.getValue(1);
5212 SDValue InFlag = Result.getValue(2);
5214 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5215 // shouldn't be necessary except that RFP cannot be live across
5216 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5217 MachineFunction &MF = DAG.getMachineFunction();
5218 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5219 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5220 Tys = DAG.getVTList(MVT::Other);
5222 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5224 Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5225 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5226 PseudoSourceValue::getFixedStack(SSFI), 0);
5232 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5233 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5234 // This algorithm is not obvious. Here it is in C code, more or less:
5236 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5237 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5238 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5240 // Copy ints to xmm registers.
5241 __m128i xh = _mm_cvtsi32_si128( hi );
5242 __m128i xl = _mm_cvtsi32_si128( lo );
5244 // Combine into low half of a single xmm register.
5245 __m128i x = _mm_unpacklo_epi32( xh, xl );
5249 // Merge in appropriate exponents to give the integer bits the right
5251 x = _mm_unpacklo_epi32( x, exp );
5253 // Subtract away the biases to deal with the IEEE-754 double precision
5255 d = _mm_sub_pd( (__m128d) x, bias );
5257 // All conversions up to here are exact. The correctly rounded result is
5258 // calculated using the current rounding mode using the following
5260 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5261 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5262 // store doesn't really need to be here (except
5263 // maybe to zero the other double)
5268 DebugLoc dl = Op.getDebugLoc();
5269 LLVMContext *Context = DAG.getContext();
5271 // Build some magic constants.
5272 std::vector<Constant*> CV0;
5273 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5274 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5275 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5276 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5277 Constant *C0 = ConstantVector::get(CV0);
5278 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5280 std::vector<Constant*> CV1;
5282 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5284 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5285 Constant *C1 = ConstantVector::get(CV1);
5286 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5288 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5289 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5291 DAG.getIntPtrConstant(1)));
5292 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5293 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5295 DAG.getIntPtrConstant(0)));
5296 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5297 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5298 PseudoSourceValue::getConstantPool(), 0,
5300 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5301 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5302 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5303 PseudoSourceValue::getConstantPool(), 0,
5305 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5307 // Add the halves; easiest way is to swap them into another reg first.
5308 int ShufMask[2] = { 1, -1 };
5309 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5310 DAG.getUNDEF(MVT::v2f64), ShufMask);
5311 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5312 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5313 DAG.getIntPtrConstant(0));
5316 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5317 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5318 DebugLoc dl = Op.getDebugLoc();
5319 // FP constant to bias correct the final result.
5320 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5323 // Load the 32-bit value into an XMM register.
5324 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5325 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5327 DAG.getIntPtrConstant(0)));
5329 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5330 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5331 DAG.getIntPtrConstant(0));
5333 // Or the load with the bias.
5334 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5335 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5336 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5338 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5339 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5340 MVT::v2f64, Bias)));
5341 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5342 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5343 DAG.getIntPtrConstant(0));
5345 // Subtract the bias.
5346 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5348 // Handle final rounding.
5349 EVT DestVT = Op.getValueType();
5351 if (DestVT.bitsLT(MVT::f64)) {
5352 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5353 DAG.getIntPtrConstant(0));
5354 } else if (DestVT.bitsGT(MVT::f64)) {
5355 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5358 // Handle final rounding.
5362 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5363 SDValue N0 = Op.getOperand(0);
5364 DebugLoc dl = Op.getDebugLoc();
5366 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5367 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5368 // the optimization here.
5369 if (DAG.SignBitIsZero(N0))
5370 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5372 EVT SrcVT = N0.getValueType();
5373 if (SrcVT == MVT::i64) {
5374 // We only handle SSE2 f64 target here; caller can expand the rest.
5375 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5378 return LowerUINT_TO_FP_i64(Op, DAG);
5379 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5380 return LowerUINT_TO_FP_i32(Op, DAG);
5383 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5385 // Make a 64-bit buffer, and use it to build an FILD.
5386 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5387 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5388 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5389 getPointerTy(), StackSlot, WordOff);
5390 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5391 StackSlot, NULL, 0);
5392 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5393 OffsetSlot, NULL, 0);
5394 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5397 std::pair<SDValue,SDValue> X86TargetLowering::
5398 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5399 DebugLoc dl = Op.getDebugLoc();
5401 EVT DstTy = Op.getValueType();
5404 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5408 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5409 DstTy.getSimpleVT() >= MVT::i16 &&
5410 "Unknown FP_TO_SINT to lower!");
5412 // These are really Legal.
5413 if (DstTy == MVT::i32 &&
5414 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5415 return std::make_pair(SDValue(), SDValue());
5416 if (Subtarget->is64Bit() &&
5417 DstTy == MVT::i64 &&
5418 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5419 return std::make_pair(SDValue(), SDValue());
5421 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5423 MachineFunction &MF = DAG.getMachineFunction();
5424 unsigned MemSize = DstTy.getSizeInBits()/8;
5425 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5426 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5429 switch (DstTy.getSimpleVT().SimpleTy) {
5430 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5431 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5432 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5433 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5436 SDValue Chain = DAG.getEntryNode();
5437 SDValue Value = Op.getOperand(0);
5438 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5439 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5440 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5441 PseudoSourceValue::getFixedStack(SSFI), 0);
5442 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5444 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5446 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5447 Chain = Value.getValue(1);
5448 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5449 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5452 // Build the FP_TO_INT*_IN_MEM
5453 SDValue Ops[] = { Chain, Value, StackSlot };
5454 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5456 return std::make_pair(FIST, StackSlot);
5459 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5460 if (Op.getValueType().isVector()) {
5461 if (Op.getValueType() == MVT::v2i32 &&
5462 Op.getOperand(0).getValueType() == MVT::v2f64) {
5468 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5469 SDValue FIST = Vals.first, StackSlot = Vals.second;
5470 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5471 if (FIST.getNode() == 0) return Op;
5474 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5475 FIST, StackSlot, NULL, 0);
5478 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5479 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5480 SDValue FIST = Vals.first, StackSlot = Vals.second;
5481 assert(FIST.getNode() && "Unexpected failure");
5484 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5485 FIST, StackSlot, NULL, 0);
5488 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5489 LLVMContext *Context = DAG.getContext();
5490 DebugLoc dl = Op.getDebugLoc();
5491 EVT VT = Op.getValueType();
5494 EltVT = VT.getVectorElementType();
5495 std::vector<Constant*> CV;
5496 if (EltVT == MVT::f64) {
5497 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5501 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5507 Constant *C = ConstantVector::get(CV);
5508 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5509 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5510 PseudoSourceValue::getConstantPool(), 0,
5512 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5515 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5516 LLVMContext *Context = DAG.getContext();
5517 DebugLoc dl = Op.getDebugLoc();
5518 EVT VT = Op.getValueType();
5521 EltVT = VT.getVectorElementType();
5522 std::vector<Constant*> CV;
5523 if (EltVT == MVT::f64) {
5524 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5528 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5534 Constant *C = ConstantVector::get(CV);
5535 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5536 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5537 PseudoSourceValue::getConstantPool(), 0,
5539 if (VT.isVector()) {
5540 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5541 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5542 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5544 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5546 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5550 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5551 LLVMContext *Context = DAG.getContext();
5552 SDValue Op0 = Op.getOperand(0);
5553 SDValue Op1 = Op.getOperand(1);
5554 DebugLoc dl = Op.getDebugLoc();
5555 EVT VT = Op.getValueType();
5556 EVT SrcVT = Op1.getValueType();
5558 // If second operand is smaller, extend it first.
5559 if (SrcVT.bitsLT(VT)) {
5560 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5563 // And if it is bigger, shrink it first.
5564 if (SrcVT.bitsGT(VT)) {
5565 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5569 // At this point the operands and the result should have the same
5570 // type, and that won't be f80 since that is not custom lowered.
5572 // First get the sign bit of second operand.
5573 std::vector<Constant*> CV;
5574 if (SrcVT == MVT::f64) {
5575 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5576 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5578 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5579 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5580 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5581 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5583 Constant *C = ConstantVector::get(CV);
5584 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5585 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5586 PseudoSourceValue::getConstantPool(), 0,
5588 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5590 // Shift sign bit right or left if the two operands have different types.
5591 if (SrcVT.bitsGT(VT)) {
5592 // Op0 is MVT::f32, Op1 is MVT::f64.
5593 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5594 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5595 DAG.getConstant(32, MVT::i32));
5596 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5597 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5598 DAG.getIntPtrConstant(0));
5601 // Clear first operand sign bit.
5603 if (VT == MVT::f64) {
5604 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5605 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5607 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5608 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5609 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5610 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5612 C = ConstantVector::get(CV);
5613 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5614 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5615 PseudoSourceValue::getConstantPool(), 0,
5617 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5619 // Or the value with the sign bit.
5620 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5623 /// Emit nodes that will be selected as "test Op0,Op0", or something
5625 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5626 SelectionDAG &DAG) {
5627 DebugLoc dl = Op.getDebugLoc();
5629 // CF and OF aren't always set the way we want. Determine which
5630 // of these we need.
5631 bool NeedCF = false;
5632 bool NeedOF = false;
5634 case X86::COND_A: case X86::COND_AE:
5635 case X86::COND_B: case X86::COND_BE:
5638 case X86::COND_G: case X86::COND_GE:
5639 case X86::COND_L: case X86::COND_LE:
5640 case X86::COND_O: case X86::COND_NO:
5646 // See if we can use the EFLAGS value from the operand instead of
5647 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5648 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5649 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5650 unsigned Opcode = 0;
5651 unsigned NumOperands = 0;
5652 switch (Op.getNode()->getOpcode()) {
5654 // Due to an isel shortcoming, be conservative if this add is likely to
5655 // be selected as part of a load-modify-store instruction. When the root
5656 // node in a match is a store, isel doesn't know how to remap non-chain
5657 // non-flag uses of other nodes in the match, such as the ADD in this
5658 // case. This leads to the ADD being left around and reselected, with
5659 // the result being two adds in the output.
5660 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5661 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5662 if (UI->getOpcode() == ISD::STORE)
5664 if (ConstantSDNode *C =
5665 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5666 // An add of one will be selected as an INC.
5667 if (C->getAPIntValue() == 1) {
5668 Opcode = X86ISD::INC;
5672 // An add of negative one (subtract of one) will be selected as a DEC.
5673 if (C->getAPIntValue().isAllOnesValue()) {
5674 Opcode = X86ISD::DEC;
5679 // Otherwise use a regular EFLAGS-setting add.
5680 Opcode = X86ISD::ADD;
5684 // If the primary and result isn't used, don't bother using X86ISD::AND,
5685 // because a TEST instruction will be better.
5686 bool NonFlagUse = false;
5687 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5688 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5690 unsigned UOpNo = UI.getOperandNo();
5691 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5692 // Look pass truncate.
5693 UOpNo = User->use_begin().getOperandNo();
5694 User = *User->use_begin();
5696 if (User->getOpcode() != ISD::BRCOND &&
5697 User->getOpcode() != ISD::SETCC &&
5698 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5710 // Due to the ISEL shortcoming noted above, be conservative if this op is
5711 // likely to be selected as part of a load-modify-store instruction.
5712 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5713 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5714 if (UI->getOpcode() == ISD::STORE)
5716 // Otherwise use a regular EFLAGS-setting instruction.
5717 switch (Op.getNode()->getOpcode()) {
5718 case ISD::SUB: Opcode = X86ISD::SUB; break;
5719 case ISD::OR: Opcode = X86ISD::OR; break;
5720 case ISD::XOR: Opcode = X86ISD::XOR; break;
5721 case ISD::AND: Opcode = X86ISD::AND; break;
5722 default: llvm_unreachable("unexpected operator!");
5733 return SDValue(Op.getNode(), 1);
5739 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5740 SmallVector<SDValue, 4> Ops;
5741 for (unsigned i = 0; i != NumOperands; ++i)
5742 Ops.push_back(Op.getOperand(i));
5743 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5744 DAG.ReplaceAllUsesWith(Op, New);
5745 return SDValue(New.getNode(), 1);
5749 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5750 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5751 DAG.getConstant(0, Op.getValueType()));
5754 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5756 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5757 SelectionDAG &DAG) {
5758 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5759 if (C->getAPIntValue() == 0)
5760 return EmitTest(Op0, X86CC, DAG);
5762 DebugLoc dl = Op0.getDebugLoc();
5763 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5766 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
5767 /// if it's possible.
5768 static SDValue LowerToBT(SDValue Op0, ISD::CondCode CC,
5769 DebugLoc dl, SelectionDAG &DAG) {
5771 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5772 if (ConstantSDNode *Op010C =
5773 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5774 if (Op010C->getZExtValue() == 1) {
5775 LHS = Op0.getOperand(0);
5776 RHS = Op0.getOperand(1).getOperand(1);
5778 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5779 if (ConstantSDNode *Op000C =
5780 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5781 if (Op000C->getZExtValue() == 1) {
5782 LHS = Op0.getOperand(1);
5783 RHS = Op0.getOperand(0).getOperand(1);
5785 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5786 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5787 SDValue AndLHS = Op0.getOperand(0);
5788 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5789 LHS = AndLHS.getOperand(0);
5790 RHS = AndLHS.getOperand(1);
5794 if (LHS.getNode()) {
5795 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5796 // instruction. Since the shift amount is in-range-or-undefined, we know
5797 // that doing a bittest on the i16 value is ok. We extend to i32 because
5798 // the encoding for the i16 version is larger than the i32 version.
5799 if (LHS.getValueType() == MVT::i8)
5800 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5802 // If the operand types disagree, extend the shift amount to match. Since
5803 // BT ignores high bits (like shifts) we can use anyextend.
5804 if (LHS.getValueType() != RHS.getValueType())
5805 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5807 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5808 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5809 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5810 DAG.getConstant(Cond, MVT::i8), BT);
5816 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5817 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5818 SDValue Op0 = Op.getOperand(0);
5819 SDValue Op1 = Op.getOperand(1);
5820 DebugLoc dl = Op.getDebugLoc();
5821 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5823 // Optimize to BT if possible.
5824 // Lower (X & (1 << N)) == 0 to BT(X, N).
5825 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5826 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5827 if (Op0.getOpcode() == ISD::AND &&
5829 Op1.getOpcode() == ISD::Constant &&
5830 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5831 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5832 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
5833 if (NewSetCC.getNode())
5837 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5838 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5839 if (X86CC == X86::COND_INVALID)
5842 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5844 // Use sbb x, x to materialize carry bit into a GPR.
5845 if (X86CC == X86::COND_B)
5846 return DAG.getNode(ISD::AND, dl, MVT::i8,
5847 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
5848 DAG.getConstant(X86CC, MVT::i8), Cond),
5849 DAG.getConstant(1, MVT::i8));
5851 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5852 DAG.getConstant(X86CC, MVT::i8), Cond);
5855 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5857 SDValue Op0 = Op.getOperand(0);
5858 SDValue Op1 = Op.getOperand(1);
5859 SDValue CC = Op.getOperand(2);
5860 EVT VT = Op.getValueType();
5861 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5862 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5863 DebugLoc dl = Op.getDebugLoc();
5867 EVT VT0 = Op0.getValueType();
5868 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5869 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5872 switch (SetCCOpcode) {
5875 case ISD::SETEQ: SSECC = 0; break;
5877 case ISD::SETGT: Swap = true; // Fallthrough
5879 case ISD::SETOLT: SSECC = 1; break;
5881 case ISD::SETGE: Swap = true; // Fallthrough
5883 case ISD::SETOLE: SSECC = 2; break;
5884 case ISD::SETUO: SSECC = 3; break;
5886 case ISD::SETNE: SSECC = 4; break;
5887 case ISD::SETULE: Swap = true;
5888 case ISD::SETUGE: SSECC = 5; break;
5889 case ISD::SETULT: Swap = true;
5890 case ISD::SETUGT: SSECC = 6; break;
5891 case ISD::SETO: SSECC = 7; break;
5894 std::swap(Op0, Op1);
5896 // In the two special cases we can't handle, emit two comparisons.
5898 if (SetCCOpcode == ISD::SETUEQ) {
5900 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5901 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5902 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5904 else if (SetCCOpcode == ISD::SETONE) {
5906 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5907 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5908 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5910 llvm_unreachable("Illegal FP comparison");
5912 // Handle all other FP comparisons here.
5913 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5916 // We are handling one of the integer comparisons here. Since SSE only has
5917 // GT and EQ comparisons for integer, swapping operands and multiple
5918 // operations may be required for some comparisons.
5919 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5920 bool Swap = false, Invert = false, FlipSigns = false;
5922 switch (VT.getSimpleVT().SimpleTy) {
5925 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5927 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5929 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5930 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5933 switch (SetCCOpcode) {
5935 case ISD::SETNE: Invert = true;
5936 case ISD::SETEQ: Opc = EQOpc; break;
5937 case ISD::SETLT: Swap = true;
5938 case ISD::SETGT: Opc = GTOpc; break;
5939 case ISD::SETGE: Swap = true;
5940 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5941 case ISD::SETULT: Swap = true;
5942 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5943 case ISD::SETUGE: Swap = true;
5944 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5947 std::swap(Op0, Op1);
5949 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5950 // bits of the inputs before performing those operations.
5952 EVT EltVT = VT.getVectorElementType();
5953 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5955 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5956 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5958 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5959 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5962 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5964 // If the logical-not of the result is required, perform that now.
5966 Result = DAG.getNOT(dl, Result, VT);
5971 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5972 static bool isX86LogicalCmp(SDValue Op) {
5973 unsigned Opc = Op.getNode()->getOpcode();
5974 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5976 if (Op.getResNo() == 1 &&
5977 (Opc == X86ISD::ADD ||
5978 Opc == X86ISD::SUB ||
5979 Opc == X86ISD::SMUL ||
5980 Opc == X86ISD::UMUL ||
5981 Opc == X86ISD::INC ||
5982 Opc == X86ISD::DEC ||
5983 Opc == X86ISD::OR ||
5984 Opc == X86ISD::XOR ||
5985 Opc == X86ISD::AND))
5991 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5992 bool addTest = true;
5993 SDValue Cond = Op.getOperand(0);
5994 DebugLoc dl = Op.getDebugLoc();
5997 if (Cond.getOpcode() == ISD::SETCC) {
5998 SDValue NewCond = LowerSETCC(Cond, DAG);
5999 if (NewCond.getNode())
6003 // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6004 SDValue Op1 = Op.getOperand(1);
6005 SDValue Op2 = Op.getOperand(2);
6006 if (Cond.getOpcode() == X86ISD::SETCC &&
6007 cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6008 SDValue Cmp = Cond.getOperand(1);
6009 if (Cmp.getOpcode() == X86ISD::CMP) {
6010 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6011 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6012 ConstantSDNode *RHSC =
6013 dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6014 if (N1C && N1C->isAllOnesValue() &&
6015 N2C && N2C->isNullValue() &&
6016 RHSC && RHSC->isNullValue()) {
6017 SDValue CmpOp0 = Cmp.getOperand(0);
6018 Cmp = DAG.getNode(X86ISD::CMP, dl, Op.getValueType(),
6019 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6020 return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6021 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6026 // Look pass (and (setcc_carry (cmp ...)), 1).
6027 if (Cond.getOpcode() == ISD::AND &&
6028 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6029 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6030 if (C && C->getAPIntValue() == 1)
6031 Cond = Cond.getOperand(0);
6034 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6035 // setting operand in place of the X86ISD::SETCC.
6036 if (Cond.getOpcode() == X86ISD::SETCC ||
6037 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6038 CC = Cond.getOperand(0);
6040 SDValue Cmp = Cond.getOperand(1);
6041 unsigned Opc = Cmp.getOpcode();
6042 EVT VT = Op.getValueType();
6044 bool IllegalFPCMov = false;
6045 if (VT.isFloatingPoint() && !VT.isVector() &&
6046 !isScalarFPTypeInSSEReg(VT)) // FPStack?
6047 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6049 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6050 Opc == X86ISD::BT) { // FIXME
6057 // Look pass the truncate.
6058 if (Cond.getOpcode() == ISD::TRUNCATE)
6059 Cond = Cond.getOperand(0);
6061 // We know the result of AND is compared against zero. Try to match
6063 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6064 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6065 if (NewSetCC.getNode()) {
6066 CC = NewSetCC.getOperand(0);
6067 Cond = NewSetCC.getOperand(1);
6074 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6075 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6078 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6079 // condition is true.
6080 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6081 SDValue Ops[] = { Op2, Op1, CC, Cond };
6082 return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6085 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6086 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6087 // from the AND / OR.
6088 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6089 Opc = Op.getOpcode();
6090 if (Opc != ISD::OR && Opc != ISD::AND)
6092 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6093 Op.getOperand(0).hasOneUse() &&
6094 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6095 Op.getOperand(1).hasOneUse());
6098 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6099 // 1 and that the SETCC node has a single use.
6100 static bool isXor1OfSetCC(SDValue Op) {
6101 if (Op.getOpcode() != ISD::XOR)
6103 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6104 if (N1C && N1C->getAPIntValue() == 1) {
6105 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6106 Op.getOperand(0).hasOneUse();
6111 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
6112 bool addTest = true;
6113 SDValue Chain = Op.getOperand(0);
6114 SDValue Cond = Op.getOperand(1);
6115 SDValue Dest = Op.getOperand(2);
6116 DebugLoc dl = Op.getDebugLoc();
6119 if (Cond.getOpcode() == ISD::SETCC) {
6120 SDValue NewCond = LowerSETCC(Cond, DAG);
6121 if (NewCond.getNode())
6125 // FIXME: LowerXALUO doesn't handle these!!
6126 else if (Cond.getOpcode() == X86ISD::ADD ||
6127 Cond.getOpcode() == X86ISD::SUB ||
6128 Cond.getOpcode() == X86ISD::SMUL ||
6129 Cond.getOpcode() == X86ISD::UMUL)
6130 Cond = LowerXALUO(Cond, DAG);
6133 // Look pass (and (setcc_carry (cmp ...)), 1).
6134 if (Cond.getOpcode() == ISD::AND &&
6135 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6136 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6137 if (C && C->getAPIntValue() == 1)
6138 Cond = Cond.getOperand(0);
6141 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6142 // setting operand in place of the X86ISD::SETCC.
6143 if (Cond.getOpcode() == X86ISD::SETCC ||
6144 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6145 CC = Cond.getOperand(0);
6147 SDValue Cmp = Cond.getOperand(1);
6148 unsigned Opc = Cmp.getOpcode();
6149 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6150 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6154 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6158 // These can only come from an arithmetic instruction with overflow,
6159 // e.g. SADDO, UADDO.
6160 Cond = Cond.getNode()->getOperand(1);
6167 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6168 SDValue Cmp = Cond.getOperand(0).getOperand(1);
6169 if (CondOpc == ISD::OR) {
6170 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6171 // two branches instead of an explicit OR instruction with a
6173 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6174 isX86LogicalCmp(Cmp)) {
6175 CC = Cond.getOperand(0).getOperand(0);
6176 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6177 Chain, Dest, CC, Cmp);
6178 CC = Cond.getOperand(1).getOperand(0);
6182 } else { // ISD::AND
6183 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6184 // two branches instead of an explicit AND instruction with a
6185 // separate test. However, we only do this if this block doesn't
6186 // have a fall-through edge, because this requires an explicit
6187 // jmp when the condition is false.
6188 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6189 isX86LogicalCmp(Cmp) &&
6190 Op.getNode()->hasOneUse()) {
6191 X86::CondCode CCode =
6192 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6193 CCode = X86::GetOppositeBranchCondition(CCode);
6194 CC = DAG.getConstant(CCode, MVT::i8);
6195 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6196 // Look for an unconditional branch following this conditional branch.
6197 // We need this because we need to reverse the successors in order
6198 // to implement FCMP_OEQ.
6199 if (User.getOpcode() == ISD::BR) {
6200 SDValue FalseBB = User.getOperand(1);
6202 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6203 assert(NewBR == User);
6206 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6207 Chain, Dest, CC, Cmp);
6208 X86::CondCode CCode =
6209 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6210 CCode = X86::GetOppositeBranchCondition(CCode);
6211 CC = DAG.getConstant(CCode, MVT::i8);
6217 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6218 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6219 // It should be transformed during dag combiner except when the condition
6220 // is set by a arithmetics with overflow node.
6221 X86::CondCode CCode =
6222 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6223 CCode = X86::GetOppositeBranchCondition(CCode);
6224 CC = DAG.getConstant(CCode, MVT::i8);
6225 Cond = Cond.getOperand(0).getOperand(1);
6231 // Look pass the truncate.
6232 if (Cond.getOpcode() == ISD::TRUNCATE)
6233 Cond = Cond.getOperand(0);
6235 // We know the result of AND is compared against zero. Try to match
6237 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6238 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6239 if (NewSetCC.getNode()) {
6240 CC = NewSetCC.getOperand(0);
6241 Cond = NewSetCC.getOperand(1);
6248 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6249 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6251 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6252 Chain, Dest, CC, Cond);
6256 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6257 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6258 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6259 // that the guard pages used by the OS virtual memory manager are allocated in
6260 // correct sequence.
6262 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6263 SelectionDAG &DAG) {
6264 assert(Subtarget->isTargetCygMing() &&
6265 "This should be used only on Cygwin/Mingw targets");
6266 DebugLoc dl = Op.getDebugLoc();
6269 SDValue Chain = Op.getOperand(0);
6270 SDValue Size = Op.getOperand(1);
6271 // FIXME: Ensure alignment here
6275 EVT IntPtr = getPointerTy();
6276 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6278 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
6280 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6281 Flag = Chain.getValue(1);
6283 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6284 SDValue Ops[] = { Chain,
6285 DAG.getTargetExternalSymbol("_alloca", IntPtr),
6286 DAG.getRegister(X86::EAX, IntPtr),
6287 DAG.getRegister(X86StackPtr, SPTy),
6289 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
6290 Flag = Chain.getValue(1);
6292 Chain = DAG.getCALLSEQ_END(Chain,
6293 DAG.getIntPtrConstant(0, true),
6294 DAG.getIntPtrConstant(0, true),
6297 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6299 SDValue Ops1[2] = { Chain.getValue(0), Chain };
6300 return DAG.getMergeValues(Ops1, 2, dl);
6304 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6306 SDValue Dst, SDValue Src,
6307 SDValue Size, unsigned Align,
6309 uint64_t DstSVOff) {
6310 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6312 // If not DWORD aligned or size is more than the threshold, call the library.
6313 // The libc version is likely to be faster for these cases. It can use the
6314 // address value and run time information about the CPU.
6315 if ((Align & 3) != 0 ||
6317 ConstantSize->getZExtValue() >
6318 getSubtarget()->getMaxInlineSizeThreshold()) {
6319 SDValue InFlag(0, 0);
6321 // Check to see if there is a specialized entry-point for memory zeroing.
6322 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6324 if (const char *bzeroEntry = V &&
6325 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6326 EVT IntPtr = getPointerTy();
6327 const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6328 TargetLowering::ArgListTy Args;
6329 TargetLowering::ArgListEntry Entry;
6331 Entry.Ty = IntPtrTy;
6332 Args.push_back(Entry);
6334 Args.push_back(Entry);
6335 std::pair<SDValue,SDValue> CallResult =
6336 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6337 false, false, false, false,
6338 0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6339 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl,
6340 DAG.GetOrdering(Chain.getNode()));
6341 return CallResult.second;
6344 // Otherwise have the target-independent code call memset.
6348 uint64_t SizeVal = ConstantSize->getZExtValue();
6349 SDValue InFlag(0, 0);
6352 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6353 unsigned BytesLeft = 0;
6354 bool TwoRepStos = false;
6357 uint64_t Val = ValC->getZExtValue() & 255;
6359 // If the value is a constant, then we can potentially use larger sets.
6360 switch (Align & 3) {
6361 case 2: // WORD aligned
6364 Val = (Val << 8) | Val;
6366 case 0: // DWORD aligned
6369 Val = (Val << 8) | Val;
6370 Val = (Val << 16) | Val;
6371 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
6374 Val = (Val << 32) | Val;
6377 default: // Byte aligned
6380 Count = DAG.getIntPtrConstant(SizeVal);
6384 if (AVT.bitsGT(MVT::i8)) {
6385 unsigned UBytes = AVT.getSizeInBits() / 8;
6386 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6387 BytesLeft = SizeVal % UBytes;
6390 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6392 InFlag = Chain.getValue(1);
6395 Count = DAG.getIntPtrConstant(SizeVal);
6396 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6397 InFlag = Chain.getValue(1);
6400 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6403 InFlag = Chain.getValue(1);
6404 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6407 InFlag = Chain.getValue(1);
6409 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6410 SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6411 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6414 InFlag = Chain.getValue(1);
6416 EVT CVT = Count.getValueType();
6417 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6418 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6419 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6422 InFlag = Chain.getValue(1);
6423 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6424 SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag };
6425 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6426 } else if (BytesLeft) {
6427 // Handle the last 1 - 7 bytes.
6428 unsigned Offset = SizeVal - BytesLeft;
6429 EVT AddrVT = Dst.getValueType();
6430 EVT SizeVT = Size.getValueType();
6432 Chain = DAG.getMemset(Chain, dl,
6433 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6434 DAG.getConstant(Offset, AddrVT)),
6436 DAG.getConstant(BytesLeft, SizeVT),
6437 Align, DstSV, DstSVOff + Offset);
6440 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6445 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6446 SDValue Chain, SDValue Dst, SDValue Src,
6447 SDValue Size, unsigned Align,
6449 const Value *DstSV, uint64_t DstSVOff,
6450 const Value *SrcSV, uint64_t SrcSVOff) {
6451 // This requires the copy size to be a constant, preferrably
6452 // within a subtarget-specific limit.
6453 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6456 uint64_t SizeVal = ConstantSize->getZExtValue();
6457 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6460 /// If not DWORD aligned, call the library.
6461 if ((Align & 3) != 0)
6466 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
6469 unsigned UBytes = AVT.getSizeInBits() / 8;
6470 unsigned CountVal = SizeVal / UBytes;
6471 SDValue Count = DAG.getIntPtrConstant(CountVal);
6472 unsigned BytesLeft = SizeVal % UBytes;
6474 SDValue InFlag(0, 0);
6475 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6478 InFlag = Chain.getValue(1);
6479 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6482 InFlag = Chain.getValue(1);
6483 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6486 InFlag = Chain.getValue(1);
6488 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6489 SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6490 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops,
6491 array_lengthof(Ops));
6493 SmallVector<SDValue, 4> Results;
6494 Results.push_back(RepMovs);
6496 // Handle the last 1 - 7 bytes.
6497 unsigned Offset = SizeVal - BytesLeft;
6498 EVT DstVT = Dst.getValueType();
6499 EVT SrcVT = Src.getValueType();
6500 EVT SizeVT = Size.getValueType();
6501 Results.push_back(DAG.getMemcpy(Chain, dl,
6502 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6503 DAG.getConstant(Offset, DstVT)),
6504 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6505 DAG.getConstant(Offset, SrcVT)),
6506 DAG.getConstant(BytesLeft, SizeVT),
6507 Align, AlwaysInline,
6508 DstSV, DstSVOff + Offset,
6509 SrcSV, SrcSVOff + Offset));
6512 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6513 &Results[0], Results.size());
6516 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6517 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6518 DebugLoc dl = Op.getDebugLoc();
6520 if (!Subtarget->is64Bit()) {
6521 // vastart just stores the address of the VarArgsFrameIndex slot into the
6522 // memory location argument.
6523 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6524 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6528 // gp_offset (0 - 6 * 8)
6529 // fp_offset (48 - 48 + 8 * 16)
6530 // overflow_arg_area (point to parameters coming in memory).
6532 SmallVector<SDValue, 8> MemOps;
6533 SDValue FIN = Op.getOperand(1);
6535 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6536 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6538 MemOps.push_back(Store);
6541 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6542 FIN, DAG.getIntPtrConstant(4));
6543 Store = DAG.getStore(Op.getOperand(0), dl,
6544 DAG.getConstant(VarArgsFPOffset, MVT::i32),
6546 MemOps.push_back(Store);
6548 // Store ptr to overflow_arg_area
6549 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6550 FIN, DAG.getIntPtrConstant(4));
6551 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6552 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6553 MemOps.push_back(Store);
6555 // Store ptr to reg_save_area.
6556 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6557 FIN, DAG.getIntPtrConstant(8));
6558 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6559 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6560 MemOps.push_back(Store);
6561 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6562 &MemOps[0], MemOps.size());
6565 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6566 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6567 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6568 SDValue Chain = Op.getOperand(0);
6569 SDValue SrcPtr = Op.getOperand(1);
6570 SDValue SrcSV = Op.getOperand(2);
6572 llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6576 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6577 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6578 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6579 SDValue Chain = Op.getOperand(0);
6580 SDValue DstPtr = Op.getOperand(1);
6581 SDValue SrcPtr = Op.getOperand(2);
6582 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6583 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6584 DebugLoc dl = Op.getDebugLoc();
6586 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6587 DAG.getIntPtrConstant(24), 8, false,
6588 DstSV, 0, SrcSV, 0);
6592 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6593 DebugLoc dl = Op.getDebugLoc();
6594 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6596 default: return SDValue(); // Don't custom lower most intrinsics.
6597 // Comparison intrinsics.
6598 case Intrinsic::x86_sse_comieq_ss:
6599 case Intrinsic::x86_sse_comilt_ss:
6600 case Intrinsic::x86_sse_comile_ss:
6601 case Intrinsic::x86_sse_comigt_ss:
6602 case Intrinsic::x86_sse_comige_ss:
6603 case Intrinsic::x86_sse_comineq_ss:
6604 case Intrinsic::x86_sse_ucomieq_ss:
6605 case Intrinsic::x86_sse_ucomilt_ss:
6606 case Intrinsic::x86_sse_ucomile_ss:
6607 case Intrinsic::x86_sse_ucomigt_ss:
6608 case Intrinsic::x86_sse_ucomige_ss:
6609 case Intrinsic::x86_sse_ucomineq_ss:
6610 case Intrinsic::x86_sse2_comieq_sd:
6611 case Intrinsic::x86_sse2_comilt_sd:
6612 case Intrinsic::x86_sse2_comile_sd:
6613 case Intrinsic::x86_sse2_comigt_sd:
6614 case Intrinsic::x86_sse2_comige_sd:
6615 case Intrinsic::x86_sse2_comineq_sd:
6616 case Intrinsic::x86_sse2_ucomieq_sd:
6617 case Intrinsic::x86_sse2_ucomilt_sd:
6618 case Intrinsic::x86_sse2_ucomile_sd:
6619 case Intrinsic::x86_sse2_ucomigt_sd:
6620 case Intrinsic::x86_sse2_ucomige_sd:
6621 case Intrinsic::x86_sse2_ucomineq_sd: {
6623 ISD::CondCode CC = ISD::SETCC_INVALID;
6626 case Intrinsic::x86_sse_comieq_ss:
6627 case Intrinsic::x86_sse2_comieq_sd:
6631 case Intrinsic::x86_sse_comilt_ss:
6632 case Intrinsic::x86_sse2_comilt_sd:
6636 case Intrinsic::x86_sse_comile_ss:
6637 case Intrinsic::x86_sse2_comile_sd:
6641 case Intrinsic::x86_sse_comigt_ss:
6642 case Intrinsic::x86_sse2_comigt_sd:
6646 case Intrinsic::x86_sse_comige_ss:
6647 case Intrinsic::x86_sse2_comige_sd:
6651 case Intrinsic::x86_sse_comineq_ss:
6652 case Intrinsic::x86_sse2_comineq_sd:
6656 case Intrinsic::x86_sse_ucomieq_ss:
6657 case Intrinsic::x86_sse2_ucomieq_sd:
6658 Opc = X86ISD::UCOMI;
6661 case Intrinsic::x86_sse_ucomilt_ss:
6662 case Intrinsic::x86_sse2_ucomilt_sd:
6663 Opc = X86ISD::UCOMI;
6666 case Intrinsic::x86_sse_ucomile_ss:
6667 case Intrinsic::x86_sse2_ucomile_sd:
6668 Opc = X86ISD::UCOMI;
6671 case Intrinsic::x86_sse_ucomigt_ss:
6672 case Intrinsic::x86_sse2_ucomigt_sd:
6673 Opc = X86ISD::UCOMI;
6676 case Intrinsic::x86_sse_ucomige_ss:
6677 case Intrinsic::x86_sse2_ucomige_sd:
6678 Opc = X86ISD::UCOMI;
6681 case Intrinsic::x86_sse_ucomineq_ss:
6682 case Intrinsic::x86_sse2_ucomineq_sd:
6683 Opc = X86ISD::UCOMI;
6688 SDValue LHS = Op.getOperand(1);
6689 SDValue RHS = Op.getOperand(2);
6690 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6691 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6692 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6693 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6694 DAG.getConstant(X86CC, MVT::i8), Cond);
6695 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6697 // ptest intrinsics. The intrinsic these come from are designed to return
6698 // an integer value, not just an instruction so lower it to the ptest
6699 // pattern and a setcc for the result.
6700 case Intrinsic::x86_sse41_ptestz:
6701 case Intrinsic::x86_sse41_ptestc:
6702 case Intrinsic::x86_sse41_ptestnzc:{
6705 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6706 case Intrinsic::x86_sse41_ptestz:
6708 X86CC = X86::COND_E;
6710 case Intrinsic::x86_sse41_ptestc:
6712 X86CC = X86::COND_B;
6714 case Intrinsic::x86_sse41_ptestnzc:
6716 X86CC = X86::COND_A;
6720 SDValue LHS = Op.getOperand(1);
6721 SDValue RHS = Op.getOperand(2);
6722 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6723 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6724 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6725 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6728 // Fix vector shift instructions where the last operand is a non-immediate
6730 case Intrinsic::x86_sse2_pslli_w:
6731 case Intrinsic::x86_sse2_pslli_d:
6732 case Intrinsic::x86_sse2_pslli_q:
6733 case Intrinsic::x86_sse2_psrli_w:
6734 case Intrinsic::x86_sse2_psrli_d:
6735 case Intrinsic::x86_sse2_psrli_q:
6736 case Intrinsic::x86_sse2_psrai_w:
6737 case Intrinsic::x86_sse2_psrai_d:
6738 case Intrinsic::x86_mmx_pslli_w:
6739 case Intrinsic::x86_mmx_pslli_d:
6740 case Intrinsic::x86_mmx_pslli_q:
6741 case Intrinsic::x86_mmx_psrli_w:
6742 case Intrinsic::x86_mmx_psrli_d:
6743 case Intrinsic::x86_mmx_psrli_q:
6744 case Intrinsic::x86_mmx_psrai_w:
6745 case Intrinsic::x86_mmx_psrai_d: {
6746 SDValue ShAmt = Op.getOperand(2);
6747 if (isa<ConstantSDNode>(ShAmt))
6750 unsigned NewIntNo = 0;
6751 EVT ShAmtVT = MVT::v4i32;
6753 case Intrinsic::x86_sse2_pslli_w:
6754 NewIntNo = Intrinsic::x86_sse2_psll_w;
6756 case Intrinsic::x86_sse2_pslli_d:
6757 NewIntNo = Intrinsic::x86_sse2_psll_d;
6759 case Intrinsic::x86_sse2_pslli_q:
6760 NewIntNo = Intrinsic::x86_sse2_psll_q;
6762 case Intrinsic::x86_sse2_psrli_w:
6763 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6765 case Intrinsic::x86_sse2_psrli_d:
6766 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6768 case Intrinsic::x86_sse2_psrli_q:
6769 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6771 case Intrinsic::x86_sse2_psrai_w:
6772 NewIntNo = Intrinsic::x86_sse2_psra_w;
6774 case Intrinsic::x86_sse2_psrai_d:
6775 NewIntNo = Intrinsic::x86_sse2_psra_d;
6778 ShAmtVT = MVT::v2i32;
6780 case Intrinsic::x86_mmx_pslli_w:
6781 NewIntNo = Intrinsic::x86_mmx_psll_w;
6783 case Intrinsic::x86_mmx_pslli_d:
6784 NewIntNo = Intrinsic::x86_mmx_psll_d;
6786 case Intrinsic::x86_mmx_pslli_q:
6787 NewIntNo = Intrinsic::x86_mmx_psll_q;
6789 case Intrinsic::x86_mmx_psrli_w:
6790 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6792 case Intrinsic::x86_mmx_psrli_d:
6793 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6795 case Intrinsic::x86_mmx_psrli_q:
6796 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6798 case Intrinsic::x86_mmx_psrai_w:
6799 NewIntNo = Intrinsic::x86_mmx_psra_w;
6801 case Intrinsic::x86_mmx_psrai_d:
6802 NewIntNo = Intrinsic::x86_mmx_psra_d;
6804 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6810 // The vector shift intrinsics with scalars uses 32b shift amounts but
6811 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6815 ShOps[1] = DAG.getConstant(0, MVT::i32);
6816 if (ShAmtVT == MVT::v4i32) {
6817 ShOps[2] = DAG.getUNDEF(MVT::i32);
6818 ShOps[3] = DAG.getUNDEF(MVT::i32);
6819 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6821 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6824 EVT VT = Op.getValueType();
6825 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6826 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6827 DAG.getConstant(NewIntNo, MVT::i32),
6828 Op.getOperand(1), ShAmt);
6833 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6834 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6835 DebugLoc dl = Op.getDebugLoc();
6838 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6840 DAG.getConstant(TD->getPointerSize(),
6841 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6842 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6843 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6848 // Just load the return address.
6849 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6850 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6851 RetAddrFI, NULL, 0);
6854 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6855 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6856 MFI->setFrameAddressIsTaken(true);
6857 EVT VT = Op.getValueType();
6858 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6859 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6860 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6861 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6863 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6867 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6868 SelectionDAG &DAG) {
6869 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6872 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6874 MachineFunction &MF = DAG.getMachineFunction();
6875 SDValue Chain = Op.getOperand(0);
6876 SDValue Offset = Op.getOperand(1);
6877 SDValue Handler = Op.getOperand(2);
6878 DebugLoc dl = Op.getDebugLoc();
6880 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6882 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6884 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6885 DAG.getIntPtrConstant(-TD->getPointerSize()));
6886 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6887 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6888 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6889 MF.getRegInfo().addLiveOut(StoreAddrReg);
6891 return DAG.getNode(X86ISD::EH_RETURN, dl,
6893 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6896 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6897 SelectionDAG &DAG) {
6898 SDValue Root = Op.getOperand(0);
6899 SDValue Trmp = Op.getOperand(1); // trampoline
6900 SDValue FPtr = Op.getOperand(2); // nested function
6901 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6902 DebugLoc dl = Op.getDebugLoc();
6904 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6906 const X86InstrInfo *TII =
6907 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6909 if (Subtarget->is64Bit()) {
6910 SDValue OutChains[6];
6912 // Large code-model.
6914 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6915 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6917 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6918 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6920 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6922 // Load the pointer to the nested function into R11.
6923 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6924 SDValue Addr = Trmp;
6925 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6928 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6929 DAG.getConstant(2, MVT::i64));
6930 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6932 // Load the 'nest' parameter value into R10.
6933 // R10 is specified in X86CallingConv.td
6934 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6935 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6936 DAG.getConstant(10, MVT::i64));
6937 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6938 Addr, TrmpAddr, 10);
6940 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6941 DAG.getConstant(12, MVT::i64));
6942 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6944 // Jump to the nested function.
6945 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6946 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6947 DAG.getConstant(20, MVT::i64));
6948 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6949 Addr, TrmpAddr, 20);
6951 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6952 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6953 DAG.getConstant(22, MVT::i64));
6954 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6958 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6959 return DAG.getMergeValues(Ops, 2, dl);
6961 const Function *Func =
6962 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6963 CallingConv::ID CC = Func->getCallingConv();
6968 llvm_unreachable("Unsupported calling convention");
6969 case CallingConv::C:
6970 case CallingConv::X86_StdCall: {
6971 // Pass 'nest' parameter in ECX.
6972 // Must be kept in sync with X86CallingConv.td
6975 // Check that ECX wasn't needed by an 'inreg' parameter.
6976 const FunctionType *FTy = Func->getFunctionType();
6977 const AttrListPtr &Attrs = Func->getAttributes();
6979 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6980 unsigned InRegCount = 0;
6983 for (FunctionType::param_iterator I = FTy->param_begin(),
6984 E = FTy->param_end(); I != E; ++I, ++Idx)
6985 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6986 // FIXME: should only count parameters that are lowered to integers.
6987 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6989 if (InRegCount > 2) {
6990 llvm_report_error("Nest register in use - reduce number of inreg parameters!");
6995 case CallingConv::X86_FastCall:
6996 case CallingConv::Fast:
6997 // Pass 'nest' parameter in EAX.
6998 // Must be kept in sync with X86CallingConv.td
7003 SDValue OutChains[4];
7006 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7007 DAG.getConstant(10, MVT::i32));
7008 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7010 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
7011 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7012 OutChains[0] = DAG.getStore(Root, dl,
7013 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7016 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7017 DAG.getConstant(1, MVT::i32));
7018 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
7020 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
7021 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7022 DAG.getConstant(5, MVT::i32));
7023 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7024 TrmpAddr, 5, false, 1);
7026 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7027 DAG.getConstant(6, MVT::i32));
7028 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
7031 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7032 return DAG.getMergeValues(Ops, 2, dl);
7036 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
7038 The rounding mode is in bits 11:10 of FPSR, and has the following
7045 FLT_ROUNDS, on the other hand, expects the following:
7052 To perform the conversion, we do:
7053 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7056 MachineFunction &MF = DAG.getMachineFunction();
7057 const TargetMachine &TM = MF.getTarget();
7058 const TargetFrameInfo &TFI = *TM.getFrameInfo();
7059 unsigned StackAlignment = TFI.getStackAlignment();
7060 EVT VT = Op.getValueType();
7061 DebugLoc dl = Op.getDebugLoc();
7063 // Save FP Control Word to stack slot
7064 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7065 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7067 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7068 DAG.getEntryNode(), StackSlot);
7070 // Load FP Control Word from stack slot
7071 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
7073 // Transform as necessary
7075 DAG.getNode(ISD::SRL, dl, MVT::i16,
7076 DAG.getNode(ISD::AND, dl, MVT::i16,
7077 CWD, DAG.getConstant(0x800, MVT::i16)),
7078 DAG.getConstant(11, MVT::i8));
7080 DAG.getNode(ISD::SRL, dl, MVT::i16,
7081 DAG.getNode(ISD::AND, dl, MVT::i16,
7082 CWD, DAG.getConstant(0x400, MVT::i16)),
7083 DAG.getConstant(9, MVT::i8));
7086 DAG.getNode(ISD::AND, dl, MVT::i16,
7087 DAG.getNode(ISD::ADD, dl, MVT::i16,
7088 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7089 DAG.getConstant(1, MVT::i16)),
7090 DAG.getConstant(3, MVT::i16));
7093 return DAG.getNode((VT.getSizeInBits() < 16 ?
7094 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7097 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
7098 EVT VT = Op.getValueType();
7100 unsigned NumBits = VT.getSizeInBits();
7101 DebugLoc dl = Op.getDebugLoc();
7103 Op = Op.getOperand(0);
7104 if (VT == MVT::i8) {
7105 // Zero extend to i32 since there is not an i8 bsr.
7107 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7110 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7111 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7112 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7114 // If src is zero (i.e. bsr sets ZF), returns NumBits.
7117 DAG.getConstant(NumBits+NumBits-1, OpVT),
7118 DAG.getConstant(X86::COND_E, MVT::i8),
7121 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7123 // Finally xor with NumBits-1.
7124 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7127 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7131 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
7132 EVT VT = Op.getValueType();
7134 unsigned NumBits = VT.getSizeInBits();
7135 DebugLoc dl = Op.getDebugLoc();
7137 Op = Op.getOperand(0);
7138 if (VT == MVT::i8) {
7140 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7143 // Issue a bsf (scan bits forward) which also sets EFLAGS.
7144 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7145 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7147 // If src is zero (i.e. bsf sets ZF), returns NumBits.
7150 DAG.getConstant(NumBits, OpVT),
7151 DAG.getConstant(X86::COND_E, MVT::i8),
7154 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7157 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7161 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
7162 EVT VT = Op.getValueType();
7163 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7164 DebugLoc dl = Op.getDebugLoc();
7166 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7167 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7168 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7169 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7170 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7172 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7173 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7174 // return AloBlo + AloBhi + AhiBlo;
7176 SDValue A = Op.getOperand(0);
7177 SDValue B = Op.getOperand(1);
7179 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7180 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7181 A, DAG.getConstant(32, MVT::i32));
7182 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7183 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7184 B, DAG.getConstant(32, MVT::i32));
7185 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7186 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7188 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7189 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7191 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7192 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7194 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7195 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7196 AloBhi, DAG.getConstant(32, MVT::i32));
7197 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7198 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7199 AhiBlo, DAG.getConstant(32, MVT::i32));
7200 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7201 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7206 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
7207 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7208 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7209 // looks for this combo and may remove the "setcc" instruction if the "setcc"
7210 // has only one use.
7211 SDNode *N = Op.getNode();
7212 SDValue LHS = N->getOperand(0);
7213 SDValue RHS = N->getOperand(1);
7214 unsigned BaseOp = 0;
7216 DebugLoc dl = Op.getDebugLoc();
7218 switch (Op.getOpcode()) {
7219 default: llvm_unreachable("Unknown ovf instruction!");
7221 // A subtract of one will be selected as a INC. Note that INC doesn't
7222 // set CF, so we can't do this for UADDO.
7223 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7224 if (C->getAPIntValue() == 1) {
7225 BaseOp = X86ISD::INC;
7229 BaseOp = X86ISD::ADD;
7233 BaseOp = X86ISD::ADD;
7237 // A subtract of one will be selected as a DEC. Note that DEC doesn't
7238 // set CF, so we can't do this for USUBO.
7239 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7240 if (C->getAPIntValue() == 1) {
7241 BaseOp = X86ISD::DEC;
7245 BaseOp = X86ISD::SUB;
7249 BaseOp = X86ISD::SUB;
7253 BaseOp = X86ISD::SMUL;
7257 BaseOp = X86ISD::UMUL;
7262 // Also sets EFLAGS.
7263 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7264 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7267 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7268 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7270 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7274 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
7275 EVT T = Op.getValueType();
7276 DebugLoc dl = Op.getDebugLoc();
7279 switch(T.getSimpleVT().SimpleTy) {
7281 assert(false && "Invalid value type!");
7282 case MVT::i8: Reg = X86::AL; size = 1; break;
7283 case MVT::i16: Reg = X86::AX; size = 2; break;
7284 case MVT::i32: Reg = X86::EAX; size = 4; break;
7286 assert(Subtarget->is64Bit() && "Node not type legal!");
7287 Reg = X86::RAX; size = 8;
7290 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7291 Op.getOperand(2), SDValue());
7292 SDValue Ops[] = { cpIn.getValue(0),
7295 DAG.getTargetConstant(size, MVT::i8),
7297 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7298 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7300 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7304 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7305 SelectionDAG &DAG) {
7306 assert(Subtarget->is64Bit() && "Result not type legalized?");
7307 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7308 SDValue TheChain = Op.getOperand(0);
7309 DebugLoc dl = Op.getDebugLoc();
7310 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7311 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7312 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7314 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7315 DAG.getConstant(32, MVT::i8));
7317 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7320 return DAG.getMergeValues(Ops, 2, dl);
7323 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7324 SDNode *Node = Op.getNode();
7325 DebugLoc dl = Node->getDebugLoc();
7326 EVT T = Node->getValueType(0);
7327 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7328 DAG.getConstant(0, T), Node->getOperand(2));
7329 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7330 cast<AtomicSDNode>(Node)->getMemoryVT(),
7331 Node->getOperand(0),
7332 Node->getOperand(1), negOp,
7333 cast<AtomicSDNode>(Node)->getSrcValue(),
7334 cast<AtomicSDNode>(Node)->getAlignment());
7337 /// LowerOperation - Provide custom lowering hooks for some operations.
7339 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7340 switch (Op.getOpcode()) {
7341 default: llvm_unreachable("Should not custom lower this!");
7342 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
7343 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
7344 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7345 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7346 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7347 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7348 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7349 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7350 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7351 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7352 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7353 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
7354 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7355 case ISD::SHL_PARTS:
7356 case ISD::SRA_PARTS:
7357 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
7358 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
7359 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
7360 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
7361 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
7362 case ISD::FABS: return LowerFABS(Op, DAG);
7363 case ISD::FNEG: return LowerFNEG(Op, DAG);
7364 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7365 case ISD::SETCC: return LowerSETCC(Op, DAG);
7366 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
7367 case ISD::SELECT: return LowerSELECT(Op, DAG);
7368 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
7369 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7370 case ISD::VASTART: return LowerVASTART(Op, DAG);
7371 case ISD::VAARG: return LowerVAARG(Op, DAG);
7372 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
7373 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7374 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7375 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7376 case ISD::FRAME_TO_ARGS_OFFSET:
7377 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7378 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7379 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
7380 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
7381 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7382 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
7383 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
7384 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
7390 case ISD::UMULO: return LowerXALUO(Op, DAG);
7391 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
7395 void X86TargetLowering::
7396 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7397 SelectionDAG &DAG, unsigned NewOp) {
7398 EVT T = Node->getValueType(0);
7399 DebugLoc dl = Node->getDebugLoc();
7400 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7402 SDValue Chain = Node->getOperand(0);
7403 SDValue In1 = Node->getOperand(1);
7404 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7405 Node->getOperand(2), DAG.getIntPtrConstant(0));
7406 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7407 Node->getOperand(2), DAG.getIntPtrConstant(1));
7408 SDValue Ops[] = { Chain, In1, In2L, In2H };
7409 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7411 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7412 cast<MemSDNode>(Node)->getMemOperand());
7413 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7414 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7415 Results.push_back(Result.getValue(2));
7418 /// ReplaceNodeResults - Replace a node with an illegal result type
7419 /// with a new node built out of custom code.
7420 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7421 SmallVectorImpl<SDValue>&Results,
7422 SelectionDAG &DAG) {
7423 DebugLoc dl = N->getDebugLoc();
7424 switch (N->getOpcode()) {
7426 assert(false && "Do not know how to custom type legalize this operation!");
7428 case ISD::FP_TO_SINT: {
7429 std::pair<SDValue,SDValue> Vals =
7430 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7431 SDValue FIST = Vals.first, StackSlot = Vals.second;
7432 if (FIST.getNode() != 0) {
7433 EVT VT = N->getValueType(0);
7434 // Return a load from the stack slot.
7435 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
7439 case ISD::READCYCLECOUNTER: {
7440 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7441 SDValue TheChain = N->getOperand(0);
7442 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7443 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7445 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7447 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7448 SDValue Ops[] = { eax, edx };
7449 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7450 Results.push_back(edx.getValue(1));
7457 EVT WidenVT = getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
7458 Results.push_back(DAG.UnrollVectorOp(N, WidenVT.getVectorNumElements()));
7461 case ISD::ATOMIC_CMP_SWAP: {
7462 EVT T = N->getValueType(0);
7463 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7464 SDValue cpInL, cpInH;
7465 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7466 DAG.getConstant(0, MVT::i32));
7467 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7468 DAG.getConstant(1, MVT::i32));
7469 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7470 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7472 SDValue swapInL, swapInH;
7473 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7474 DAG.getConstant(0, MVT::i32));
7475 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7476 DAG.getConstant(1, MVT::i32));
7477 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7479 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7480 swapInL.getValue(1));
7481 SDValue Ops[] = { swapInH.getValue(0),
7483 swapInH.getValue(1) };
7484 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7485 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7486 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7487 MVT::i32, Result.getValue(1));
7488 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7489 MVT::i32, cpOutL.getValue(2));
7490 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7491 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7492 Results.push_back(cpOutH.getValue(1));
7495 case ISD::ATOMIC_LOAD_ADD:
7496 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7498 case ISD::ATOMIC_LOAD_AND:
7499 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7501 case ISD::ATOMIC_LOAD_NAND:
7502 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7504 case ISD::ATOMIC_LOAD_OR:
7505 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7507 case ISD::ATOMIC_LOAD_SUB:
7508 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7510 case ISD::ATOMIC_LOAD_XOR:
7511 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7513 case ISD::ATOMIC_SWAP:
7514 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7519 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7521 default: return NULL;
7522 case X86ISD::BSF: return "X86ISD::BSF";
7523 case X86ISD::BSR: return "X86ISD::BSR";
7524 case X86ISD::SHLD: return "X86ISD::SHLD";
7525 case X86ISD::SHRD: return "X86ISD::SHRD";
7526 case X86ISD::FAND: return "X86ISD::FAND";
7527 case X86ISD::FOR: return "X86ISD::FOR";
7528 case X86ISD::FXOR: return "X86ISD::FXOR";
7529 case X86ISD::FSRL: return "X86ISD::FSRL";
7530 case X86ISD::FILD: return "X86ISD::FILD";
7531 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7532 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7533 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7534 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7535 case X86ISD::FLD: return "X86ISD::FLD";
7536 case X86ISD::FST: return "X86ISD::FST";
7537 case X86ISD::CALL: return "X86ISD::CALL";
7538 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7539 case X86ISD::BT: return "X86ISD::BT";
7540 case X86ISD::CMP: return "X86ISD::CMP";
7541 case X86ISD::COMI: return "X86ISD::COMI";
7542 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7543 case X86ISD::SETCC: return "X86ISD::SETCC";
7544 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
7545 case X86ISD::CMOV: return "X86ISD::CMOV";
7546 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7547 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7548 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7549 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7550 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7551 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7552 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7553 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7554 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7555 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7556 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7557 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7558 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7559 case X86ISD::FMAX: return "X86ISD::FMAX";
7560 case X86ISD::FMIN: return "X86ISD::FMIN";
7561 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7562 case X86ISD::FRCP: return "X86ISD::FRCP";
7563 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7564 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7565 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7566 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7567 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7568 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7569 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7570 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7571 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7572 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7573 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7574 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7575 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7576 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7577 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7578 case X86ISD::VSHL: return "X86ISD::VSHL";
7579 case X86ISD::VSRL: return "X86ISD::VSRL";
7580 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7581 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7582 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7583 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7584 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7585 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7586 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7587 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7588 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7589 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7590 case X86ISD::ADD: return "X86ISD::ADD";
7591 case X86ISD::SUB: return "X86ISD::SUB";
7592 case X86ISD::SMUL: return "X86ISD::SMUL";
7593 case X86ISD::UMUL: return "X86ISD::UMUL";
7594 case X86ISD::INC: return "X86ISD::INC";
7595 case X86ISD::DEC: return "X86ISD::DEC";
7596 case X86ISD::OR: return "X86ISD::OR";
7597 case X86ISD::XOR: return "X86ISD::XOR";
7598 case X86ISD::AND: return "X86ISD::AND";
7599 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7600 case X86ISD::PTEST: return "X86ISD::PTEST";
7601 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7605 // isLegalAddressingMode - Return true if the addressing mode represented
7606 // by AM is legal for this target, for a load/store of the specified type.
7607 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7608 const Type *Ty) const {
7609 // X86 supports extremely general addressing modes.
7610 CodeModel::Model M = getTargetMachine().getCodeModel();
7612 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7613 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7618 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7620 // If a reference to this global requires an extra load, we can't fold it.
7621 if (isGlobalStubReference(GVFlags))
7624 // If BaseGV requires a register for the PIC base, we cannot also have a
7625 // BaseReg specified.
7626 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7629 // If lower 4G is not available, then we must use rip-relative addressing.
7630 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7640 // These scales always work.
7645 // These scales are formed with basereg+scalereg. Only accept if there is
7650 default: // Other stuff never works.
7658 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7659 if (!Ty1->isInteger() || !Ty2->isInteger())
7661 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7662 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7663 if (NumBits1 <= NumBits2)
7665 return Subtarget->is64Bit() || NumBits1 < 64;
7668 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7669 if (!VT1.isInteger() || !VT2.isInteger())
7671 unsigned NumBits1 = VT1.getSizeInBits();
7672 unsigned NumBits2 = VT2.getSizeInBits();
7673 if (NumBits1 <= NumBits2)
7675 return Subtarget->is64Bit() || NumBits1 < 64;
7678 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7679 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7680 return Ty1->isInteger(32) && Ty2->isInteger(64) && Subtarget->is64Bit();
7683 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7684 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7685 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7688 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7689 // i16 instructions are longer (0x66 prefix) and potentially slower.
7690 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7693 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7694 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7695 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7696 /// are assumed to be legal.
7698 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7700 // Only do shuffles on 128-bit vector types for now.
7701 if (VT.getSizeInBits() == 64)
7704 // FIXME: pshufb, blends, shifts.
7705 return (VT.getVectorNumElements() == 2 ||
7706 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7707 isMOVLMask(M, VT) ||
7708 isSHUFPMask(M, VT) ||
7709 isPSHUFDMask(M, VT) ||
7710 isPSHUFHWMask(M, VT) ||
7711 isPSHUFLWMask(M, VT) ||
7712 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7713 isUNPCKLMask(M, VT) ||
7714 isUNPCKHMask(M, VT) ||
7715 isUNPCKL_v_undef_Mask(M, VT) ||
7716 isUNPCKH_v_undef_Mask(M, VT));
7720 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7722 unsigned NumElts = VT.getVectorNumElements();
7723 // FIXME: This collection of masks seems suspect.
7726 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7727 return (isMOVLMask(Mask, VT) ||
7728 isCommutedMOVLMask(Mask, VT, true) ||
7729 isSHUFPMask(Mask, VT) ||
7730 isCommutedSHUFPMask(Mask, VT));
7735 //===----------------------------------------------------------------------===//
7736 // X86 Scheduler Hooks
7737 //===----------------------------------------------------------------------===//
7739 // private utility function
7741 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7742 MachineBasicBlock *MBB,
7750 TargetRegisterClass *RC,
7751 bool invSrc) const {
7752 // For the atomic bitwise operator, we generate
7755 // ld t1 = [bitinstr.addr]
7756 // op t2 = t1, [bitinstr.val]
7758 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7760 // fallthrough -->nextMBB
7761 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7762 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7763 MachineFunction::iterator MBBIter = MBB;
7766 /// First build the CFG
7767 MachineFunction *F = MBB->getParent();
7768 MachineBasicBlock *thisMBB = MBB;
7769 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7770 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7771 F->insert(MBBIter, newMBB);
7772 F->insert(MBBIter, nextMBB);
7774 // Move all successors to thisMBB to nextMBB
7775 nextMBB->transferSuccessors(thisMBB);
7777 // Update thisMBB to fall through to newMBB
7778 thisMBB->addSuccessor(newMBB);
7780 // newMBB jumps to itself and fall through to nextMBB
7781 newMBB->addSuccessor(nextMBB);
7782 newMBB->addSuccessor(newMBB);
7784 // Insert instructions into newMBB based on incoming instruction
7785 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7786 "unexpected number of operands");
7787 DebugLoc dl = bInstr->getDebugLoc();
7788 MachineOperand& destOper = bInstr->getOperand(0);
7789 MachineOperand* argOpers[2 + X86AddrNumOperands];
7790 int numArgs = bInstr->getNumOperands() - 1;
7791 for (int i=0; i < numArgs; ++i)
7792 argOpers[i] = &bInstr->getOperand(i+1);
7794 // x86 address has 4 operands: base, index, scale, and displacement
7795 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7796 int valArgIndx = lastAddrIndx + 1;
7798 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7799 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7800 for (int i=0; i <= lastAddrIndx; ++i)
7801 (*MIB).addOperand(*argOpers[i]);
7803 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7805 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7810 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7811 assert((argOpers[valArgIndx]->isReg() ||
7812 argOpers[valArgIndx]->isImm()) &&
7814 if (argOpers[valArgIndx]->isReg())
7815 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7817 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7819 (*MIB).addOperand(*argOpers[valArgIndx]);
7821 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7824 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7825 for (int i=0; i <= lastAddrIndx; ++i)
7826 (*MIB).addOperand(*argOpers[i]);
7828 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7829 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7830 bInstr->memoperands_end());
7832 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7836 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7838 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7842 // private utility function: 64 bit atomics on 32 bit host.
7844 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7845 MachineBasicBlock *MBB,
7850 bool invSrc) const {
7851 // For the atomic bitwise operator, we generate
7852 // thisMBB (instructions are in pairs, except cmpxchg8b)
7853 // ld t1,t2 = [bitinstr.addr]
7855 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7856 // op t5, t6 <- out1, out2, [bitinstr.val]
7857 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7858 // mov ECX, EBX <- t5, t6
7859 // mov EAX, EDX <- t1, t2
7860 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7861 // mov t3, t4 <- EAX, EDX
7863 // result in out1, out2
7864 // fallthrough -->nextMBB
7866 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7867 const unsigned LoadOpc = X86::MOV32rm;
7868 const unsigned copyOpc = X86::MOV32rr;
7869 const unsigned NotOpc = X86::NOT32r;
7870 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7871 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7872 MachineFunction::iterator MBBIter = MBB;
7875 /// First build the CFG
7876 MachineFunction *F = MBB->getParent();
7877 MachineBasicBlock *thisMBB = MBB;
7878 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7879 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7880 F->insert(MBBIter, newMBB);
7881 F->insert(MBBIter, nextMBB);
7883 // Move all successors to thisMBB to nextMBB
7884 nextMBB->transferSuccessors(thisMBB);
7886 // Update thisMBB to fall through to newMBB
7887 thisMBB->addSuccessor(newMBB);
7889 // newMBB jumps to itself and fall through to nextMBB
7890 newMBB->addSuccessor(nextMBB);
7891 newMBB->addSuccessor(newMBB);
7893 DebugLoc dl = bInstr->getDebugLoc();
7894 // Insert instructions into newMBB based on incoming instruction
7895 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7896 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7897 "unexpected number of operands");
7898 MachineOperand& dest1Oper = bInstr->getOperand(0);
7899 MachineOperand& dest2Oper = bInstr->getOperand(1);
7900 MachineOperand* argOpers[2 + X86AddrNumOperands];
7901 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7902 argOpers[i] = &bInstr->getOperand(i+2);
7904 // x86 address has 5 operands: base, index, scale, displacement, and segment.
7905 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7907 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7908 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7909 for (int i=0; i <= lastAddrIndx; ++i)
7910 (*MIB).addOperand(*argOpers[i]);
7911 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7912 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7913 // add 4 to displacement.
7914 for (int i=0; i <= lastAddrIndx-2; ++i)
7915 (*MIB).addOperand(*argOpers[i]);
7916 MachineOperand newOp3 = *(argOpers[3]);
7918 newOp3.setImm(newOp3.getImm()+4);
7920 newOp3.setOffset(newOp3.getOffset()+4);
7921 (*MIB).addOperand(newOp3);
7922 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7924 // t3/4 are defined later, at the bottom of the loop
7925 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7926 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7927 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7928 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7929 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7930 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7932 // The subsequent operations should be using the destination registers of
7933 //the PHI instructions.
7935 t1 = F->getRegInfo().createVirtualRegister(RC);
7936 t2 = F->getRegInfo().createVirtualRegister(RC);
7937 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
7938 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
7940 t1 = dest1Oper.getReg();
7941 t2 = dest2Oper.getReg();
7944 int valArgIndx = lastAddrIndx + 1;
7945 assert((argOpers[valArgIndx]->isReg() ||
7946 argOpers[valArgIndx]->isImm()) &&
7948 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7949 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7950 if (argOpers[valArgIndx]->isReg())
7951 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7953 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7954 if (regOpcL != X86::MOV32rr)
7956 (*MIB).addOperand(*argOpers[valArgIndx]);
7957 assert(argOpers[valArgIndx + 1]->isReg() ==
7958 argOpers[valArgIndx]->isReg());
7959 assert(argOpers[valArgIndx + 1]->isImm() ==
7960 argOpers[valArgIndx]->isImm());
7961 if (argOpers[valArgIndx + 1]->isReg())
7962 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7964 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7965 if (regOpcH != X86::MOV32rr)
7967 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7969 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7971 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7974 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7976 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7979 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7980 for (int i=0; i <= lastAddrIndx; ++i)
7981 (*MIB).addOperand(*argOpers[i]);
7983 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7984 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7985 bInstr->memoperands_end());
7987 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7988 MIB.addReg(X86::EAX);
7989 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7990 MIB.addReg(X86::EDX);
7993 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7995 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7999 // private utility function
8001 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8002 MachineBasicBlock *MBB,
8003 unsigned cmovOpc) const {
8004 // For the atomic min/max operator, we generate
8007 // ld t1 = [min/max.addr]
8008 // mov t2 = [min/max.val]
8010 // cmov[cond] t2 = t1
8012 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
8014 // fallthrough -->nextMBB
8016 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8017 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8018 MachineFunction::iterator MBBIter = MBB;
8021 /// First build the CFG
8022 MachineFunction *F = MBB->getParent();
8023 MachineBasicBlock *thisMBB = MBB;
8024 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8025 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8026 F->insert(MBBIter, newMBB);
8027 F->insert(MBBIter, nextMBB);
8029 // Move all successors of thisMBB to nextMBB
8030 nextMBB->transferSuccessors(thisMBB);
8032 // Update thisMBB to fall through to newMBB
8033 thisMBB->addSuccessor(newMBB);
8035 // newMBB jumps to newMBB and fall through to nextMBB
8036 newMBB->addSuccessor(nextMBB);
8037 newMBB->addSuccessor(newMBB);
8039 DebugLoc dl = mInstr->getDebugLoc();
8040 // Insert instructions into newMBB based on incoming instruction
8041 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8042 "unexpected number of operands");
8043 MachineOperand& destOper = mInstr->getOperand(0);
8044 MachineOperand* argOpers[2 + X86AddrNumOperands];
8045 int numArgs = mInstr->getNumOperands() - 1;
8046 for (int i=0; i < numArgs; ++i)
8047 argOpers[i] = &mInstr->getOperand(i+1);
8049 // x86 address has 4 operands: base, index, scale, and displacement
8050 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8051 int valArgIndx = lastAddrIndx + 1;
8053 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8054 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8055 for (int i=0; i <= lastAddrIndx; ++i)
8056 (*MIB).addOperand(*argOpers[i]);
8058 // We only support register and immediate values
8059 assert((argOpers[valArgIndx]->isReg() ||
8060 argOpers[valArgIndx]->isImm()) &&
8063 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8064 if (argOpers[valArgIndx]->isReg())
8065 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8067 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8068 (*MIB).addOperand(*argOpers[valArgIndx]);
8070 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8073 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8078 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8079 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8083 // Cmp and exchange if none has modified the memory location
8084 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8085 for (int i=0; i <= lastAddrIndx; ++i)
8086 (*MIB).addOperand(*argOpers[i]);
8088 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8089 (*MIB).setMemRefs(mInstr->memoperands_begin(),
8090 mInstr->memoperands_end());
8092 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8093 MIB.addReg(X86::EAX);
8096 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
8098 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
8102 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8103 // all of this code can be replaced with that in the .td file.
8105 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8106 unsigned numArgs, bool memArg) const {
8108 MachineFunction *F = BB->getParent();
8109 DebugLoc dl = MI->getDebugLoc();
8110 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8114 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8116 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8118 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8120 for (unsigned i = 0; i < numArgs; ++i) {
8121 MachineOperand &Op = MI->getOperand(i+1);
8123 if (!(Op.isReg() && Op.isImplicit()))
8127 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8130 F->DeleteMachineInstr(MI);
8136 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8138 MachineBasicBlock *MBB) const {
8139 // Emit code to save XMM registers to the stack. The ABI says that the
8140 // number of registers to save is given in %al, so it's theoretically
8141 // possible to do an indirect jump trick to avoid saving all of them,
8142 // however this code takes a simpler approach and just executes all
8143 // of the stores if %al is non-zero. It's less code, and it's probably
8144 // easier on the hardware branch predictor, and stores aren't all that
8145 // expensive anyway.
8147 // Create the new basic blocks. One block contains all the XMM stores,
8148 // and one block is the final destination regardless of whether any
8149 // stores were performed.
8150 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8151 MachineFunction *F = MBB->getParent();
8152 MachineFunction::iterator MBBIter = MBB;
8154 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8155 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8156 F->insert(MBBIter, XMMSaveMBB);
8157 F->insert(MBBIter, EndMBB);
8160 // Move any original successors of MBB to the end block.
8161 EndMBB->transferSuccessors(MBB);
8162 // The original block will now fall through to the XMM save block.
8163 MBB->addSuccessor(XMMSaveMBB);
8164 // The XMMSaveMBB will fall through to the end block.
8165 XMMSaveMBB->addSuccessor(EndMBB);
8167 // Now add the instructions.
8168 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8169 DebugLoc DL = MI->getDebugLoc();
8171 unsigned CountReg = MI->getOperand(0).getReg();
8172 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8173 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8175 if (!Subtarget->isTargetWin64()) {
8176 // If %al is 0, branch around the XMM save block.
8177 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8178 BuildMI(MBB, DL, TII->get(X86::JE)).addMBB(EndMBB);
8179 MBB->addSuccessor(EndMBB);
8182 // In the XMM save block, save all the XMM argument registers.
8183 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8184 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8185 MachineMemOperand *MMO =
8186 F->getMachineMemOperand(
8187 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8188 MachineMemOperand::MOStore, Offset,
8189 /*Size=*/16, /*Align=*/16);
8190 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8191 .addFrameIndex(RegSaveFrameIndex)
8192 .addImm(/*Scale=*/1)
8193 .addReg(/*IndexReg=*/0)
8194 .addImm(/*Disp=*/Offset)
8195 .addReg(/*Segment=*/0)
8196 .addReg(MI->getOperand(i).getReg())
8197 .addMemOperand(MMO);
8200 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8206 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8207 MachineBasicBlock *BB,
8208 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8209 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8210 DebugLoc DL = MI->getDebugLoc();
8212 // To "insert" a SELECT_CC instruction, we actually have to insert the
8213 // diamond control-flow pattern. The incoming instruction knows the
8214 // destination vreg to set, the condition code register to branch on, the
8215 // true/false values to select between, and a branch opcode to use.
8216 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8217 MachineFunction::iterator It = BB;
8223 // cmpTY ccX, r1, r2
8225 // fallthrough --> copy0MBB
8226 MachineBasicBlock *thisMBB = BB;
8227 MachineFunction *F = BB->getParent();
8228 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8229 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8231 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8232 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8233 F->insert(It, copy0MBB);
8234 F->insert(It, sinkMBB);
8235 // Update machine-CFG edges by first adding all successors of the current
8236 // block to the new block which will contain the Phi node for the select.
8237 // Also inform sdisel of the edge changes.
8238 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8239 E = BB->succ_end(); I != E; ++I) {
8240 EM->insert(std::make_pair(*I, sinkMBB));
8241 sinkMBB->addSuccessor(*I);
8243 // Next, remove all successors of the current block, and add the true
8244 // and fallthrough blocks as its successors.
8245 while (!BB->succ_empty())
8246 BB->removeSuccessor(BB->succ_begin());
8247 // Add the true and fallthrough blocks as its successors.
8248 BB->addSuccessor(copy0MBB);
8249 BB->addSuccessor(sinkMBB);
8252 // %FalseValue = ...
8253 // # fallthrough to sinkMBB
8256 // Update machine-CFG edges
8257 BB->addSuccessor(sinkMBB);
8260 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8263 BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8264 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8265 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8267 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8273 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8274 MachineBasicBlock *BB,
8275 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8276 switch (MI->getOpcode()) {
8277 default: assert(false && "Unexpected instr type to insert");
8279 case X86::CMOV_V1I64:
8280 case X86::CMOV_FR32:
8281 case X86::CMOV_FR64:
8282 case X86::CMOV_V4F32:
8283 case X86::CMOV_V2F64:
8284 case X86::CMOV_V2I64:
8285 return EmitLoweredSelect(MI, BB, EM);
8287 case X86::FP32_TO_INT16_IN_MEM:
8288 case X86::FP32_TO_INT32_IN_MEM:
8289 case X86::FP32_TO_INT64_IN_MEM:
8290 case X86::FP64_TO_INT16_IN_MEM:
8291 case X86::FP64_TO_INT32_IN_MEM:
8292 case X86::FP64_TO_INT64_IN_MEM:
8293 case X86::FP80_TO_INT16_IN_MEM:
8294 case X86::FP80_TO_INT32_IN_MEM:
8295 case X86::FP80_TO_INT64_IN_MEM: {
8296 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8297 DebugLoc DL = MI->getDebugLoc();
8299 // Change the floating point control register to use "round towards zero"
8300 // mode when truncating to an integer value.
8301 MachineFunction *F = BB->getParent();
8302 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8303 addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8305 // Load the old value of the high byte of the control word...
8307 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8308 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8311 // Set the high part to be round to zero...
8312 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8315 // Reload the modified control word now...
8316 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8318 // Restore the memory image of control word to original value
8319 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8322 // Get the X86 opcode to use.
8324 switch (MI->getOpcode()) {
8325 default: llvm_unreachable("illegal opcode!");
8326 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8327 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8328 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8329 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8330 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8331 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8332 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8333 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8334 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8338 MachineOperand &Op = MI->getOperand(0);
8340 AM.BaseType = X86AddressMode::RegBase;
8341 AM.Base.Reg = Op.getReg();
8343 AM.BaseType = X86AddressMode::FrameIndexBase;
8344 AM.Base.FrameIndex = Op.getIndex();
8346 Op = MI->getOperand(1);
8348 AM.Scale = Op.getImm();
8349 Op = MI->getOperand(2);
8351 AM.IndexReg = Op.getImm();
8352 Op = MI->getOperand(3);
8353 if (Op.isGlobal()) {
8354 AM.GV = Op.getGlobal();
8356 AM.Disp = Op.getImm();
8358 addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8359 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8361 // Reload the original control word now.
8362 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8364 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8367 // String/text processing lowering.
8368 case X86::PCMPISTRM128REG:
8369 return EmitPCMP(MI, BB, 3, false /* in-mem */);
8370 case X86::PCMPISTRM128MEM:
8371 return EmitPCMP(MI, BB, 3, true /* in-mem */);
8372 case X86::PCMPESTRM128REG:
8373 return EmitPCMP(MI, BB, 5, false /* in mem */);
8374 case X86::PCMPESTRM128MEM:
8375 return EmitPCMP(MI, BB, 5, true /* in mem */);
8378 case X86::ATOMAND32:
8379 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8380 X86::AND32ri, X86::MOV32rm,
8381 X86::LCMPXCHG32, X86::MOV32rr,
8382 X86::NOT32r, X86::EAX,
8383 X86::GR32RegisterClass);
8385 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8386 X86::OR32ri, X86::MOV32rm,
8387 X86::LCMPXCHG32, X86::MOV32rr,
8388 X86::NOT32r, X86::EAX,
8389 X86::GR32RegisterClass);
8390 case X86::ATOMXOR32:
8391 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8392 X86::XOR32ri, X86::MOV32rm,
8393 X86::LCMPXCHG32, X86::MOV32rr,
8394 X86::NOT32r, X86::EAX,
8395 X86::GR32RegisterClass);
8396 case X86::ATOMNAND32:
8397 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8398 X86::AND32ri, X86::MOV32rm,
8399 X86::LCMPXCHG32, X86::MOV32rr,
8400 X86::NOT32r, X86::EAX,
8401 X86::GR32RegisterClass, true);
8402 case X86::ATOMMIN32:
8403 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8404 case X86::ATOMMAX32:
8405 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8406 case X86::ATOMUMIN32:
8407 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8408 case X86::ATOMUMAX32:
8409 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8411 case X86::ATOMAND16:
8412 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8413 X86::AND16ri, X86::MOV16rm,
8414 X86::LCMPXCHG16, X86::MOV16rr,
8415 X86::NOT16r, X86::AX,
8416 X86::GR16RegisterClass);
8418 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8419 X86::OR16ri, X86::MOV16rm,
8420 X86::LCMPXCHG16, X86::MOV16rr,
8421 X86::NOT16r, X86::AX,
8422 X86::GR16RegisterClass);
8423 case X86::ATOMXOR16:
8424 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8425 X86::XOR16ri, X86::MOV16rm,
8426 X86::LCMPXCHG16, X86::MOV16rr,
8427 X86::NOT16r, X86::AX,
8428 X86::GR16RegisterClass);
8429 case X86::ATOMNAND16:
8430 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8431 X86::AND16ri, X86::MOV16rm,
8432 X86::LCMPXCHG16, X86::MOV16rr,
8433 X86::NOT16r, X86::AX,
8434 X86::GR16RegisterClass, true);
8435 case X86::ATOMMIN16:
8436 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8437 case X86::ATOMMAX16:
8438 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8439 case X86::ATOMUMIN16:
8440 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8441 case X86::ATOMUMAX16:
8442 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8445 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8446 X86::AND8ri, X86::MOV8rm,
8447 X86::LCMPXCHG8, X86::MOV8rr,
8448 X86::NOT8r, X86::AL,
8449 X86::GR8RegisterClass);
8451 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8452 X86::OR8ri, X86::MOV8rm,
8453 X86::LCMPXCHG8, X86::MOV8rr,
8454 X86::NOT8r, X86::AL,
8455 X86::GR8RegisterClass);
8457 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8458 X86::XOR8ri, X86::MOV8rm,
8459 X86::LCMPXCHG8, X86::MOV8rr,
8460 X86::NOT8r, X86::AL,
8461 X86::GR8RegisterClass);
8462 case X86::ATOMNAND8:
8463 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8464 X86::AND8ri, X86::MOV8rm,
8465 X86::LCMPXCHG8, X86::MOV8rr,
8466 X86::NOT8r, X86::AL,
8467 X86::GR8RegisterClass, true);
8468 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8469 // This group is for 64-bit host.
8470 case X86::ATOMAND64:
8471 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8472 X86::AND64ri32, X86::MOV64rm,
8473 X86::LCMPXCHG64, X86::MOV64rr,
8474 X86::NOT64r, X86::RAX,
8475 X86::GR64RegisterClass);
8477 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8478 X86::OR64ri32, X86::MOV64rm,
8479 X86::LCMPXCHG64, X86::MOV64rr,
8480 X86::NOT64r, X86::RAX,
8481 X86::GR64RegisterClass);
8482 case X86::ATOMXOR64:
8483 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8484 X86::XOR64ri32, X86::MOV64rm,
8485 X86::LCMPXCHG64, X86::MOV64rr,
8486 X86::NOT64r, X86::RAX,
8487 X86::GR64RegisterClass);
8488 case X86::ATOMNAND64:
8489 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8490 X86::AND64ri32, X86::MOV64rm,
8491 X86::LCMPXCHG64, X86::MOV64rr,
8492 X86::NOT64r, X86::RAX,
8493 X86::GR64RegisterClass, true);
8494 case X86::ATOMMIN64:
8495 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8496 case X86::ATOMMAX64:
8497 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8498 case X86::ATOMUMIN64:
8499 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8500 case X86::ATOMUMAX64:
8501 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8503 // This group does 64-bit operations on a 32-bit host.
8504 case X86::ATOMAND6432:
8505 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8506 X86::AND32rr, X86::AND32rr,
8507 X86::AND32ri, X86::AND32ri,
8509 case X86::ATOMOR6432:
8510 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8511 X86::OR32rr, X86::OR32rr,
8512 X86::OR32ri, X86::OR32ri,
8514 case X86::ATOMXOR6432:
8515 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8516 X86::XOR32rr, X86::XOR32rr,
8517 X86::XOR32ri, X86::XOR32ri,
8519 case X86::ATOMNAND6432:
8520 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8521 X86::AND32rr, X86::AND32rr,
8522 X86::AND32ri, X86::AND32ri,
8524 case X86::ATOMADD6432:
8525 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8526 X86::ADD32rr, X86::ADC32rr,
8527 X86::ADD32ri, X86::ADC32ri,
8529 case X86::ATOMSUB6432:
8530 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8531 X86::SUB32rr, X86::SBB32rr,
8532 X86::SUB32ri, X86::SBB32ri,
8534 case X86::ATOMSWAP6432:
8535 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8536 X86::MOV32rr, X86::MOV32rr,
8537 X86::MOV32ri, X86::MOV32ri,
8539 case X86::VASTART_SAVE_XMM_REGS:
8540 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8544 //===----------------------------------------------------------------------===//
8545 // X86 Optimization Hooks
8546 //===----------------------------------------------------------------------===//
8548 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8552 const SelectionDAG &DAG,
8553 unsigned Depth) const {
8554 unsigned Opc = Op.getOpcode();
8555 assert((Opc >= ISD::BUILTIN_OP_END ||
8556 Opc == ISD::INTRINSIC_WO_CHAIN ||
8557 Opc == ISD::INTRINSIC_W_CHAIN ||
8558 Opc == ISD::INTRINSIC_VOID) &&
8559 "Should use MaskedValueIsZero if you don't know whether Op"
8560 " is a target node!");
8562 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
8574 // These nodes' second result is a boolean.
8575 if (Op.getResNo() == 0)
8579 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8580 Mask.getBitWidth() - 1);
8585 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8586 /// node is a GlobalAddress + offset.
8587 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8588 GlobalValue* &GA, int64_t &Offset) const{
8589 if (N->getOpcode() == X86ISD::Wrapper) {
8590 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8591 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8592 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8596 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8599 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
8600 EVT EltVT, LoadSDNode *&LDBase,
8601 unsigned &LastLoadedElt,
8602 SelectionDAG &DAG, MachineFrameInfo *MFI,
8603 const TargetLowering &TLI) {
8605 LastLoadedElt = -1U;
8606 for (unsigned i = 0; i < NumElems; ++i) {
8607 if (N->getMaskElt(i) < 0) {
8613 SDValue Elt = DAG.getShuffleScalarElt(N, i);
8614 if (!Elt.getNode() ||
8615 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8618 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
8620 LDBase = cast<LoadSDNode>(Elt.getNode());
8624 if (Elt.getOpcode() == ISD::UNDEF)
8627 LoadSDNode *LD = cast<LoadSDNode>(Elt);
8628 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
8635 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8636 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8637 /// if the load addresses are consecutive, non-overlapping, and in the right
8638 /// order. In the case of v2i64, it will see if it can rewrite the
8639 /// shuffle to be an appropriate build vector so it can take advantage of
8640 // performBuildVectorCombine.
8641 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8642 const TargetLowering &TLI) {
8643 DebugLoc dl = N->getDebugLoc();
8644 EVT VT = N->getValueType(0);
8645 EVT EltVT = VT.getVectorElementType();
8646 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8647 unsigned NumElems = VT.getVectorNumElements();
8649 if (VT.getSizeInBits() != 128)
8652 // Try to combine a vector_shuffle into a 128-bit load.
8653 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8654 LoadSDNode *LD = NULL;
8655 unsigned LastLoadedElt;
8656 if (!EltsFromConsecutiveLoads(SVN, NumElems, EltVT, LD, LastLoadedElt, DAG,
8660 if (LastLoadedElt == NumElems - 1) {
8661 if (DAG.InferPtrAlignment(LD->getBasePtr()) >= 16)
8662 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8663 LD->getSrcValue(), LD->getSrcValueOffset(),
8665 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8666 LD->getSrcValue(), LD->getSrcValueOffset(),
8667 LD->isVolatile(), LD->getAlignment());
8668 } else if (NumElems == 4 && LastLoadedElt == 1) {
8669 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
8670 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8671 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8672 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
8677 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8678 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8679 const X86Subtarget *Subtarget) {
8680 DebugLoc DL = N->getDebugLoc();
8681 SDValue Cond = N->getOperand(0);
8682 // Get the LHS/RHS of the select.
8683 SDValue LHS = N->getOperand(1);
8684 SDValue RHS = N->getOperand(2);
8686 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8687 // instructions have the peculiarity that if either operand is a NaN,
8688 // they chose what we call the RHS operand (and as such are not symmetric).
8689 // It happens that this matches the semantics of the common C idiom
8690 // x<y?x:y and related forms, so we can recognize these cases.
8691 if (Subtarget->hasSSE2() &&
8692 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8693 Cond.getOpcode() == ISD::SETCC) {
8694 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8696 unsigned Opcode = 0;
8697 // Check for x CC y ? x : y.
8698 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8702 // This can be a min if we can prove that at least one of the operands
8704 if (!FiniteOnlyFPMath()) {
8705 if (DAG.isKnownNeverNaN(RHS)) {
8706 // Put the potential NaN in the RHS so that SSE will preserve it.
8707 std::swap(LHS, RHS);
8708 } else if (!DAG.isKnownNeverNaN(LHS))
8711 Opcode = X86ISD::FMIN;
8714 // This can be a min if we can prove that at least one of the operands
8716 if (!FiniteOnlyFPMath()) {
8717 if (DAG.isKnownNeverNaN(LHS)) {
8718 // Put the potential NaN in the RHS so that SSE will preserve it.
8719 std::swap(LHS, RHS);
8720 } else if (!DAG.isKnownNeverNaN(RHS))
8723 Opcode = X86ISD::FMIN;
8726 // This can be a min, but if either operand is a NaN we need it to
8727 // preserve the original LHS.
8728 std::swap(LHS, RHS);
8732 Opcode = X86ISD::FMIN;
8736 // This can be a max if we can prove that at least one of the operands
8738 if (!FiniteOnlyFPMath()) {
8739 if (DAG.isKnownNeverNaN(LHS)) {
8740 // Put the potential NaN in the RHS so that SSE will preserve it.
8741 std::swap(LHS, RHS);
8742 } else if (!DAG.isKnownNeverNaN(RHS))
8745 Opcode = X86ISD::FMAX;
8748 // This can be a max if we can prove that at least one of the operands
8750 if (!FiniteOnlyFPMath()) {
8751 if (DAG.isKnownNeverNaN(RHS)) {
8752 // Put the potential NaN in the RHS so that SSE will preserve it.
8753 std::swap(LHS, RHS);
8754 } else if (!DAG.isKnownNeverNaN(LHS))
8757 Opcode = X86ISD::FMAX;
8760 // This can be a max, but if either operand is a NaN we need it to
8761 // preserve the original LHS.
8762 std::swap(LHS, RHS);
8766 Opcode = X86ISD::FMAX;
8769 // Check for x CC y ? y : x -- a min/max with reversed arms.
8770 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8774 // This can be a min if we can prove that at least one of the operands
8776 if (!FiniteOnlyFPMath()) {
8777 if (DAG.isKnownNeverNaN(RHS)) {
8778 // Put the potential NaN in the RHS so that SSE will preserve it.
8779 std::swap(LHS, RHS);
8780 } else if (!DAG.isKnownNeverNaN(LHS))
8783 Opcode = X86ISD::FMIN;
8786 // This can be a min if we can prove that at least one of the operands
8788 if (!FiniteOnlyFPMath()) {
8789 if (DAG.isKnownNeverNaN(LHS)) {
8790 // Put the potential NaN in the RHS so that SSE will preserve it.
8791 std::swap(LHS, RHS);
8792 } else if (!DAG.isKnownNeverNaN(RHS))
8795 Opcode = X86ISD::FMIN;
8798 // This can be a min, but if either operand is a NaN we need it to
8799 // preserve the original LHS.
8800 std::swap(LHS, RHS);
8804 Opcode = X86ISD::FMIN;
8808 // This can be a max if we can prove that at least one of the operands
8810 if (!FiniteOnlyFPMath()) {
8811 if (DAG.isKnownNeverNaN(LHS)) {
8812 // Put the potential NaN in the RHS so that SSE will preserve it.
8813 std::swap(LHS, RHS);
8814 } else if (!DAG.isKnownNeverNaN(RHS))
8817 Opcode = X86ISD::FMAX;
8820 // This can be a max if we can prove that at least one of the operands
8822 if (!FiniteOnlyFPMath()) {
8823 if (DAG.isKnownNeverNaN(RHS)) {
8824 // Put the potential NaN in the RHS so that SSE will preserve it.
8825 std::swap(LHS, RHS);
8826 } else if (!DAG.isKnownNeverNaN(LHS))
8829 Opcode = X86ISD::FMAX;
8832 // This can be a max, but if either operand is a NaN we need it to
8833 // preserve the original LHS.
8834 std::swap(LHS, RHS);
8838 Opcode = X86ISD::FMAX;
8844 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8847 // If this is a select between two integer constants, try to do some
8849 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8850 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8851 // Don't do this for crazy integer types.
8852 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8853 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8854 // so that TrueC (the true value) is larger than FalseC.
8855 bool NeedsCondInvert = false;
8857 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8858 // Efficiently invertible.
8859 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
8860 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
8861 isa<ConstantSDNode>(Cond.getOperand(1))))) {
8862 NeedsCondInvert = true;
8863 std::swap(TrueC, FalseC);
8866 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
8867 if (FalseC->getAPIntValue() == 0 &&
8868 TrueC->getAPIntValue().isPowerOf2()) {
8869 if (NeedsCondInvert) // Invert the condition if needed.
8870 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8871 DAG.getConstant(1, Cond.getValueType()));
8873 // Zero extend the condition if needed.
8874 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8876 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8877 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8878 DAG.getConstant(ShAmt, MVT::i8));
8881 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8882 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8883 if (NeedsCondInvert) // Invert the condition if needed.
8884 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8885 DAG.getConstant(1, Cond.getValueType()));
8887 // Zero extend the condition if needed.
8888 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8889 FalseC->getValueType(0), Cond);
8890 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8891 SDValue(FalseC, 0));
8894 // Optimize cases that will turn into an LEA instruction. This requires
8895 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8896 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8897 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8898 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8900 bool isFastMultiplier = false;
8902 switch ((unsigned char)Diff) {
8904 case 1: // result = add base, cond
8905 case 2: // result = lea base( , cond*2)
8906 case 3: // result = lea base(cond, cond*2)
8907 case 4: // result = lea base( , cond*4)
8908 case 5: // result = lea base(cond, cond*4)
8909 case 8: // result = lea base( , cond*8)
8910 case 9: // result = lea base(cond, cond*8)
8911 isFastMultiplier = true;
8916 if (isFastMultiplier) {
8917 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8918 if (NeedsCondInvert) // Invert the condition if needed.
8919 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8920 DAG.getConstant(1, Cond.getValueType()));
8922 // Zero extend the condition if needed.
8923 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8925 // Scale the condition by the difference.
8927 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8928 DAG.getConstant(Diff, Cond.getValueType()));
8930 // Add the base if non-zero.
8931 if (FalseC->getAPIntValue() != 0)
8932 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8933 SDValue(FalseC, 0));
8943 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8944 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8945 TargetLowering::DAGCombinerInfo &DCI) {
8946 DebugLoc DL = N->getDebugLoc();
8948 // If the flag operand isn't dead, don't touch this CMOV.
8949 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8952 // If this is a select between two integer constants, try to do some
8953 // optimizations. Note that the operands are ordered the opposite of SELECT
8955 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8956 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8957 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8958 // larger than FalseC (the false value).
8959 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8961 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8962 CC = X86::GetOppositeBranchCondition(CC);
8963 std::swap(TrueC, FalseC);
8966 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
8967 // This is efficient for any integer data type (including i8/i16) and
8969 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8970 SDValue Cond = N->getOperand(3);
8971 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8972 DAG.getConstant(CC, MVT::i8), Cond);
8974 // Zero extend the condition if needed.
8975 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8977 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8978 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8979 DAG.getConstant(ShAmt, MVT::i8));
8980 if (N->getNumValues() == 2) // Dead flag value?
8981 return DCI.CombineTo(N, Cond, SDValue());
8985 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
8986 // for any integer data type, including i8/i16.
8987 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8988 SDValue Cond = N->getOperand(3);
8989 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8990 DAG.getConstant(CC, MVT::i8), Cond);
8992 // Zero extend the condition if needed.
8993 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8994 FalseC->getValueType(0), Cond);
8995 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8996 SDValue(FalseC, 0));
8998 if (N->getNumValues() == 2) // Dead flag value?
8999 return DCI.CombineTo(N, Cond, SDValue());
9003 // Optimize cases that will turn into an LEA instruction. This requires
9004 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9005 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9006 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9007 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9009 bool isFastMultiplier = false;
9011 switch ((unsigned char)Diff) {
9013 case 1: // result = add base, cond
9014 case 2: // result = lea base( , cond*2)
9015 case 3: // result = lea base(cond, cond*2)
9016 case 4: // result = lea base( , cond*4)
9017 case 5: // result = lea base(cond, cond*4)
9018 case 8: // result = lea base( , cond*8)
9019 case 9: // result = lea base(cond, cond*8)
9020 isFastMultiplier = true;
9025 if (isFastMultiplier) {
9026 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9027 SDValue Cond = N->getOperand(3);
9028 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9029 DAG.getConstant(CC, MVT::i8), Cond);
9030 // Zero extend the condition if needed.
9031 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9033 // Scale the condition by the difference.
9035 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9036 DAG.getConstant(Diff, Cond.getValueType()));
9038 // Add the base if non-zero.
9039 if (FalseC->getAPIntValue() != 0)
9040 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9041 SDValue(FalseC, 0));
9042 if (N->getNumValues() == 2) // Dead flag value?
9043 return DCI.CombineTo(N, Cond, SDValue());
9053 /// PerformMulCombine - Optimize a single multiply with constant into two
9054 /// in order to implement it with two cheaper instructions, e.g.
9055 /// LEA + SHL, LEA + LEA.
9056 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9057 TargetLowering::DAGCombinerInfo &DCI) {
9058 if (DAG.getMachineFunction().
9059 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
9062 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9065 EVT VT = N->getValueType(0);
9069 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9072 uint64_t MulAmt = C->getZExtValue();
9073 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9076 uint64_t MulAmt1 = 0;
9077 uint64_t MulAmt2 = 0;
9078 if ((MulAmt % 9) == 0) {
9080 MulAmt2 = MulAmt / 9;
9081 } else if ((MulAmt % 5) == 0) {
9083 MulAmt2 = MulAmt / 5;
9084 } else if ((MulAmt % 3) == 0) {
9086 MulAmt2 = MulAmt / 3;
9089 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9090 DebugLoc DL = N->getDebugLoc();
9092 if (isPowerOf2_64(MulAmt2) &&
9093 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9094 // If second multiplifer is pow2, issue it first. We want the multiply by
9095 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9097 std::swap(MulAmt1, MulAmt2);
9100 if (isPowerOf2_64(MulAmt1))
9101 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9102 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9104 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9105 DAG.getConstant(MulAmt1, VT));
9107 if (isPowerOf2_64(MulAmt2))
9108 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9109 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9111 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9112 DAG.getConstant(MulAmt2, VT));
9114 // Do not add new nodes to DAG combiner worklist.
9115 DCI.CombineTo(N, NewMul, false);
9120 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9121 SDValue N0 = N->getOperand(0);
9122 SDValue N1 = N->getOperand(1);
9123 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9124 EVT VT = N0.getValueType();
9126 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9127 // since the result of setcc_c is all zero's or all ones.
9128 if (N1C && N0.getOpcode() == ISD::AND &&
9129 N0.getOperand(1).getOpcode() == ISD::Constant) {
9130 SDValue N00 = N0.getOperand(0);
9131 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9132 ((N00.getOpcode() == ISD::ANY_EXTEND ||
9133 N00.getOpcode() == ISD::ZERO_EXTEND) &&
9134 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9135 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9136 APInt ShAmt = N1C->getAPIntValue();
9137 Mask = Mask.shl(ShAmt);
9139 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9140 N00, DAG.getConstant(Mask, VT));
9147 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9149 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9150 const X86Subtarget *Subtarget) {
9151 EVT VT = N->getValueType(0);
9152 if (!VT.isVector() && VT.isInteger() &&
9153 N->getOpcode() == ISD::SHL)
9154 return PerformSHLCombine(N, DAG);
9156 // On X86 with SSE2 support, we can transform this to a vector shift if
9157 // all elements are shifted by the same amount. We can't do this in legalize
9158 // because the a constant vector is typically transformed to a constant pool
9159 // so we have no knowledge of the shift amount.
9160 if (!Subtarget->hasSSE2())
9163 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9166 SDValue ShAmtOp = N->getOperand(1);
9167 EVT EltVT = VT.getVectorElementType();
9168 DebugLoc DL = N->getDebugLoc();
9169 SDValue BaseShAmt = SDValue();
9170 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9171 unsigned NumElts = VT.getVectorNumElements();
9173 for (; i != NumElts; ++i) {
9174 SDValue Arg = ShAmtOp.getOperand(i);
9175 if (Arg.getOpcode() == ISD::UNDEF) continue;
9179 for (; i != NumElts; ++i) {
9180 SDValue Arg = ShAmtOp.getOperand(i);
9181 if (Arg.getOpcode() == ISD::UNDEF) continue;
9182 if (Arg != BaseShAmt) {
9186 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9187 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9188 SDValue InVec = ShAmtOp.getOperand(0);
9189 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9190 unsigned NumElts = InVec.getValueType().getVectorNumElements();
9192 for (; i != NumElts; ++i) {
9193 SDValue Arg = InVec.getOperand(i);
9194 if (Arg.getOpcode() == ISD::UNDEF) continue;
9198 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9199 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9200 unsigned SplatIdx = cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9201 if (C->getZExtValue() == SplatIdx)
9202 BaseShAmt = InVec.getOperand(1);
9205 if (BaseShAmt.getNode() == 0)
9206 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9207 DAG.getIntPtrConstant(0));
9211 // The shift amount is an i32.
9212 if (EltVT.bitsGT(MVT::i32))
9213 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9214 else if (EltVT.bitsLT(MVT::i32))
9215 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9217 // The shift amount is identical so we can do a vector shift.
9218 SDValue ValOp = N->getOperand(0);
9219 switch (N->getOpcode()) {
9221 llvm_unreachable("Unknown shift opcode!");
9224 if (VT == MVT::v2i64)
9225 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9226 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9228 if (VT == MVT::v4i32)
9229 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9230 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9232 if (VT == MVT::v8i16)
9233 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9234 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9238 if (VT == MVT::v4i32)
9239 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9240 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9242 if (VT == MVT::v8i16)
9243 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9244 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9248 if (VT == MVT::v2i64)
9249 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9250 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9252 if (VT == MVT::v4i32)
9253 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9254 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9256 if (VT == MVT::v8i16)
9257 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9258 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9265 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9266 const X86Subtarget *Subtarget) {
9267 EVT VT = N->getValueType(0);
9268 if (VT != MVT::i64 || !Subtarget->is64Bit())
9271 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9272 SDValue N0 = N->getOperand(0);
9273 SDValue N1 = N->getOperand(1);
9274 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9276 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9279 SDValue ShAmt0 = N0.getOperand(1);
9280 if (ShAmt0.getValueType() != MVT::i8)
9282 SDValue ShAmt1 = N1.getOperand(1);
9283 if (ShAmt1.getValueType() != MVT::i8)
9285 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9286 ShAmt0 = ShAmt0.getOperand(0);
9287 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9288 ShAmt1 = ShAmt1.getOperand(0);
9290 DebugLoc DL = N->getDebugLoc();
9291 unsigned Opc = X86ISD::SHLD;
9292 SDValue Op0 = N0.getOperand(0);
9293 SDValue Op1 = N1.getOperand(0);
9294 if (ShAmt0.getOpcode() == ISD::SUB) {
9296 std::swap(Op0, Op1);
9297 std::swap(ShAmt0, ShAmt1);
9300 if (ShAmt1.getOpcode() == ISD::SUB) {
9301 SDValue Sum = ShAmt1.getOperand(0);
9302 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9303 if (SumC->getSExtValue() == 64 &&
9304 ShAmt1.getOperand(1) == ShAmt0)
9305 return DAG.getNode(Opc, DL, VT,
9307 DAG.getNode(ISD::TRUNCATE, DL,
9310 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9311 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9313 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == 64)
9314 return DAG.getNode(Opc, DL, VT,
9315 N0.getOperand(0), N1.getOperand(0),
9316 DAG.getNode(ISD::TRUNCATE, DL,
9323 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9324 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9325 const X86Subtarget *Subtarget) {
9326 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
9327 // the FP state in cases where an emms may be missing.
9328 // A preferable solution to the general problem is to figure out the right
9329 // places to insert EMMS. This qualifies as a quick hack.
9331 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9332 StoreSDNode *St = cast<StoreSDNode>(N);
9333 EVT VT = St->getValue().getValueType();
9334 if (VT.getSizeInBits() != 64)
9337 const Function *F = DAG.getMachineFunction().getFunction();
9338 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9339 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9340 && Subtarget->hasSSE2();
9341 if ((VT.isVector() ||
9342 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9343 isa<LoadSDNode>(St->getValue()) &&
9344 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9345 St->getChain().hasOneUse() && !St->isVolatile()) {
9346 SDNode* LdVal = St->getValue().getNode();
9348 int TokenFactorIndex = -1;
9349 SmallVector<SDValue, 8> Ops;
9350 SDNode* ChainVal = St->getChain().getNode();
9351 // Must be a store of a load. We currently handle two cases: the load
9352 // is a direct child, and it's under an intervening TokenFactor. It is
9353 // possible to dig deeper under nested TokenFactors.
9354 if (ChainVal == LdVal)
9355 Ld = cast<LoadSDNode>(St->getChain());
9356 else if (St->getValue().hasOneUse() &&
9357 ChainVal->getOpcode() == ISD::TokenFactor) {
9358 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9359 if (ChainVal->getOperand(i).getNode() == LdVal) {
9360 TokenFactorIndex = i;
9361 Ld = cast<LoadSDNode>(St->getValue());
9363 Ops.push_back(ChainVal->getOperand(i));
9367 if (!Ld || !ISD::isNormalLoad(Ld))
9370 // If this is not the MMX case, i.e. we are just turning i64 load/store
9371 // into f64 load/store, avoid the transformation if there are multiple
9372 // uses of the loaded value.
9373 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9376 DebugLoc LdDL = Ld->getDebugLoc();
9377 DebugLoc StDL = N->getDebugLoc();
9378 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9379 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9381 if (Subtarget->is64Bit() || F64IsLegal) {
9382 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9383 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9384 Ld->getBasePtr(), Ld->getSrcValue(),
9385 Ld->getSrcValueOffset(), Ld->isVolatile(),
9386 Ld->getAlignment());
9387 SDValue NewChain = NewLd.getValue(1);
9388 if (TokenFactorIndex != -1) {
9389 Ops.push_back(NewChain);
9390 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9393 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9394 St->getSrcValue(), St->getSrcValueOffset(),
9395 St->isVolatile(), St->getAlignment());
9398 // Otherwise, lower to two pairs of 32-bit loads / stores.
9399 SDValue LoAddr = Ld->getBasePtr();
9400 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9401 DAG.getConstant(4, MVT::i32));
9403 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9404 Ld->getSrcValue(), Ld->getSrcValueOffset(),
9405 Ld->isVolatile(), Ld->getAlignment());
9406 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9407 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9409 MinAlign(Ld->getAlignment(), 4));
9411 SDValue NewChain = LoLd.getValue(1);
9412 if (TokenFactorIndex != -1) {
9413 Ops.push_back(LoLd);
9414 Ops.push_back(HiLd);
9415 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9419 LoAddr = St->getBasePtr();
9420 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9421 DAG.getConstant(4, MVT::i32));
9423 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9424 St->getSrcValue(), St->getSrcValueOffset(),
9425 St->isVolatile(), St->getAlignment());
9426 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9428 St->getSrcValueOffset() + 4,
9430 MinAlign(St->getAlignment(), 4));
9431 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9436 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9437 /// X86ISD::FXOR nodes.
9438 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9439 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9440 // F[X]OR(0.0, x) -> x
9441 // F[X]OR(x, 0.0) -> x
9442 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9443 if (C->getValueAPF().isPosZero())
9444 return N->getOperand(1);
9445 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9446 if (C->getValueAPF().isPosZero())
9447 return N->getOperand(0);
9451 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9452 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9453 // FAND(0.0, x) -> 0.0
9454 // FAND(x, 0.0) -> 0.0
9455 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9456 if (C->getValueAPF().isPosZero())
9457 return N->getOperand(0);
9458 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9459 if (C->getValueAPF().isPosZero())
9460 return N->getOperand(1);
9464 static SDValue PerformBTCombine(SDNode *N,
9466 TargetLowering::DAGCombinerInfo &DCI) {
9467 // BT ignores high bits in the bit index operand.
9468 SDValue Op1 = N->getOperand(1);
9469 if (Op1.hasOneUse()) {
9470 unsigned BitWidth = Op1.getValueSizeInBits();
9471 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9472 APInt KnownZero, KnownOne;
9473 TargetLowering::TargetLoweringOpt TLO(DAG);
9474 TargetLowering &TLI = DAG.getTargetLoweringInfo();
9475 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9476 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9477 DCI.CommitTargetLoweringOpt(TLO);
9482 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9483 SDValue Op = N->getOperand(0);
9484 if (Op.getOpcode() == ISD::BIT_CONVERT)
9485 Op = Op.getOperand(0);
9486 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9487 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9488 VT.getVectorElementType().getSizeInBits() ==
9489 OpVT.getVectorElementType().getSizeInBits()) {
9490 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9495 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9496 // Locked instructions, in turn, have implicit fence semantics (all memory
9497 // operations are flushed before issuing the locked instruction, and the
9498 // are not buffered), so we can fold away the common pattern of
9499 // fence-atomic-fence.
9500 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9501 SDValue atomic = N->getOperand(0);
9502 switch (atomic.getOpcode()) {
9503 case ISD::ATOMIC_CMP_SWAP:
9504 case ISD::ATOMIC_SWAP:
9505 case ISD::ATOMIC_LOAD_ADD:
9506 case ISD::ATOMIC_LOAD_SUB:
9507 case ISD::ATOMIC_LOAD_AND:
9508 case ISD::ATOMIC_LOAD_OR:
9509 case ISD::ATOMIC_LOAD_XOR:
9510 case ISD::ATOMIC_LOAD_NAND:
9511 case ISD::ATOMIC_LOAD_MIN:
9512 case ISD::ATOMIC_LOAD_MAX:
9513 case ISD::ATOMIC_LOAD_UMIN:
9514 case ISD::ATOMIC_LOAD_UMAX:
9520 SDValue fence = atomic.getOperand(0);
9521 if (fence.getOpcode() != ISD::MEMBARRIER)
9524 switch (atomic.getOpcode()) {
9525 case ISD::ATOMIC_CMP_SWAP:
9526 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9527 atomic.getOperand(1), atomic.getOperand(2),
9528 atomic.getOperand(3));
9529 case ISD::ATOMIC_SWAP:
9530 case ISD::ATOMIC_LOAD_ADD:
9531 case ISD::ATOMIC_LOAD_SUB:
9532 case ISD::ATOMIC_LOAD_AND:
9533 case ISD::ATOMIC_LOAD_OR:
9534 case ISD::ATOMIC_LOAD_XOR:
9535 case ISD::ATOMIC_LOAD_NAND:
9536 case ISD::ATOMIC_LOAD_MIN:
9537 case ISD::ATOMIC_LOAD_MAX:
9538 case ISD::ATOMIC_LOAD_UMIN:
9539 case ISD::ATOMIC_LOAD_UMAX:
9540 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9541 atomic.getOperand(1), atomic.getOperand(2));
9547 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9548 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
9549 // (and (i32 x86isd::setcc_carry), 1)
9550 // This eliminates the zext. This transformation is necessary because
9551 // ISD::SETCC is always legalized to i8.
9552 DebugLoc dl = N->getDebugLoc();
9553 SDValue N0 = N->getOperand(0);
9554 EVT VT = N->getValueType(0);
9555 if (N0.getOpcode() == ISD::AND &&
9557 N0.getOperand(0).hasOneUse()) {
9558 SDValue N00 = N0.getOperand(0);
9559 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9561 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9562 if (!C || C->getZExtValue() != 1)
9564 return DAG.getNode(ISD::AND, dl, VT,
9565 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9566 N00.getOperand(0), N00.getOperand(1)),
9567 DAG.getConstant(1, VT));
9573 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9574 DAGCombinerInfo &DCI) const {
9575 SelectionDAG &DAG = DCI.DAG;
9576 switch (N->getOpcode()) {
9578 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9579 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
9580 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
9581 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
9584 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
9585 case ISD::OR: return PerformOrCombine(N, DAG, Subtarget);
9586 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
9588 case X86ISD::FOR: return PerformFORCombine(N, DAG);
9589 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
9590 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
9591 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
9592 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
9593 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
9599 //===----------------------------------------------------------------------===//
9600 // X86 Inline Assembly Support
9601 //===----------------------------------------------------------------------===//
9603 static bool LowerToBSwap(CallInst *CI) {
9604 // FIXME: this should verify that we are targetting a 486 or better. If not,
9605 // we will turn this bswap into something that will be lowered to logical ops
9606 // instead of emitting the bswap asm. For now, we don't support 486 or lower
9607 // so don't worry about this.
9609 // Verify this is a simple bswap.
9610 if (CI->getNumOperands() != 2 ||
9611 CI->getType() != CI->getOperand(1)->getType() ||
9612 !CI->getType()->isInteger())
9615 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9616 if (!Ty || Ty->getBitWidth() % 16 != 0)
9619 // Okay, we can do this xform, do so now.
9620 const Type *Tys[] = { Ty };
9621 Module *M = CI->getParent()->getParent()->getParent();
9622 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9624 Value *Op = CI->getOperand(1);
9625 Op = CallInst::Create(Int, Op, CI->getName(), CI);
9627 CI->replaceAllUsesWith(Op);
9628 CI->eraseFromParent();
9632 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9633 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9634 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9636 std::string AsmStr = IA->getAsmString();
9638 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9639 SmallVector<StringRef, 4> AsmPieces;
9640 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
9642 switch (AsmPieces.size()) {
9643 default: return false;
9645 AsmStr = AsmPieces[0];
9647 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
9650 if (AsmPieces.size() == 2 &&
9651 (AsmPieces[0] == "bswap" ||
9652 AsmPieces[0] == "bswapq" ||
9653 AsmPieces[0] == "bswapl") &&
9654 (AsmPieces[1] == "$0" ||
9655 AsmPieces[1] == "${0:q}")) {
9656 // No need to check constraints, nothing other than the equivalent of
9657 // "=r,0" would be valid here.
9658 return LowerToBSwap(CI);
9660 // rorw $$8, ${0:w} --> llvm.bswap.i16
9661 if (CI->getType()->isInteger(16) &&
9662 AsmPieces.size() == 3 &&
9663 AsmPieces[0] == "rorw" &&
9664 AsmPieces[1] == "$$8," &&
9665 AsmPieces[2] == "${0:w}" &&
9666 IA->getConstraintString() == "=r,0,~{dirflag},~{fpsr},~{flags},~{cc}") {
9667 return LowerToBSwap(CI);
9671 if (CI->getType()->isInteger(64) &&
9672 Constraints.size() >= 2 &&
9673 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9674 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9675 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
9676 SmallVector<StringRef, 4> Words;
9677 SplitString(AsmPieces[0], Words, " \t");
9678 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9680 SplitString(AsmPieces[1], Words, " \t");
9681 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9683 SplitString(AsmPieces[2], Words, " \t,");
9684 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9685 Words[2] == "%edx") {
9686 return LowerToBSwap(CI);
9698 /// getConstraintType - Given a constraint letter, return the type of
9699 /// constraint it is for this target.
9700 X86TargetLowering::ConstraintType
9701 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9702 if (Constraint.size() == 1) {
9703 switch (Constraint[0]) {
9715 return C_RegisterClass;
9723 return TargetLowering::getConstraintType(Constraint);
9726 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9727 /// with another that has more specific requirements based on the type of the
9728 /// corresponding operand.
9729 const char *X86TargetLowering::
9730 LowerXConstraint(EVT ConstraintVT) const {
9731 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9732 // 'f' like normal targets.
9733 if (ConstraintVT.isFloatingPoint()) {
9734 if (Subtarget->hasSSE2())
9736 if (Subtarget->hasSSE1())
9740 return TargetLowering::LowerXConstraint(ConstraintVT);
9743 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9744 /// vector. If it is invalid, don't add anything to Ops.
9745 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9748 std::vector<SDValue>&Ops,
9749 SelectionDAG &DAG) const {
9750 SDValue Result(0, 0);
9752 switch (Constraint) {
9755 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9756 if (C->getZExtValue() <= 31) {
9757 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9763 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9764 if (C->getZExtValue() <= 63) {
9765 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9771 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9772 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
9773 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9779 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9780 if (C->getZExtValue() <= 255) {
9781 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9787 // 32-bit signed value
9788 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9789 const ConstantInt *CI = C->getConstantIntValue();
9790 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9791 C->getSExtValue())) {
9792 // Widen to 64 bits here to get it sign extended.
9793 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
9796 // FIXME gcc accepts some relocatable values here too, but only in certain
9797 // memory models; it's complicated.
9802 // 32-bit unsigned value
9803 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9804 const ConstantInt *CI = C->getConstantIntValue();
9805 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9806 C->getZExtValue())) {
9807 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9811 // FIXME gcc accepts some relocatable values here too, but only in certain
9812 // memory models; it's complicated.
9816 // Literal immediates are always ok.
9817 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
9818 // Widen to 64 bits here to get it sign extended.
9819 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
9823 // If we are in non-pic codegen mode, we allow the address of a global (with
9824 // an optional displacement) to be used with 'i'.
9825 GlobalAddressSDNode *GA = 0;
9828 // Match either (GA), (GA+C), (GA+C1+C2), etc.
9830 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
9831 Offset += GA->getOffset();
9833 } else if (Op.getOpcode() == ISD::ADD) {
9834 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9835 Offset += C->getZExtValue();
9836 Op = Op.getOperand(0);
9839 } else if (Op.getOpcode() == ISD::SUB) {
9840 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9841 Offset += -C->getZExtValue();
9842 Op = Op.getOperand(0);
9847 // Otherwise, this isn't something we can handle, reject it.
9851 GlobalValue *GV = GA->getGlobal();
9852 // If we require an extra load to get this address, as in PIC mode, we
9854 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
9855 getTargetMachine())))
9859 Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
9861 Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
9867 if (Result.getNode()) {
9868 Ops.push_back(Result);
9871 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
9875 std::vector<unsigned> X86TargetLowering::
9876 getRegClassForInlineAsmConstraint(const std::string &Constraint,
9878 if (Constraint.size() == 1) {
9879 // FIXME: not handling fp-stack yet!
9880 switch (Constraint[0]) { // GCC X86 Constraint Letters
9881 default: break; // Unknown constraint letter
9882 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
9883 if (Subtarget->is64Bit()) {
9885 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
9886 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
9887 X86::R10D,X86::R11D,X86::R12D,
9888 X86::R13D,X86::R14D,X86::R15D,
9889 X86::EBP, X86::ESP, 0);
9890 else if (VT == MVT::i16)
9891 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
9892 X86::SI, X86::DI, X86::R8W,X86::R9W,
9893 X86::R10W,X86::R11W,X86::R12W,
9894 X86::R13W,X86::R14W,X86::R15W,
9895 X86::BP, X86::SP, 0);
9896 else if (VT == MVT::i8)
9897 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
9898 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
9899 X86::R10B,X86::R11B,X86::R12B,
9900 X86::R13B,X86::R14B,X86::R15B,
9901 X86::BPL, X86::SPL, 0);
9903 else if (VT == MVT::i64)
9904 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
9905 X86::RSI, X86::RDI, X86::R8, X86::R9,
9906 X86::R10, X86::R11, X86::R12,
9907 X86::R13, X86::R14, X86::R15,
9908 X86::RBP, X86::RSP, 0);
9912 // 32-bit fallthrough
9915 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
9916 else if (VT == MVT::i16)
9917 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
9918 else if (VT == MVT::i8)
9919 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
9920 else if (VT == MVT::i64)
9921 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
9926 return std::vector<unsigned>();
9929 std::pair<unsigned, const TargetRegisterClass*>
9930 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9932 // First, see if this is a constraint that directly corresponds to an LLVM
9934 if (Constraint.size() == 1) {
9935 // GCC Constraint Letters
9936 switch (Constraint[0]) {
9938 case 'r': // GENERAL_REGS
9939 case 'l': // INDEX_REGS
9941 return std::make_pair(0U, X86::GR8RegisterClass);
9943 return std::make_pair(0U, X86::GR16RegisterClass);
9944 if (VT == MVT::i32 || !Subtarget->is64Bit())
9945 return std::make_pair(0U, X86::GR32RegisterClass);
9946 return std::make_pair(0U, X86::GR64RegisterClass);
9947 case 'R': // LEGACY_REGS
9949 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
9951 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
9952 if (VT == MVT::i32 || !Subtarget->is64Bit())
9953 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
9954 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
9955 case 'f': // FP Stack registers.
9956 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
9957 // value to the correct fpstack register class.
9958 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
9959 return std::make_pair(0U, X86::RFP32RegisterClass);
9960 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
9961 return std::make_pair(0U, X86::RFP64RegisterClass);
9962 return std::make_pair(0U, X86::RFP80RegisterClass);
9963 case 'y': // MMX_REGS if MMX allowed.
9964 if (!Subtarget->hasMMX()) break;
9965 return std::make_pair(0U, X86::VR64RegisterClass);
9966 case 'Y': // SSE_REGS if SSE2 allowed
9967 if (!Subtarget->hasSSE2()) break;
9969 case 'x': // SSE_REGS if SSE1 allowed
9970 if (!Subtarget->hasSSE1()) break;
9972 switch (VT.getSimpleVT().SimpleTy) {
9974 // Scalar SSE types.
9977 return std::make_pair(0U, X86::FR32RegisterClass);
9980 return std::make_pair(0U, X86::FR64RegisterClass);
9988 return std::make_pair(0U, X86::VR128RegisterClass);
9994 // Use the default implementation in TargetLowering to convert the register
9995 // constraint into a member of a register class.
9996 std::pair<unsigned, const TargetRegisterClass*> Res;
9997 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9999 // Not found as a standard register?
10000 if (Res.second == 0) {
10001 // Map st(0) -> st(7) -> ST0
10002 if (Constraint.size() == 7 && Constraint[0] == '{' &&
10003 tolower(Constraint[1]) == 's' &&
10004 tolower(Constraint[2]) == 't' &&
10005 Constraint[3] == '(' &&
10006 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10007 Constraint[5] == ')' &&
10008 Constraint[6] == '}') {
10010 Res.first = X86::ST0+Constraint[4]-'0';
10011 Res.second = X86::RFP80RegisterClass;
10015 // GCC allows "st(0)" to be called just plain "st".
10016 if (StringRef("{st}").equals_lower(Constraint)) {
10017 Res.first = X86::ST0;
10018 Res.second = X86::RFP80RegisterClass;
10023 if (StringRef("{flags}").equals_lower(Constraint)) {
10024 Res.first = X86::EFLAGS;
10025 Res.second = X86::CCRRegisterClass;
10029 // 'A' means EAX + EDX.
10030 if (Constraint == "A") {
10031 Res.first = X86::EAX;
10032 Res.second = X86::GR32_ADRegisterClass;
10038 // Otherwise, check to see if this is a register class of the wrong value
10039 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10040 // turn into {ax},{dx}.
10041 if (Res.second->hasType(VT))
10042 return Res; // Correct type already, nothing to do.
10044 // All of the single-register GCC register classes map their values onto
10045 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
10046 // really want an 8-bit or 32-bit register, map to the appropriate register
10047 // class and return the appropriate register.
10048 if (Res.second == X86::GR16RegisterClass) {
10049 if (VT == MVT::i8) {
10050 unsigned DestReg = 0;
10051 switch (Res.first) {
10053 case X86::AX: DestReg = X86::AL; break;
10054 case X86::DX: DestReg = X86::DL; break;
10055 case X86::CX: DestReg = X86::CL; break;
10056 case X86::BX: DestReg = X86::BL; break;
10059 Res.first = DestReg;
10060 Res.second = X86::GR8RegisterClass;
10062 } else if (VT == MVT::i32) {
10063 unsigned DestReg = 0;
10064 switch (Res.first) {
10066 case X86::AX: DestReg = X86::EAX; break;
10067 case X86::DX: DestReg = X86::EDX; break;
10068 case X86::CX: DestReg = X86::ECX; break;
10069 case X86::BX: DestReg = X86::EBX; break;
10070 case X86::SI: DestReg = X86::ESI; break;
10071 case X86::DI: DestReg = X86::EDI; break;
10072 case X86::BP: DestReg = X86::EBP; break;
10073 case X86::SP: DestReg = X86::ESP; break;
10076 Res.first = DestReg;
10077 Res.second = X86::GR32RegisterClass;
10079 } else if (VT == MVT::i64) {
10080 unsigned DestReg = 0;
10081 switch (Res.first) {
10083 case X86::AX: DestReg = X86::RAX; break;
10084 case X86::DX: DestReg = X86::RDX; break;
10085 case X86::CX: DestReg = X86::RCX; break;
10086 case X86::BX: DestReg = X86::RBX; break;
10087 case X86::SI: DestReg = X86::RSI; break;
10088 case X86::DI: DestReg = X86::RDI; break;
10089 case X86::BP: DestReg = X86::RBP; break;
10090 case X86::SP: DestReg = X86::RSP; break;
10093 Res.first = DestReg;
10094 Res.second = X86::GR64RegisterClass;
10097 } else if (Res.second == X86::FR32RegisterClass ||
10098 Res.second == X86::FR64RegisterClass ||
10099 Res.second == X86::VR128RegisterClass) {
10100 // Handle references to XMM physical registers that got mapped into the
10101 // wrong class. This can happen with constraints like {xmm0} where the
10102 // target independent register mapper will just pick the first match it can
10103 // find, ignoring the required type.
10104 if (VT == MVT::f32)
10105 Res.second = X86::FR32RegisterClass;
10106 else if (VT == MVT::f64)
10107 Res.second = X86::FR64RegisterClass;
10108 else if (X86::VR128RegisterClass->hasType(VT))
10109 Res.second = X86::VR128RegisterClass;
10115 //===----------------------------------------------------------------------===//
10116 // X86 Widen vector type
10117 //===----------------------------------------------------------------------===//
10119 /// getWidenVectorType: given a vector type, returns the type to widen
10120 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
10121 /// If there is no vector type that we want to widen to, returns MVT::Other
10122 /// When and where to widen is target dependent based on the cost of
10123 /// scalarizing vs using the wider vector type.
10125 EVT X86TargetLowering::getWidenVectorType(EVT VT) const {
10126 assert(VT.isVector());
10127 if (isTypeLegal(VT))
10130 // TODO: In computeRegisterProperty, we can compute the list of legal vector
10131 // type based on element type. This would speed up our search (though
10132 // it may not be worth it since the size of the list is relatively
10134 EVT EltVT = VT.getVectorElementType();
10135 unsigned NElts = VT.getVectorNumElements();
10137 // On X86, it make sense to widen any vector wider than 1
10141 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
10142 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
10143 EVT SVT = (MVT::SimpleValueType)nVT;
10145 if (isTypeLegal(SVT) &&
10146 SVT.getVectorElementType() == EltVT &&
10147 SVT.getVectorNumElements() > NElts)