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 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
55 using namespace dwarf;
57 STATISTIC(NumTailCalls, "Number of tail calls");
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
63 static SDValue Insert128BitVector(SDValue Result,
69 static SDValue Extract128BitVector(SDValue Vec,
74 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
77 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
78 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
79 /// simple subregister reference. Idx is an index in the 128 bits we
80 /// want. It need not be aligned to a 128-bit bounday. That makes
81 /// lowering EXTRACT_VECTOR_ELT operations easier.
82 static SDValue Extract128BitVector(SDValue Vec,
86 EVT VT = Vec.getValueType();
87 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
89 EVT ElVT = VT.getVectorElementType();
91 int Factor = VT.getSizeInBits() / 128;
93 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(),
95 VT.getVectorNumElements() / Factor);
97 // Extract from UNDEF is UNDEF.
98 if (Vec.getOpcode() == ISD::UNDEF)
99 return DAG.getNode(ISD::UNDEF, dl, ResultVT);
101 if (isa<ConstantSDNode>(Idx)) {
102 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
104 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
105 // we can match to VEXTRACTF128.
106 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
108 // This is the index of the first element of the 128-bit chunk
110 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
113 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
115 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
124 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
125 /// sets things up to match to an AVX VINSERTF128 instruction or a
126 /// simple superregister reference. Idx is an index in the 128 bits
127 /// we want. It need not be aligned to a 128-bit bounday. That makes
128 /// lowering INSERT_VECTOR_ELT operations easier.
129 static SDValue Insert128BitVector(SDValue Result,
134 if (isa<ConstantSDNode>(Idx)) {
135 EVT VT = Vec.getValueType();
136 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
138 EVT ElVT = VT.getVectorElementType();
140 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
142 EVT ResultVT = Result.getValueType();
144 // Insert the relevant 128 bits.
145 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
147 // This is the index of the first element of the 128-bit chunk
149 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
152 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
154 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
162 /// Given two vectors, concat them.
163 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
164 DebugLoc dl = Lower.getDebugLoc();
166 assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
168 EVT VT = EVT::getVectorVT(*DAG.getContext(),
169 Lower.getValueType().getVectorElementType(),
170 Lower.getValueType().getVectorNumElements() * 2);
172 // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
173 assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
175 // Insert the upper subvector.
176 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
178 // This is half the length of the result
179 // vector. Start inserting the upper 128
181 Lower.getValueType().getVectorNumElements(),
185 // Insert the lower subvector.
186 Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
190 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
191 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
192 bool is64Bit = Subtarget->is64Bit();
194 if (Subtarget->isTargetEnvMacho()) {
196 return new X8664_MachoTargetObjectFile();
197 return new TargetLoweringObjectFileMachO();
200 if (Subtarget->isTargetELF()) {
202 return new X8664_ELFTargetObjectFile(TM);
203 return new X8632_ELFTargetObjectFile(TM);
205 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
206 return new TargetLoweringObjectFileCOFF();
207 llvm_unreachable("unknown subtarget type");
210 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
211 : TargetLowering(TM, createTLOF(TM)) {
212 Subtarget = &TM.getSubtarget<X86Subtarget>();
213 X86ScalarSSEf64 = Subtarget->hasXMMInt();
214 X86ScalarSSEf32 = Subtarget->hasXMM();
215 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
217 RegInfo = TM.getRegisterInfo();
218 TD = getTargetData();
220 // Set up the TargetLowering object.
221 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
223 // X86 is weird, it always uses i8 for shift amounts and setcc results.
224 setBooleanContents(ZeroOrOneBooleanContent);
226 // For 64-bit since we have so many registers use the ILP scheduler, for
227 // 32-bit code use the register pressure specific scheduling.
228 if (Subtarget->is64Bit())
229 setSchedulingPreference(Sched::ILP);
231 setSchedulingPreference(Sched::RegPressure);
232 setStackPointerRegisterToSaveRestore(X86StackPtr);
234 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
235 // Setup Windows compiler runtime calls.
236 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
237 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
238 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
239 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
240 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
241 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
242 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
243 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
246 if (Subtarget->isTargetDarwin()) {
247 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
248 setUseUnderscoreSetJmp(false);
249 setUseUnderscoreLongJmp(false);
250 } else if (Subtarget->isTargetMingw()) {
251 // MS runtime is weird: it exports _setjmp, but longjmp!
252 setUseUnderscoreSetJmp(true);
253 setUseUnderscoreLongJmp(false);
255 setUseUnderscoreSetJmp(true);
256 setUseUnderscoreLongJmp(true);
259 // Set up the register classes.
260 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
261 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
262 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
263 if (Subtarget->is64Bit())
264 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
266 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
268 // We don't accept any truncstore of integer registers.
269 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
270 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
271 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
272 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
273 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
274 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
276 // SETOEQ and SETUNE require checking two conditions.
277 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
278 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
279 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
280 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
281 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
282 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
284 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
286 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
287 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
288 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
290 if (Subtarget->is64Bit()) {
291 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
292 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
293 } else if (!UseSoftFloat) {
294 // We have an algorithm for SSE2->double, and we turn this into a
295 // 64-bit FILD followed by conditional FADD for other targets.
296 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
297 // We have an algorithm for SSE2, and we turn this into a 64-bit
298 // FILD for other targets.
299 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
302 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
304 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
305 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
308 // SSE has no i16 to fp conversion, only i32
309 if (X86ScalarSSEf32) {
310 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
311 // f32 and f64 cases are Legal, f80 case is not
312 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
314 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
315 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
318 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
319 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
322 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
323 // are Legal, f80 is custom lowered.
324 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
325 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
327 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
329 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
330 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
332 if (X86ScalarSSEf32) {
333 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
334 // f32 and f64 cases are Legal, f80 case is not
335 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
337 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
338 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
341 // Handle FP_TO_UINT by promoting the destination to a larger signed
343 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
344 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
345 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
347 if (Subtarget->is64Bit()) {
348 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
349 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
350 } else if (!UseSoftFloat) {
351 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
352 // Expand FP_TO_UINT into a select.
353 // FIXME: We would like to use a Custom expander here eventually to do
354 // the optimal thing for SSE vs. the default expansion in the legalizer.
355 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
357 // With SSE3 we can use fisttpll to convert to a signed i64; without
358 // SSE, we're stuck with a fistpll.
359 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
362 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
363 if (!X86ScalarSSEf64) {
364 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
365 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
366 if (Subtarget->is64Bit()) {
367 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
368 // Without SSE, i64->f64 goes through memory.
369 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
373 // Scalar integer divide and remainder are lowered to use operations that
374 // produce two results, to match the available instructions. This exposes
375 // the two-result form to trivial CSE, which is able to combine x/y and x%y
376 // into a single instruction.
378 // Scalar integer multiply-high is also lowered to use two-result
379 // operations, to match the available instructions. However, plain multiply
380 // (low) operations are left as Legal, as there are single-result
381 // instructions for this in x86. Using the two-result multiply instructions
382 // when both high and low results are needed must be arranged by dagcombine.
383 for (unsigned i = 0, e = 4; i != e; ++i) {
385 setOperationAction(ISD::MULHS, VT, Expand);
386 setOperationAction(ISD::MULHU, VT, Expand);
387 setOperationAction(ISD::SDIV, VT, Expand);
388 setOperationAction(ISD::UDIV, VT, Expand);
389 setOperationAction(ISD::SREM, VT, Expand);
390 setOperationAction(ISD::UREM, VT, Expand);
392 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
393 setOperationAction(ISD::ADDC, VT, Custom);
394 setOperationAction(ISD::ADDE, VT, Custom);
395 setOperationAction(ISD::SUBC, VT, Custom);
396 setOperationAction(ISD::SUBE, VT, Custom);
399 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
400 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
401 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
402 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
403 if (Subtarget->is64Bit())
404 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
405 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
406 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
407 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
408 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
409 setOperationAction(ISD::FREM , MVT::f32 , Expand);
410 setOperationAction(ISD::FREM , MVT::f64 , Expand);
411 setOperationAction(ISD::FREM , MVT::f80 , Expand);
412 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
414 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
415 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
416 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
417 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
418 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
419 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
420 if (Subtarget->is64Bit()) {
421 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
422 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
425 if (Subtarget->hasPOPCNT()) {
426 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
428 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
429 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
430 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
431 if (Subtarget->is64Bit())
432 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
435 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
436 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
438 // These should be promoted to a larger select which is supported.
439 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
440 // X86 wants to expand cmov itself.
441 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
442 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
443 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
444 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
445 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
446 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
447 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
448 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
449 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
450 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
451 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
452 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
453 if (Subtarget->is64Bit()) {
454 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
455 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
457 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
460 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
461 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
462 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
463 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
464 if (Subtarget->is64Bit())
465 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
466 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
467 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
468 if (Subtarget->is64Bit()) {
469 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
470 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
471 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
472 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
473 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
475 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
476 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
477 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
478 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
479 if (Subtarget->is64Bit()) {
480 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
481 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
482 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
485 if (Subtarget->hasXMM())
486 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
488 // We may not have a libcall for MEMBARRIER so we should lower this.
489 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
491 // On X86 and X86-64, atomic operations are lowered to locked instructions.
492 // Locked instructions, in turn, have implicit fence semantics (all memory
493 // operations are flushed before issuing the locked instruction, and they
494 // are not buffered), so we can fold away the common pattern of
495 // fence-atomic-fence.
496 setShouldFoldAtomicFences(true);
498 // Expand certain atomics
499 for (unsigned i = 0, e = 4; i != e; ++i) {
501 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
502 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
505 if (!Subtarget->is64Bit()) {
506 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
507 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
508 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
509 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
510 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
511 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
512 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
515 // FIXME - use subtarget debug flags
516 if (!Subtarget->isTargetDarwin() &&
517 !Subtarget->isTargetELF() &&
518 !Subtarget->isTargetCygMing()) {
519 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
522 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
523 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
524 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
525 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
526 if (Subtarget->is64Bit()) {
527 setExceptionPointerRegister(X86::RAX);
528 setExceptionSelectorRegister(X86::RDX);
530 setExceptionPointerRegister(X86::EAX);
531 setExceptionSelectorRegister(X86::EDX);
533 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
534 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
536 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
538 setOperationAction(ISD::TRAP, MVT::Other, Legal);
540 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
541 setOperationAction(ISD::VASTART , MVT::Other, Custom);
542 setOperationAction(ISD::VAEND , MVT::Other, Expand);
543 if (Subtarget->is64Bit()) {
544 setOperationAction(ISD::VAARG , MVT::Other, Custom);
545 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
547 setOperationAction(ISD::VAARG , MVT::Other, Expand);
548 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
551 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
552 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
553 setOperationAction(ISD::DYNAMIC_STACKALLOC,
554 (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
555 (Subtarget->isTargetCOFF()
556 && !Subtarget->isTargetEnvMacho()
559 if (!UseSoftFloat && X86ScalarSSEf64) {
560 // f32 and f64 use SSE.
561 // Set up the FP register classes.
562 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
563 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
565 // Use ANDPD to simulate FABS.
566 setOperationAction(ISD::FABS , MVT::f64, Custom);
567 setOperationAction(ISD::FABS , MVT::f32, Custom);
569 // Use XORP to simulate FNEG.
570 setOperationAction(ISD::FNEG , MVT::f64, Custom);
571 setOperationAction(ISD::FNEG , MVT::f32, Custom);
573 // Use ANDPD and ORPD to simulate FCOPYSIGN.
574 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
575 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
577 // We don't support sin/cos/fmod
578 setOperationAction(ISD::FSIN , MVT::f64, Expand);
579 setOperationAction(ISD::FCOS , MVT::f64, Expand);
580 setOperationAction(ISD::FSIN , MVT::f32, Expand);
581 setOperationAction(ISD::FCOS , MVT::f32, Expand);
583 // Expand FP immediates into loads from the stack, except for the special
585 addLegalFPImmediate(APFloat(+0.0)); // xorpd
586 addLegalFPImmediate(APFloat(+0.0f)); // xorps
587 } else if (!UseSoftFloat && X86ScalarSSEf32) {
588 // Use SSE for f32, x87 for f64.
589 // Set up the FP register classes.
590 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
591 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
593 // Use ANDPS to simulate FABS.
594 setOperationAction(ISD::FABS , MVT::f32, Custom);
596 // Use XORP to simulate FNEG.
597 setOperationAction(ISD::FNEG , MVT::f32, Custom);
599 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
601 // Use ANDPS and ORPS to simulate FCOPYSIGN.
602 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
603 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
605 // We don't support sin/cos/fmod
606 setOperationAction(ISD::FSIN , MVT::f32, Expand);
607 setOperationAction(ISD::FCOS , MVT::f32, Expand);
609 // Special cases we handle for FP constants.
610 addLegalFPImmediate(APFloat(+0.0f)); // xorps
611 addLegalFPImmediate(APFloat(+0.0)); // FLD0
612 addLegalFPImmediate(APFloat(+1.0)); // FLD1
613 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
614 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
617 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
618 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
620 } else if (!UseSoftFloat) {
621 // f32 and f64 in x87.
622 // Set up the FP register classes.
623 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
624 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
626 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
627 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
628 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
629 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
632 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
633 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
635 addLegalFPImmediate(APFloat(+0.0)); // FLD0
636 addLegalFPImmediate(APFloat(+1.0)); // FLD1
637 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
638 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
639 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
640 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
641 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
642 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
645 // Long double always uses X87.
647 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
648 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
649 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
651 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
652 addLegalFPImmediate(TmpFlt); // FLD0
654 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
657 APFloat TmpFlt2(+1.0);
658 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
660 addLegalFPImmediate(TmpFlt2); // FLD1
661 TmpFlt2.changeSign();
662 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
666 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
667 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
671 // Always use a library call for pow.
672 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
673 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
674 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
676 setOperationAction(ISD::FLOG, MVT::f80, Expand);
677 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
678 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
679 setOperationAction(ISD::FEXP, MVT::f80, Expand);
680 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
682 // First set operation action for all vector types to either promote
683 // (for widening) or expand (for scalarization). Then we will selectively
684 // turn on ones that can be effectively codegen'd.
685 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
686 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
687 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
688 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
689 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
690 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
691 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
692 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
693 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
694 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
695 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
696 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
698 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
699 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
700 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
701 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
702 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
703 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
704 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
705 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
737 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
741 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
742 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
743 setTruncStoreAction((MVT::SimpleValueType)VT,
744 (MVT::SimpleValueType)InnerVT, Expand);
745 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
747 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
750 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
751 // with -msoft-float, disable use of MMX as well.
752 if (!UseSoftFloat && Subtarget->hasMMX()) {
753 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
754 // No operations on x86mmx supported, everything uses intrinsics.
757 // MMX-sized vectors (other than x86mmx) are expected to be expanded
758 // into smaller operations.
759 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
760 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
761 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
762 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
763 setOperationAction(ISD::AND, MVT::v8i8, Expand);
764 setOperationAction(ISD::AND, MVT::v4i16, Expand);
765 setOperationAction(ISD::AND, MVT::v2i32, Expand);
766 setOperationAction(ISD::AND, MVT::v1i64, Expand);
767 setOperationAction(ISD::OR, MVT::v8i8, Expand);
768 setOperationAction(ISD::OR, MVT::v4i16, Expand);
769 setOperationAction(ISD::OR, MVT::v2i32, Expand);
770 setOperationAction(ISD::OR, MVT::v1i64, Expand);
771 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
772 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
773 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
774 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
775 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
776 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
777 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
778 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
779 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
780 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
781 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
782 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
783 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
784 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
785 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
786 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
787 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
789 if (!UseSoftFloat && Subtarget->hasXMM()) {
790 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
792 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
793 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
794 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
795 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
796 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
797 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
798 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
799 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
800 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
801 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
802 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
803 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
806 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
807 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
809 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
810 // registers cannot be used even for integer operations.
811 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
812 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
813 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
814 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
816 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
817 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
818 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
819 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
820 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
821 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
822 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
823 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
824 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
825 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
826 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
827 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
828 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
829 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
830 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
831 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
833 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
834 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
835 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
836 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
838 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
839 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
840 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
841 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
842 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
844 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
845 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
846 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
847 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
848 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
850 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
851 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
852 EVT VT = (MVT::SimpleValueType)i;
853 // Do not attempt to custom lower non-power-of-2 vectors
854 if (!isPowerOf2_32(VT.getVectorNumElements()))
856 // Do not attempt to custom lower non-128-bit vectors
857 if (!VT.is128BitVector())
859 setOperationAction(ISD::BUILD_VECTOR,
860 VT.getSimpleVT().SimpleTy, Custom);
861 setOperationAction(ISD::VECTOR_SHUFFLE,
862 VT.getSimpleVT().SimpleTy, Custom);
863 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
864 VT.getSimpleVT().SimpleTy, Custom);
867 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
868 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
869 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
870 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
871 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
872 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
874 if (Subtarget->is64Bit()) {
875 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
876 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
879 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
880 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
881 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
884 // Do not attempt to promote non-128-bit vectors
885 if (!VT.is128BitVector())
888 setOperationAction(ISD::AND, SVT, Promote);
889 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
890 setOperationAction(ISD::OR, SVT, Promote);
891 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
892 setOperationAction(ISD::XOR, SVT, Promote);
893 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
894 setOperationAction(ISD::LOAD, SVT, Promote);
895 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
896 setOperationAction(ISD::SELECT, SVT, Promote);
897 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
900 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
902 // Custom lower v2i64 and v2f64 selects.
903 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
904 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
905 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
906 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
908 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
909 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
912 if (Subtarget->hasSSE41()) {
913 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
914 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
915 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
916 setOperationAction(ISD::FRINT, MVT::f32, Legal);
917 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
918 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
919 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
920 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
921 setOperationAction(ISD::FRINT, MVT::f64, Legal);
922 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
924 // FIXME: Do we need to handle scalar-to-vector here?
925 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
927 // Can turn SHL into an integer multiply.
928 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
929 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
931 // i8 and i16 vectors are custom , because the source register and source
932 // source memory operand types are not the same width. f32 vectors are
933 // custom since the immediate controlling the insert encodes additional
935 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
936 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
937 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
938 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
940 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
941 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
942 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
943 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
945 if (Subtarget->is64Bit()) {
946 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
947 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
951 if (Subtarget->hasSSE2()) {
952 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
953 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
954 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
956 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
957 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
958 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
960 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
961 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
964 if (Subtarget->hasSSE42())
965 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
967 if (!UseSoftFloat && Subtarget->hasAVX()) {
968 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
969 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
970 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
971 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
972 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
974 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
975 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
976 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
977 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
979 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
980 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
981 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
982 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
983 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
984 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
986 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
987 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
988 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
989 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
990 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
991 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
993 // Custom lower build_vector, vector_shuffle, scalar_to_vector,
994 // insert_vector_elt extract_subvector and extract_vector_elt for
996 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
997 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
999 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1000 // Do not attempt to custom lower non-256-bit vectors
1001 if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
1002 || (MVT(VT).getSizeInBits() < 256))
1004 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1005 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1006 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1007 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1008 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1010 // Custom-lower insert_subvector and extract_subvector based on
1012 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1013 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1015 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1016 // Do not attempt to custom lower non-256-bit vectors
1017 if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1020 if (MVT(VT).getSizeInBits() == 128) {
1021 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1023 else if (MVT(VT).getSizeInBits() == 256) {
1024 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1028 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1029 // Don't promote loads because we need them for VPERM vector index versions.
1031 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1032 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1034 if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1035 || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1037 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
1038 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v4i64);
1039 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
1040 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v4i64);
1041 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
1042 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v4i64);
1043 //setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
1044 //AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v4i64);
1045 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1046 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1050 // We want to custom lower some of our intrinsics.
1051 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1054 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1055 // handle type legalization for these operations here.
1057 // FIXME: We really should do custom legalization for addition and
1058 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1059 // than generic legalization for 64-bit multiplication-with-overflow, though.
1060 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1061 // Add/Sub/Mul with overflow operations are custom lowered.
1063 setOperationAction(ISD::SADDO, VT, Custom);
1064 setOperationAction(ISD::UADDO, VT, Custom);
1065 setOperationAction(ISD::SSUBO, VT, Custom);
1066 setOperationAction(ISD::USUBO, VT, Custom);
1067 setOperationAction(ISD::SMULO, VT, Custom);
1068 setOperationAction(ISD::UMULO, VT, Custom);
1071 // There are no 8-bit 3-address imul/mul instructions
1072 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1073 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1075 if (!Subtarget->is64Bit()) {
1076 // These libcalls are not available in 32-bit.
1077 setLibcallName(RTLIB::SHL_I128, 0);
1078 setLibcallName(RTLIB::SRL_I128, 0);
1079 setLibcallName(RTLIB::SRA_I128, 0);
1082 // We have target-specific dag combine patterns for the following nodes:
1083 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1084 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1085 setTargetDAGCombine(ISD::BUILD_VECTOR);
1086 setTargetDAGCombine(ISD::SELECT);
1087 setTargetDAGCombine(ISD::SHL);
1088 setTargetDAGCombine(ISD::SRA);
1089 setTargetDAGCombine(ISD::SRL);
1090 setTargetDAGCombine(ISD::OR);
1091 setTargetDAGCombine(ISD::AND);
1092 setTargetDAGCombine(ISD::ADD);
1093 setTargetDAGCombine(ISD::SUB);
1094 setTargetDAGCombine(ISD::STORE);
1095 setTargetDAGCombine(ISD::ZERO_EXTEND);
1096 if (Subtarget->is64Bit())
1097 setTargetDAGCombine(ISD::MUL);
1099 computeRegisterProperties();
1101 // On Darwin, -Os means optimize for size without hurting performance,
1102 // do not reduce the limit.
1103 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1104 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1105 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1106 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1107 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1108 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1109 setPrefLoopAlignment(16);
1110 benefitFromCodePlacementOpt = true;
1112 setPrefFunctionAlignment(4);
1116 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1121 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1122 /// the desired ByVal argument alignment.
1123 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1126 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1127 if (VTy->getBitWidth() == 128)
1129 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1130 unsigned EltAlign = 0;
1131 getMaxByValAlign(ATy->getElementType(), EltAlign);
1132 if (EltAlign > MaxAlign)
1133 MaxAlign = EltAlign;
1134 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1135 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1136 unsigned EltAlign = 0;
1137 getMaxByValAlign(STy->getElementType(i), EltAlign);
1138 if (EltAlign > MaxAlign)
1139 MaxAlign = EltAlign;
1147 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1148 /// function arguments in the caller parameter area. For X86, aggregates
1149 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1150 /// are at 4-byte boundaries.
1151 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1152 if (Subtarget->is64Bit()) {
1153 // Max of 8 and alignment of type.
1154 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1161 if (Subtarget->hasXMM())
1162 getMaxByValAlign(Ty, Align);
1166 /// getOptimalMemOpType - Returns the target specific optimal type for load
1167 /// and store operations as a result of memset, memcpy, and memmove
1168 /// lowering. If DstAlign is zero that means it's safe to destination
1169 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1170 /// means there isn't a need to check it against alignment requirement,
1171 /// probably because the source does not need to be loaded. If
1172 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1173 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1174 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1175 /// constant so it does not need to be loaded.
1176 /// It returns EVT::Other if the type should be determined using generic
1177 /// target-independent logic.
1179 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1180 unsigned DstAlign, unsigned SrcAlign,
1181 bool NonScalarIntSafe,
1183 MachineFunction &MF) const {
1184 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1185 // linux. This is because the stack realignment code can't handle certain
1186 // cases like PR2962. This should be removed when PR2962 is fixed.
1187 const Function *F = MF.getFunction();
1188 if (NonScalarIntSafe &&
1189 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1191 (Subtarget->isUnalignedMemAccessFast() ||
1192 ((DstAlign == 0 || DstAlign >= 16) &&
1193 (SrcAlign == 0 || SrcAlign >= 16))) &&
1194 Subtarget->getStackAlignment() >= 16) {
1195 if (Subtarget->hasSSE2())
1197 if (Subtarget->hasSSE1())
1199 } else if (!MemcpyStrSrc && Size >= 8 &&
1200 !Subtarget->is64Bit() &&
1201 Subtarget->getStackAlignment() >= 8 &&
1202 Subtarget->hasXMMInt()) {
1203 // Do not use f64 to lower memcpy if source is string constant. It's
1204 // better to use i32 to avoid the loads.
1208 if (Subtarget->is64Bit() && Size >= 8)
1213 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1214 /// current function. The returned value is a member of the
1215 /// MachineJumpTableInfo::JTEntryKind enum.
1216 unsigned X86TargetLowering::getJumpTableEncoding() const {
1217 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1219 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1220 Subtarget->isPICStyleGOT())
1221 return MachineJumpTableInfo::EK_Custom32;
1223 // Otherwise, use the normal jump table encoding heuristics.
1224 return TargetLowering::getJumpTableEncoding();
1228 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1229 const MachineBasicBlock *MBB,
1230 unsigned uid,MCContext &Ctx) const{
1231 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1232 Subtarget->isPICStyleGOT());
1233 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1235 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1236 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1239 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1241 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1242 SelectionDAG &DAG) const {
1243 if (!Subtarget->is64Bit())
1244 // This doesn't have DebugLoc associated with it, but is not really the
1245 // same as a Register.
1246 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1250 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1251 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1253 const MCExpr *X86TargetLowering::
1254 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1255 MCContext &Ctx) const {
1256 // X86-64 uses RIP relative addressing based on the jump table label.
1257 if (Subtarget->isPICStyleRIPRel())
1258 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1260 // Otherwise, the reference is relative to the PIC base.
1261 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1264 // FIXME: Why this routine is here? Move to RegInfo!
1265 std::pair<const TargetRegisterClass*, uint8_t>
1266 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1267 const TargetRegisterClass *RRC = 0;
1269 switch (VT.getSimpleVT().SimpleTy) {
1271 return TargetLowering::findRepresentativeClass(VT);
1272 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1273 RRC = (Subtarget->is64Bit()
1274 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1277 RRC = X86::VR64RegisterClass;
1279 case MVT::f32: case MVT::f64:
1280 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1281 case MVT::v4f32: case MVT::v2f64:
1282 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1284 RRC = X86::VR128RegisterClass;
1287 return std::make_pair(RRC, Cost);
1290 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1291 unsigned &Offset) const {
1292 if (!Subtarget->isTargetLinux())
1295 if (Subtarget->is64Bit()) {
1296 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1298 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1311 //===----------------------------------------------------------------------===//
1312 // Return Value Calling Convention Implementation
1313 //===----------------------------------------------------------------------===//
1315 #include "X86GenCallingConv.inc"
1318 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1319 const SmallVectorImpl<ISD::OutputArg> &Outs,
1320 LLVMContext &Context) const {
1321 SmallVector<CCValAssign, 16> RVLocs;
1322 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1324 return CCInfo.CheckReturn(Outs, RetCC_X86);
1328 X86TargetLowering::LowerReturn(SDValue Chain,
1329 CallingConv::ID CallConv, bool isVarArg,
1330 const SmallVectorImpl<ISD::OutputArg> &Outs,
1331 const SmallVectorImpl<SDValue> &OutVals,
1332 DebugLoc dl, SelectionDAG &DAG) const {
1333 MachineFunction &MF = DAG.getMachineFunction();
1334 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1336 SmallVector<CCValAssign, 16> RVLocs;
1337 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1338 RVLocs, *DAG.getContext());
1339 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1341 // Add the regs to the liveout set for the function.
1342 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1343 for (unsigned i = 0; i != RVLocs.size(); ++i)
1344 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1345 MRI.addLiveOut(RVLocs[i].getLocReg());
1349 SmallVector<SDValue, 6> RetOps;
1350 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1351 // Operand #1 = Bytes To Pop
1352 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1355 // Copy the result values into the output registers.
1356 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1357 CCValAssign &VA = RVLocs[i];
1358 assert(VA.isRegLoc() && "Can only return in registers!");
1359 SDValue ValToCopy = OutVals[i];
1360 EVT ValVT = ValToCopy.getValueType();
1362 // If this is x86-64, and we disabled SSE, we can't return FP values,
1363 // or SSE or MMX vectors.
1364 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1365 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1366 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1367 report_fatal_error("SSE register return with SSE disabled");
1369 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1370 // llvm-gcc has never done it right and no one has noticed, so this
1371 // should be OK for now.
1372 if (ValVT == MVT::f64 &&
1373 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1374 report_fatal_error("SSE2 register return with SSE2 disabled");
1376 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1377 // the RET instruction and handled by the FP Stackifier.
1378 if (VA.getLocReg() == X86::ST0 ||
1379 VA.getLocReg() == X86::ST1) {
1380 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1381 // change the value to the FP stack register class.
1382 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1383 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1384 RetOps.push_back(ValToCopy);
1385 // Don't emit a copytoreg.
1389 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1390 // which is returned in RAX / RDX.
1391 if (Subtarget->is64Bit()) {
1392 if (ValVT == MVT::x86mmx) {
1393 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1394 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1395 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1397 // If we don't have SSE2 available, convert to v4f32 so the generated
1398 // register is legal.
1399 if (!Subtarget->hasSSE2())
1400 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1405 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1406 Flag = Chain.getValue(1);
1409 // The x86-64 ABI for returning structs by value requires that we copy
1410 // the sret argument into %rax for the return. We saved the argument into
1411 // a virtual register in the entry block, so now we copy the value out
1413 if (Subtarget->is64Bit() &&
1414 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1415 MachineFunction &MF = DAG.getMachineFunction();
1416 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1417 unsigned Reg = FuncInfo->getSRetReturnReg();
1419 "SRetReturnReg should have been set in LowerFormalArguments().");
1420 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1422 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1423 Flag = Chain.getValue(1);
1425 // RAX now acts like a return value.
1426 MRI.addLiveOut(X86::RAX);
1429 RetOps[0] = Chain; // Update chain.
1431 // Add the flag if we have it.
1433 RetOps.push_back(Flag);
1435 return DAG.getNode(X86ISD::RET_FLAG, dl,
1436 MVT::Other, &RetOps[0], RetOps.size());
1439 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1440 if (N->getNumValues() != 1)
1442 if (!N->hasNUsesOfValue(1, 0))
1445 SDNode *Copy = *N->use_begin();
1446 if (Copy->getOpcode() != ISD::CopyToReg &&
1447 Copy->getOpcode() != ISD::FP_EXTEND)
1450 bool HasRet = false;
1451 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1453 if (UI->getOpcode() != X86ISD::RET_FLAG)
1462 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1463 ISD::NodeType ExtendKind) const {
1465 // TODO: Is this also valid on 32-bit?
1466 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1467 ReturnMVT = MVT::i8;
1469 ReturnMVT = MVT::i32;
1471 EVT MinVT = getRegisterType(Context, ReturnMVT);
1472 return VT.bitsLT(MinVT) ? MinVT : VT;
1475 /// LowerCallResult - Lower the result values of a call into the
1476 /// appropriate copies out of appropriate physical registers.
1479 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1480 CallingConv::ID CallConv, bool isVarArg,
1481 const SmallVectorImpl<ISD::InputArg> &Ins,
1482 DebugLoc dl, SelectionDAG &DAG,
1483 SmallVectorImpl<SDValue> &InVals) const {
1485 // Assign locations to each value returned by this call.
1486 SmallVector<CCValAssign, 16> RVLocs;
1487 bool Is64Bit = Subtarget->is64Bit();
1488 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1489 RVLocs, *DAG.getContext());
1490 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1492 // Copy all of the result registers out of their specified physreg.
1493 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1494 CCValAssign &VA = RVLocs[i];
1495 EVT CopyVT = VA.getValVT();
1497 // If this is x86-64, and we disabled SSE, we can't return FP values
1498 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1499 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1500 report_fatal_error("SSE register return with SSE disabled");
1505 // If this is a call to a function that returns an fp value on the floating
1506 // point stack, we must guarantee the the value is popped from the stack, so
1507 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1508 // if the return value is not used. We use the FpGET_ST0 instructions
1510 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1511 // If we prefer to use the value in xmm registers, copy it out as f80 and
1512 // use a truncate to move it from fp stack reg to xmm reg.
1513 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1514 bool isST0 = VA.getLocReg() == X86::ST0;
1516 if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1517 if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1518 if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1519 SDValue Ops[] = { Chain, InFlag };
1520 Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1522 Val = Chain.getValue(0);
1524 // Round the f80 to the right size, which also moves it to the appropriate
1526 if (CopyVT != VA.getValVT())
1527 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1528 // This truncation won't change the value.
1529 DAG.getIntPtrConstant(1));
1531 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1532 CopyVT, InFlag).getValue(1);
1533 Val = Chain.getValue(0);
1535 InFlag = Chain.getValue(2);
1536 InVals.push_back(Val);
1543 //===----------------------------------------------------------------------===//
1544 // C & StdCall & Fast Calling Convention implementation
1545 //===----------------------------------------------------------------------===//
1546 // StdCall calling convention seems to be standard for many Windows' API
1547 // routines and around. It differs from C calling convention just a little:
1548 // callee should clean up the stack, not caller. Symbols should be also
1549 // decorated in some fancy way :) It doesn't support any vector arguments.
1550 // For info on fast calling convention see Fast Calling Convention (tail call)
1551 // implementation LowerX86_32FastCCCallTo.
1553 /// CallIsStructReturn - Determines whether a call uses struct return
1555 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1559 return Outs[0].Flags.isSRet();
1562 /// ArgsAreStructReturn - Determines whether a function uses struct
1563 /// return semantics.
1565 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1569 return Ins[0].Flags.isSRet();
1572 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1573 /// by "Src" to address "Dst" with size and alignment information specified by
1574 /// the specific parameter attribute. The copy will be passed as a byval
1575 /// function parameter.
1577 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1578 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1580 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1582 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1583 /*isVolatile*/false, /*AlwaysInline=*/true,
1584 MachinePointerInfo(), MachinePointerInfo());
1587 /// IsTailCallConvention - Return true if the calling convention is one that
1588 /// supports tail call optimization.
1589 static bool IsTailCallConvention(CallingConv::ID CC) {
1590 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1593 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1594 if (!CI->isTailCall())
1598 CallingConv::ID CalleeCC = CS.getCallingConv();
1599 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1605 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1606 /// a tailcall target by changing its ABI.
1607 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1608 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1612 X86TargetLowering::LowerMemArgument(SDValue Chain,
1613 CallingConv::ID CallConv,
1614 const SmallVectorImpl<ISD::InputArg> &Ins,
1615 DebugLoc dl, SelectionDAG &DAG,
1616 const CCValAssign &VA,
1617 MachineFrameInfo *MFI,
1619 // Create the nodes corresponding to a load from this parameter slot.
1620 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1621 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1622 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1625 // If value is passed by pointer we have address passed instead of the value
1627 if (VA.getLocInfo() == CCValAssign::Indirect)
1628 ValVT = VA.getLocVT();
1630 ValVT = VA.getValVT();
1632 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1633 // changed with more analysis.
1634 // In case of tail call optimization mark all arguments mutable. Since they
1635 // could be overwritten by lowering of arguments in case of a tail call.
1636 if (Flags.isByVal()) {
1637 unsigned Bytes = Flags.getByValSize();
1638 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1639 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1640 return DAG.getFrameIndex(FI, getPointerTy());
1642 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1643 VA.getLocMemOffset(), isImmutable);
1644 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1645 return DAG.getLoad(ValVT, dl, Chain, FIN,
1646 MachinePointerInfo::getFixedStack(FI),
1652 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1653 CallingConv::ID CallConv,
1655 const SmallVectorImpl<ISD::InputArg> &Ins,
1658 SmallVectorImpl<SDValue> &InVals)
1660 MachineFunction &MF = DAG.getMachineFunction();
1661 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1663 const Function* Fn = MF.getFunction();
1664 if (Fn->hasExternalLinkage() &&
1665 Subtarget->isTargetCygMing() &&
1666 Fn->getName() == "main")
1667 FuncInfo->setForceFramePointer(true);
1669 MachineFrameInfo *MFI = MF.getFrameInfo();
1670 bool Is64Bit = Subtarget->is64Bit();
1671 bool IsWin64 = Subtarget->isTargetWin64();
1673 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1674 "Var args not supported with calling convention fastcc or ghc");
1676 // Assign locations to all of the incoming arguments.
1677 SmallVector<CCValAssign, 16> ArgLocs;
1678 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1679 ArgLocs, *DAG.getContext());
1681 // Allocate shadow area for Win64
1683 CCInfo.AllocateStack(32, 8);
1686 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1688 unsigned LastVal = ~0U;
1690 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1691 CCValAssign &VA = ArgLocs[i];
1692 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1694 assert(VA.getValNo() != LastVal &&
1695 "Don't support value assigned to multiple locs yet");
1696 LastVal = VA.getValNo();
1698 if (VA.isRegLoc()) {
1699 EVT RegVT = VA.getLocVT();
1700 TargetRegisterClass *RC = NULL;
1701 if (RegVT == MVT::i32)
1702 RC = X86::GR32RegisterClass;
1703 else if (Is64Bit && RegVT == MVT::i64)
1704 RC = X86::GR64RegisterClass;
1705 else if (RegVT == MVT::f32)
1706 RC = X86::FR32RegisterClass;
1707 else if (RegVT == MVT::f64)
1708 RC = X86::FR64RegisterClass;
1709 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1710 RC = X86::VR256RegisterClass;
1711 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1712 RC = X86::VR128RegisterClass;
1713 else if (RegVT == MVT::x86mmx)
1714 RC = X86::VR64RegisterClass;
1716 llvm_unreachable("Unknown argument type!");
1718 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1719 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1721 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1722 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1724 if (VA.getLocInfo() == CCValAssign::SExt)
1725 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1726 DAG.getValueType(VA.getValVT()));
1727 else if (VA.getLocInfo() == CCValAssign::ZExt)
1728 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1729 DAG.getValueType(VA.getValVT()));
1730 else if (VA.getLocInfo() == CCValAssign::BCvt)
1731 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1733 if (VA.isExtInLoc()) {
1734 // Handle MMX values passed in XMM regs.
1735 if (RegVT.isVector()) {
1736 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1739 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1742 assert(VA.isMemLoc());
1743 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1746 // If value is passed via pointer - do a load.
1747 if (VA.getLocInfo() == CCValAssign::Indirect)
1748 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1749 MachinePointerInfo(), false, false, 0);
1751 InVals.push_back(ArgValue);
1754 // The x86-64 ABI for returning structs by value requires that we copy
1755 // the sret argument into %rax for the return. Save the argument into
1756 // a virtual register so that we can access it from the return points.
1757 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1758 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1759 unsigned Reg = FuncInfo->getSRetReturnReg();
1761 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1762 FuncInfo->setSRetReturnReg(Reg);
1764 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1765 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1768 unsigned StackSize = CCInfo.getNextStackOffset();
1769 // Align stack specially for tail calls.
1770 if (FuncIsMadeTailCallSafe(CallConv))
1771 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1773 // If the function takes variable number of arguments, make a frame index for
1774 // the start of the first vararg value... for expansion of llvm.va_start.
1776 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1777 CallConv != CallingConv::X86_ThisCall)) {
1778 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1781 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1783 // FIXME: We should really autogenerate these arrays
1784 static const unsigned GPR64ArgRegsWin64[] = {
1785 X86::RCX, X86::RDX, X86::R8, X86::R9
1787 static const unsigned GPR64ArgRegs64Bit[] = {
1788 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1790 static const unsigned XMMArgRegs64Bit[] = {
1791 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1792 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1794 const unsigned *GPR64ArgRegs;
1795 unsigned NumXMMRegs = 0;
1798 // The XMM registers which might contain var arg parameters are shadowed
1799 // in their paired GPR. So we only need to save the GPR to their home
1801 TotalNumIntRegs = 4;
1802 GPR64ArgRegs = GPR64ArgRegsWin64;
1804 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1805 GPR64ArgRegs = GPR64ArgRegs64Bit;
1807 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1809 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1812 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1813 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1814 "SSE register cannot be used when SSE is disabled!");
1815 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1816 "SSE register cannot be used when SSE is disabled!");
1817 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1818 // Kernel mode asks for SSE to be disabled, so don't push them
1820 TotalNumXMMRegs = 0;
1823 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1824 // Get to the caller-allocated home save location. Add 8 to account
1825 // for the return address.
1826 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1827 FuncInfo->setRegSaveFrameIndex(
1828 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1829 // Fixup to set vararg frame on shadow area (4 x i64).
1831 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1833 // For X86-64, if there are vararg parameters that are passed via
1834 // registers, then we must store them to their spots on the stack so they
1835 // may be loaded by deferencing the result of va_next.
1836 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1837 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1838 FuncInfo->setRegSaveFrameIndex(
1839 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1843 // Store the integer parameter registers.
1844 SmallVector<SDValue, 8> MemOps;
1845 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1847 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1848 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1849 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1850 DAG.getIntPtrConstant(Offset));
1851 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1852 X86::GR64RegisterClass);
1853 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1855 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1856 MachinePointerInfo::getFixedStack(
1857 FuncInfo->getRegSaveFrameIndex(), Offset),
1859 MemOps.push_back(Store);
1863 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1864 // Now store the XMM (fp + vector) parameter registers.
1865 SmallVector<SDValue, 11> SaveXMMOps;
1866 SaveXMMOps.push_back(Chain);
1868 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1869 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1870 SaveXMMOps.push_back(ALVal);
1872 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1873 FuncInfo->getRegSaveFrameIndex()));
1874 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1875 FuncInfo->getVarArgsFPOffset()));
1877 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1878 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1879 X86::VR128RegisterClass);
1880 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1881 SaveXMMOps.push_back(Val);
1883 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1885 &SaveXMMOps[0], SaveXMMOps.size()));
1888 if (!MemOps.empty())
1889 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1890 &MemOps[0], MemOps.size());
1894 // Some CCs need callee pop.
1895 if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1896 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1898 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1899 // If this is an sret function, the return should pop the hidden pointer.
1900 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1901 FuncInfo->setBytesToPopOnReturn(4);
1905 // RegSaveFrameIndex is X86-64 only.
1906 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1907 if (CallConv == CallingConv::X86_FastCall ||
1908 CallConv == CallingConv::X86_ThisCall)
1909 // fastcc functions can't have varargs.
1910 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1917 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1918 SDValue StackPtr, SDValue Arg,
1919 DebugLoc dl, SelectionDAG &DAG,
1920 const CCValAssign &VA,
1921 ISD::ArgFlagsTy Flags) const {
1922 unsigned LocMemOffset = VA.getLocMemOffset();
1923 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1924 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1925 if (Flags.isByVal())
1926 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1928 return DAG.getStore(Chain, dl, Arg, PtrOff,
1929 MachinePointerInfo::getStack(LocMemOffset),
1933 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1934 /// optimization is performed and it is required.
1936 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1937 SDValue &OutRetAddr, SDValue Chain,
1938 bool IsTailCall, bool Is64Bit,
1939 int FPDiff, DebugLoc dl) const {
1940 // Adjust the Return address stack slot.
1941 EVT VT = getPointerTy();
1942 OutRetAddr = getReturnAddressFrameIndex(DAG);
1944 // Load the "old" Return address.
1945 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1947 return SDValue(OutRetAddr.getNode(), 1);
1950 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1951 /// optimization is performed and it is required (FPDiff!=0).
1953 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1954 SDValue Chain, SDValue RetAddrFrIdx,
1955 bool Is64Bit, int FPDiff, DebugLoc dl) {
1956 // Store the return address to the appropriate stack slot.
1957 if (!FPDiff) return Chain;
1958 // Calculate the new stack slot for the return address.
1959 int SlotSize = Is64Bit ? 8 : 4;
1960 int NewReturnAddrFI =
1961 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1962 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1963 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1964 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1965 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1971 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1972 CallingConv::ID CallConv, bool isVarArg,
1974 const SmallVectorImpl<ISD::OutputArg> &Outs,
1975 const SmallVectorImpl<SDValue> &OutVals,
1976 const SmallVectorImpl<ISD::InputArg> &Ins,
1977 DebugLoc dl, SelectionDAG &DAG,
1978 SmallVectorImpl<SDValue> &InVals) const {
1979 MachineFunction &MF = DAG.getMachineFunction();
1980 bool Is64Bit = Subtarget->is64Bit();
1981 bool IsWin64 = Subtarget->isTargetWin64();
1982 bool IsStructRet = CallIsStructReturn(Outs);
1983 bool IsSibcall = false;
1986 // Check if it's really possible to do a tail call.
1987 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1988 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1989 Outs, OutVals, Ins, DAG);
1991 // Sibcalls are automatically detected tailcalls which do not require
1993 if (!GuaranteedTailCallOpt && isTailCall)
2000 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2001 "Var args not supported with calling convention fastcc or ghc");
2003 // Analyze operands of the call, assigning locations to each operand.
2004 SmallVector<CCValAssign, 16> ArgLocs;
2005 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
2006 ArgLocs, *DAG.getContext());
2008 // Allocate shadow area for Win64
2010 CCInfo.AllocateStack(32, 8);
2013 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2015 // Get a count of how many bytes are to be pushed on the stack.
2016 unsigned NumBytes = CCInfo.getNextStackOffset();
2018 // This is a sibcall. The memory operands are available in caller's
2019 // own caller's stack.
2021 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2022 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2025 if (isTailCall && !IsSibcall) {
2026 // Lower arguments at fp - stackoffset + fpdiff.
2027 unsigned NumBytesCallerPushed =
2028 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2029 FPDiff = NumBytesCallerPushed - NumBytes;
2031 // Set the delta of movement of the returnaddr stackslot.
2032 // But only set if delta is greater than previous delta.
2033 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2034 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2038 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2040 SDValue RetAddrFrIdx;
2041 // Load return address for tail calls.
2042 if (isTailCall && FPDiff)
2043 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2044 Is64Bit, FPDiff, dl);
2046 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2047 SmallVector<SDValue, 8> MemOpChains;
2050 // Walk the register/memloc assignments, inserting copies/loads. In the case
2051 // of tail call optimization arguments are handle later.
2052 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2053 CCValAssign &VA = ArgLocs[i];
2054 EVT RegVT = VA.getLocVT();
2055 SDValue Arg = OutVals[i];
2056 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2057 bool isByVal = Flags.isByVal();
2059 // Promote the value if needed.
2060 switch (VA.getLocInfo()) {
2061 default: llvm_unreachable("Unknown loc info!");
2062 case CCValAssign::Full: break;
2063 case CCValAssign::SExt:
2064 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2066 case CCValAssign::ZExt:
2067 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2069 case CCValAssign::AExt:
2070 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2071 // Special case: passing MMX values in XMM registers.
2072 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2073 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2074 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2076 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2078 case CCValAssign::BCvt:
2079 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2081 case CCValAssign::Indirect: {
2082 // Store the argument.
2083 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2084 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2085 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2086 MachinePointerInfo::getFixedStack(FI),
2093 if (VA.isRegLoc()) {
2095 if (CCInfo.isFirstByValRegValid()) {
2096 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2097 unsigned reg = CCInfo.getFirstByValReg();
2098 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, Arg,
2099 MachinePointerInfo(),
2101 MemOpChains.push_back(Load.getValue(1));
2102 RegsToPass.push_back(std::make_pair(reg, Load));
2103 if (Flags.getByValSize() > 8) {
2104 SDValue Const8 = DAG.getConstant(8, MVT::i32);
2105 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const8);
2106 SDValue Load2 = DAG.getLoad(PtrVT, dl, Chain, AddArg,
2107 MachinePointerInfo(),
2109 MemOpChains.push_back(Load.getValue(1));
2110 RegsToPass.push_back(std::make_pair(reg+1, Load));
2112 CCInfo.clearFirstByValReg();
2116 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2117 if (isVarArg && IsWin64) {
2118 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2119 // shadow reg if callee is a varargs function.
2120 unsigned ShadowReg = 0;
2121 switch (VA.getLocReg()) {
2122 case X86::XMM0: ShadowReg = X86::RCX; break;
2123 case X86::XMM1: ShadowReg = X86::RDX; break;
2124 case X86::XMM2: ShadowReg = X86::R8; break;
2125 case X86::XMM3: ShadowReg = X86::R9; break;
2128 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2131 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2132 if (isByVal) { // In memory.
2135 assert(VA.isMemLoc());
2136 if (StackPtr.getNode() == 0)
2137 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2138 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2139 dl, DAG, VA, Flags));
2141 } // end for (all register/memloc assignments)
2143 if (!MemOpChains.empty())
2144 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2145 &MemOpChains[0], MemOpChains.size());
2147 // Build a sequence of copy-to-reg nodes chained together with token chain
2148 // and flag operands which copy the outgoing args into registers.
2150 // Tail call byval lowering might overwrite argument registers so in case of
2151 // tail call optimization the copies to registers are lowered later.
2153 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2154 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2155 RegsToPass[i].second, InFlag);
2156 InFlag = Chain.getValue(1);
2159 if (Subtarget->isPICStyleGOT()) {
2160 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2163 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2164 DAG.getNode(X86ISD::GlobalBaseReg,
2165 DebugLoc(), getPointerTy()),
2167 InFlag = Chain.getValue(1);
2169 // If we are tail calling and generating PIC/GOT style code load the
2170 // address of the callee into ECX. The value in ecx is used as target of
2171 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2172 // for tail calls on PIC/GOT architectures. Normally we would just put the
2173 // address of GOT into ebx and then call target@PLT. But for tail calls
2174 // ebx would be restored (since ebx is callee saved) before jumping to the
2177 // Note: The actual moving to ECX is done further down.
2178 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2179 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2180 !G->getGlobal()->hasProtectedVisibility())
2181 Callee = LowerGlobalAddress(Callee, DAG);
2182 else if (isa<ExternalSymbolSDNode>(Callee))
2183 Callee = LowerExternalSymbol(Callee, DAG);
2187 if (Is64Bit && isVarArg && !IsWin64) {
2188 // From AMD64 ABI document:
2189 // For calls that may call functions that use varargs or stdargs
2190 // (prototype-less calls or calls to functions containing ellipsis (...) in
2191 // the declaration) %al is used as hidden argument to specify the number
2192 // of SSE registers used. The contents of %al do not need to match exactly
2193 // the number of registers, but must be an ubound on the number of SSE
2194 // registers used and is in the range 0 - 8 inclusive.
2196 // Count the number of XMM registers allocated.
2197 static const unsigned XMMArgRegs[] = {
2198 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2199 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2201 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2202 assert((Subtarget->hasXMM() || !NumXMMRegs)
2203 && "SSE registers cannot be used when SSE is disabled");
2205 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2206 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2207 InFlag = Chain.getValue(1);
2211 // For tail calls lower the arguments to the 'real' stack slot.
2213 // Force all the incoming stack arguments to be loaded from the stack
2214 // before any new outgoing arguments are stored to the stack, because the
2215 // outgoing stack slots may alias the incoming argument stack slots, and
2216 // the alias isn't otherwise explicit. This is slightly more conservative
2217 // than necessary, because it means that each store effectively depends
2218 // on every argument instead of just those arguments it would clobber.
2219 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2221 SmallVector<SDValue, 8> MemOpChains2;
2224 // Do not flag preceding copytoreg stuff together with the following stuff.
2226 if (GuaranteedTailCallOpt) {
2227 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2228 CCValAssign &VA = ArgLocs[i];
2231 assert(VA.isMemLoc());
2232 SDValue Arg = OutVals[i];
2233 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2234 // Create frame index.
2235 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2236 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2237 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2238 FIN = DAG.getFrameIndex(FI, getPointerTy());
2240 if (Flags.isByVal()) {
2241 // Copy relative to framepointer.
2242 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2243 if (StackPtr.getNode() == 0)
2244 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2246 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2248 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2252 // Store relative to framepointer.
2253 MemOpChains2.push_back(
2254 DAG.getStore(ArgChain, dl, Arg, FIN,
2255 MachinePointerInfo::getFixedStack(FI),
2261 if (!MemOpChains2.empty())
2262 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2263 &MemOpChains2[0], MemOpChains2.size());
2265 // Copy arguments to their registers.
2266 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2267 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2268 RegsToPass[i].second, InFlag);
2269 InFlag = Chain.getValue(1);
2273 // Store the return address to the appropriate stack slot.
2274 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2278 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2279 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2280 // In the 64-bit large code model, we have to make all calls
2281 // through a register, since the call instruction's 32-bit
2282 // pc-relative offset may not be large enough to hold the whole
2284 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2285 // If the callee is a GlobalAddress node (quite common, every direct call
2286 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2289 // We should use extra load for direct calls to dllimported functions in
2291 const GlobalValue *GV = G->getGlobal();
2292 if (!GV->hasDLLImportLinkage()) {
2293 unsigned char OpFlags = 0;
2295 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2296 // external symbols most go through the PLT in PIC mode. If the symbol
2297 // has hidden or protected visibility, or if it is static or local, then
2298 // we don't need to use the PLT - we can directly call it.
2299 if (Subtarget->isTargetELF() &&
2300 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2301 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2302 OpFlags = X86II::MO_PLT;
2303 } else if (Subtarget->isPICStyleStubAny() &&
2304 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2305 (!Subtarget->getTargetTriple().isMacOSX() ||
2306 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2307 // PC-relative references to external symbols should go through $stub,
2308 // unless we're building with the leopard linker or later, which
2309 // automatically synthesizes these stubs.
2310 OpFlags = X86II::MO_DARWIN_STUB;
2313 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2314 G->getOffset(), OpFlags);
2316 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2317 unsigned char OpFlags = 0;
2319 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2320 // external symbols should go through the PLT.
2321 if (Subtarget->isTargetELF() &&
2322 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2323 OpFlags = X86II::MO_PLT;
2324 } else if (Subtarget->isPICStyleStubAny() &&
2325 (!Subtarget->getTargetTriple().isMacOSX() ||
2326 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2327 // PC-relative references to external symbols should go through $stub,
2328 // unless we're building with the leopard linker or later, which
2329 // automatically synthesizes these stubs.
2330 OpFlags = X86II::MO_DARWIN_STUB;
2333 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2337 // Returns a chain & a flag for retval copy to use.
2338 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2339 SmallVector<SDValue, 8> Ops;
2341 if (!IsSibcall && isTailCall) {
2342 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2343 DAG.getIntPtrConstant(0, true), InFlag);
2344 InFlag = Chain.getValue(1);
2347 Ops.push_back(Chain);
2348 Ops.push_back(Callee);
2351 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2353 // Add argument registers to the end of the list so that they are known live
2355 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2356 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2357 RegsToPass[i].second.getValueType()));
2359 // Add an implicit use GOT pointer in EBX.
2360 if (!isTailCall && Subtarget->isPICStyleGOT())
2361 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2363 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2364 if (Is64Bit && isVarArg && !IsWin64)
2365 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2367 if (InFlag.getNode())
2368 Ops.push_back(InFlag);
2372 //// If this is the first return lowered for this function, add the regs
2373 //// to the liveout set for the function.
2374 // This isn't right, although it's probably harmless on x86; liveouts
2375 // should be computed from returns not tail calls. Consider a void
2376 // function making a tail call to a function returning int.
2377 return DAG.getNode(X86ISD::TC_RETURN, dl,
2378 NodeTys, &Ops[0], Ops.size());
2381 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2382 InFlag = Chain.getValue(1);
2384 // Create the CALLSEQ_END node.
2385 unsigned NumBytesForCalleeToPush;
2386 if (Subtarget->IsCalleePop(isVarArg, CallConv))
2387 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2388 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2389 // If this is a call to a struct-return function, the callee
2390 // pops the hidden struct pointer, so we have to push it back.
2391 // This is common for Darwin/X86, Linux & Mingw32 targets.
2392 NumBytesForCalleeToPush = 4;
2394 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2396 // Returns a flag for retval copy to use.
2398 Chain = DAG.getCALLSEQ_END(Chain,
2399 DAG.getIntPtrConstant(NumBytes, true),
2400 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2403 InFlag = Chain.getValue(1);
2406 // Handle result values, copying them out of physregs into vregs that we
2408 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2409 Ins, dl, DAG, InVals);
2413 //===----------------------------------------------------------------------===//
2414 // Fast Calling Convention (tail call) implementation
2415 //===----------------------------------------------------------------------===//
2417 // Like std call, callee cleans arguments, convention except that ECX is
2418 // reserved for storing the tail called function address. Only 2 registers are
2419 // free for argument passing (inreg). Tail call optimization is performed
2421 // * tailcallopt is enabled
2422 // * caller/callee are fastcc
2423 // On X86_64 architecture with GOT-style position independent code only local
2424 // (within module) calls are supported at the moment.
2425 // To keep the stack aligned according to platform abi the function
2426 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2427 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2428 // If a tail called function callee has more arguments than the caller the
2429 // caller needs to make sure that there is room to move the RETADDR to. This is
2430 // achieved by reserving an area the size of the argument delta right after the
2431 // original REtADDR, but before the saved framepointer or the spilled registers
2432 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2444 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2445 /// for a 16 byte align requirement.
2447 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2448 SelectionDAG& DAG) const {
2449 MachineFunction &MF = DAG.getMachineFunction();
2450 const TargetMachine &TM = MF.getTarget();
2451 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2452 unsigned StackAlignment = TFI.getStackAlignment();
2453 uint64_t AlignMask = StackAlignment - 1;
2454 int64_t Offset = StackSize;
2455 uint64_t SlotSize = TD->getPointerSize();
2456 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2457 // Number smaller than 12 so just add the difference.
2458 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2460 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2461 Offset = ((~AlignMask) & Offset) + StackAlignment +
2462 (StackAlignment-SlotSize);
2467 /// HandleByVal - Every parameter *after* a byval parameter is passed
2468 /// on the stack. Remember the next parameter register to allocate,
2469 /// and then confiscate the rest of the parameter registers to insure
2472 llvm::X86TargetLowering::HandleByVal(CCState *State, unsigned &size) const {
2473 if (!Subtarget->is64Bit())
2476 if (size == 0 || size > 16)
2479 int RegsRequired = (size > 8) ? 2 : 1;
2481 static const unsigned GPR64ArgRegs64Bit[] = {
2482 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2484 unsigned NextRegToAlloc = State->getFirstUnallocated(GPR64ArgRegs64Bit, 6);
2486 // If insufficient registers available
2487 if (NextRegToAlloc + RegsRequired > 6)
2490 size = 0; // Tell caller not to allocate stack.
2492 unsigned reg = State->AllocateReg(GPR64ArgRegs64Bit, 6);
2493 State->setFirstByValReg(reg);
2495 if (RegsRequired == 2) {
2496 State->AllocateReg(GPR64ArgRegs64Bit, 6);
2500 /// MatchingStackOffset - Return true if the given stack call argument is
2501 /// already available in the same position (relatively) of the caller's
2502 /// incoming argument stack.
2504 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2505 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2506 const X86InstrInfo *TII) {
2507 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2509 if (Arg.getOpcode() == ISD::CopyFromReg) {
2510 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2511 if (!TargetRegisterInfo::isVirtualRegister(VR))
2513 MachineInstr *Def = MRI->getVRegDef(VR);
2516 if (!Flags.isByVal()) {
2517 if (!TII->isLoadFromStackSlot(Def, FI))
2520 unsigned Opcode = Def->getOpcode();
2521 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2522 Def->getOperand(1).isFI()) {
2523 FI = Def->getOperand(1).getIndex();
2524 Bytes = Flags.getByValSize();
2528 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2529 if (Flags.isByVal())
2530 // ByVal argument is passed in as a pointer but it's now being
2531 // dereferenced. e.g.
2532 // define @foo(%struct.X* %A) {
2533 // tail call @bar(%struct.X* byval %A)
2536 SDValue Ptr = Ld->getBasePtr();
2537 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2540 FI = FINode->getIndex();
2544 assert(FI != INT_MAX);
2545 if (!MFI->isFixedObjectIndex(FI))
2547 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2550 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2551 /// for tail call optimization. Targets which want to do tail call
2552 /// optimization should implement this function.
2554 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2555 CallingConv::ID CalleeCC,
2557 bool isCalleeStructRet,
2558 bool isCallerStructRet,
2559 const SmallVectorImpl<ISD::OutputArg> &Outs,
2560 const SmallVectorImpl<SDValue> &OutVals,
2561 const SmallVectorImpl<ISD::InputArg> &Ins,
2562 SelectionDAG& DAG) const {
2563 if (!IsTailCallConvention(CalleeCC) &&
2564 CalleeCC != CallingConv::C)
2567 // If -tailcallopt is specified, make fastcc functions tail-callable.
2568 const MachineFunction &MF = DAG.getMachineFunction();
2569 const Function *CallerF = DAG.getMachineFunction().getFunction();
2570 CallingConv::ID CallerCC = CallerF->getCallingConv();
2571 bool CCMatch = CallerCC == CalleeCC;
2573 if (GuaranteedTailCallOpt) {
2574 if (IsTailCallConvention(CalleeCC) && CCMatch)
2579 // Look for obvious safe cases to perform tail call optimization that do not
2580 // require ABI changes. This is what gcc calls sibcall.
2582 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2583 // emit a special epilogue.
2584 if (RegInfo->needsStackRealignment(MF))
2587 // Also avoid sibcall optimization if either caller or callee uses struct
2588 // return semantics.
2589 if (isCalleeStructRet || isCallerStructRet)
2592 // Do not sibcall optimize vararg calls unless all arguments are passed via
2594 if (isVarArg && !Outs.empty()) {
2596 // Optimizing for varargs on Win64 is unlikely to be safe without
2597 // additional testing.
2598 if (Subtarget->isTargetWin64())
2601 SmallVector<CCValAssign, 16> ArgLocs;
2602 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2603 ArgLocs, *DAG.getContext());
2605 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2606 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2607 if (!ArgLocs[i].isRegLoc())
2611 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2612 // Therefore if it's not used by the call it is not safe to optimize this into
2614 bool Unused = false;
2615 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2622 SmallVector<CCValAssign, 16> RVLocs;
2623 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2624 RVLocs, *DAG.getContext());
2625 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2626 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2627 CCValAssign &VA = RVLocs[i];
2628 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2633 // If the calling conventions do not match, then we'd better make sure the
2634 // results are returned in the same way as what the caller expects.
2636 SmallVector<CCValAssign, 16> RVLocs1;
2637 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2638 RVLocs1, *DAG.getContext());
2639 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2641 SmallVector<CCValAssign, 16> RVLocs2;
2642 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2643 RVLocs2, *DAG.getContext());
2644 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2646 if (RVLocs1.size() != RVLocs2.size())
2648 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2649 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2651 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2653 if (RVLocs1[i].isRegLoc()) {
2654 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2657 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2663 // If the callee takes no arguments then go on to check the results of the
2665 if (!Outs.empty()) {
2666 // Check if stack adjustment is needed. For now, do not do this if any
2667 // argument is passed on the stack.
2668 SmallVector<CCValAssign, 16> ArgLocs;
2669 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2670 ArgLocs, *DAG.getContext());
2672 // Allocate shadow area for Win64
2673 if (Subtarget->isTargetWin64()) {
2674 CCInfo.AllocateStack(32, 8);
2677 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2678 if (CCInfo.getNextStackOffset()) {
2679 MachineFunction &MF = DAG.getMachineFunction();
2680 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2683 // Check if the arguments are already laid out in the right way as
2684 // the caller's fixed stack objects.
2685 MachineFrameInfo *MFI = MF.getFrameInfo();
2686 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2687 const X86InstrInfo *TII =
2688 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2689 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2690 CCValAssign &VA = ArgLocs[i];
2691 SDValue Arg = OutVals[i];
2692 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2693 if (VA.getLocInfo() == CCValAssign::Indirect)
2695 if (!VA.isRegLoc()) {
2696 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2703 // If the tailcall address may be in a register, then make sure it's
2704 // possible to register allocate for it. In 32-bit, the call address can
2705 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2706 // callee-saved registers are restored. These happen to be the same
2707 // registers used to pass 'inreg' arguments so watch out for those.
2708 if (!Subtarget->is64Bit() &&
2709 !isa<GlobalAddressSDNode>(Callee) &&
2710 !isa<ExternalSymbolSDNode>(Callee)) {
2711 unsigned NumInRegs = 0;
2712 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2713 CCValAssign &VA = ArgLocs[i];
2716 unsigned Reg = VA.getLocReg();
2719 case X86::EAX: case X86::EDX: case X86::ECX:
2720 if (++NumInRegs == 3)
2728 // An stdcall caller is expected to clean up its arguments; the callee
2729 // isn't going to do that.
2730 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2737 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2738 return X86::createFastISel(funcInfo);
2742 //===----------------------------------------------------------------------===//
2743 // Other Lowering Hooks
2744 //===----------------------------------------------------------------------===//
2746 static bool MayFoldLoad(SDValue Op) {
2747 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2750 static bool MayFoldIntoStore(SDValue Op) {
2751 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2754 static bool isTargetShuffle(unsigned Opcode) {
2756 default: return false;
2757 case X86ISD::PSHUFD:
2758 case X86ISD::PSHUFHW:
2759 case X86ISD::PSHUFLW:
2760 case X86ISD::SHUFPD:
2761 case X86ISD::PALIGN:
2762 case X86ISD::SHUFPS:
2763 case X86ISD::MOVLHPS:
2764 case X86ISD::MOVLHPD:
2765 case X86ISD::MOVHLPS:
2766 case X86ISD::MOVLPS:
2767 case X86ISD::MOVLPD:
2768 case X86ISD::MOVSHDUP:
2769 case X86ISD::MOVSLDUP:
2770 case X86ISD::MOVDDUP:
2773 case X86ISD::UNPCKLPS:
2774 case X86ISD::UNPCKLPD:
2775 case X86ISD::VUNPCKLPS:
2776 case X86ISD::VUNPCKLPD:
2777 case X86ISD::VUNPCKLPSY:
2778 case X86ISD::VUNPCKLPDY:
2779 case X86ISD::PUNPCKLWD:
2780 case X86ISD::PUNPCKLBW:
2781 case X86ISD::PUNPCKLDQ:
2782 case X86ISD::PUNPCKLQDQ:
2783 case X86ISD::UNPCKHPS:
2784 case X86ISD::UNPCKHPD:
2785 case X86ISD::PUNPCKHWD:
2786 case X86ISD::PUNPCKHBW:
2787 case X86ISD::PUNPCKHDQ:
2788 case X86ISD::PUNPCKHQDQ:
2794 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2795 SDValue V1, SelectionDAG &DAG) {
2797 default: llvm_unreachable("Unknown x86 shuffle node");
2798 case X86ISD::MOVSHDUP:
2799 case X86ISD::MOVSLDUP:
2800 case X86ISD::MOVDDUP:
2801 return DAG.getNode(Opc, dl, VT, V1);
2807 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2808 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2810 default: llvm_unreachable("Unknown x86 shuffle node");
2811 case X86ISD::PSHUFD:
2812 case X86ISD::PSHUFHW:
2813 case X86ISD::PSHUFLW:
2814 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2820 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2821 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2823 default: llvm_unreachable("Unknown x86 shuffle node");
2824 case X86ISD::PALIGN:
2825 case X86ISD::SHUFPD:
2826 case X86ISD::SHUFPS:
2827 return DAG.getNode(Opc, dl, VT, V1, V2,
2828 DAG.getConstant(TargetMask, MVT::i8));
2833 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2834 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2836 default: llvm_unreachable("Unknown x86 shuffle node");
2837 case X86ISD::MOVLHPS:
2838 case X86ISD::MOVLHPD:
2839 case X86ISD::MOVHLPS:
2840 case X86ISD::MOVLPS:
2841 case X86ISD::MOVLPD:
2844 case X86ISD::UNPCKLPS:
2845 case X86ISD::UNPCKLPD:
2846 case X86ISD::VUNPCKLPS:
2847 case X86ISD::VUNPCKLPD:
2848 case X86ISD::VUNPCKLPSY:
2849 case X86ISD::VUNPCKLPDY:
2850 case X86ISD::PUNPCKLWD:
2851 case X86ISD::PUNPCKLBW:
2852 case X86ISD::PUNPCKLDQ:
2853 case X86ISD::PUNPCKLQDQ:
2854 case X86ISD::UNPCKHPS:
2855 case X86ISD::UNPCKHPD:
2856 case X86ISD::PUNPCKHWD:
2857 case X86ISD::PUNPCKHBW:
2858 case X86ISD::PUNPCKHDQ:
2859 case X86ISD::PUNPCKHQDQ:
2860 return DAG.getNode(Opc, dl, VT, V1, V2);
2865 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2866 MachineFunction &MF = DAG.getMachineFunction();
2867 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2868 int ReturnAddrIndex = FuncInfo->getRAIndex();
2870 if (ReturnAddrIndex == 0) {
2871 // Set up a frame object for the return address.
2872 uint64_t SlotSize = TD->getPointerSize();
2873 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2875 FuncInfo->setRAIndex(ReturnAddrIndex);
2878 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2882 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2883 bool hasSymbolicDisplacement) {
2884 // Offset should fit into 32 bit immediate field.
2885 if (!isInt<32>(Offset))
2888 // If we don't have a symbolic displacement - we don't have any extra
2890 if (!hasSymbolicDisplacement)
2893 // FIXME: Some tweaks might be needed for medium code model.
2894 if (M != CodeModel::Small && M != CodeModel::Kernel)
2897 // For small code model we assume that latest object is 16MB before end of 31
2898 // bits boundary. We may also accept pretty large negative constants knowing
2899 // that all objects are in the positive half of address space.
2900 if (M == CodeModel::Small && Offset < 16*1024*1024)
2903 // For kernel code model we know that all object resist in the negative half
2904 // of 32bits address space. We may not accept negative offsets, since they may
2905 // be just off and we may accept pretty large positive ones.
2906 if (M == CodeModel::Kernel && Offset > 0)
2912 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2913 /// specific condition code, returning the condition code and the LHS/RHS of the
2914 /// comparison to make.
2915 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2916 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2918 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2919 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2920 // X > -1 -> X == 0, jump !sign.
2921 RHS = DAG.getConstant(0, RHS.getValueType());
2922 return X86::COND_NS;
2923 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2924 // X < 0 -> X == 0, jump on sign.
2926 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2928 RHS = DAG.getConstant(0, RHS.getValueType());
2929 return X86::COND_LE;
2933 switch (SetCCOpcode) {
2934 default: llvm_unreachable("Invalid integer condition!");
2935 case ISD::SETEQ: return X86::COND_E;
2936 case ISD::SETGT: return X86::COND_G;
2937 case ISD::SETGE: return X86::COND_GE;
2938 case ISD::SETLT: return X86::COND_L;
2939 case ISD::SETLE: return X86::COND_LE;
2940 case ISD::SETNE: return X86::COND_NE;
2941 case ISD::SETULT: return X86::COND_B;
2942 case ISD::SETUGT: return X86::COND_A;
2943 case ISD::SETULE: return X86::COND_BE;
2944 case ISD::SETUGE: return X86::COND_AE;
2948 // First determine if it is required or is profitable to flip the operands.
2950 // If LHS is a foldable load, but RHS is not, flip the condition.
2951 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2952 !ISD::isNON_EXTLoad(RHS.getNode())) {
2953 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2954 std::swap(LHS, RHS);
2957 switch (SetCCOpcode) {
2963 std::swap(LHS, RHS);
2967 // On a floating point condition, the flags are set as follows:
2969 // 0 | 0 | 0 | X > Y
2970 // 0 | 0 | 1 | X < Y
2971 // 1 | 0 | 0 | X == Y
2972 // 1 | 1 | 1 | unordered
2973 switch (SetCCOpcode) {
2974 default: llvm_unreachable("Condcode should be pre-legalized away");
2976 case ISD::SETEQ: return X86::COND_E;
2977 case ISD::SETOLT: // flipped
2979 case ISD::SETGT: return X86::COND_A;
2980 case ISD::SETOLE: // flipped
2982 case ISD::SETGE: return X86::COND_AE;
2983 case ISD::SETUGT: // flipped
2985 case ISD::SETLT: return X86::COND_B;
2986 case ISD::SETUGE: // flipped
2988 case ISD::SETLE: return X86::COND_BE;
2990 case ISD::SETNE: return X86::COND_NE;
2991 case ISD::SETUO: return X86::COND_P;
2992 case ISD::SETO: return X86::COND_NP;
2994 case ISD::SETUNE: return X86::COND_INVALID;
2998 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2999 /// code. Current x86 isa includes the following FP cmov instructions:
3000 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3001 static bool hasFPCMov(unsigned X86CC) {
3017 /// isFPImmLegal - Returns true if the target can instruction select the
3018 /// specified FP immediate natively. If false, the legalizer will
3019 /// materialize the FP immediate as a load from a constant pool.
3020 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3021 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3022 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3028 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3029 /// the specified range (L, H].
3030 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3031 return (Val < 0) || (Val >= Low && Val < Hi);
3034 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3035 /// specified value.
3036 static bool isUndefOrEqual(int Val, int CmpVal) {
3037 if (Val < 0 || Val == CmpVal)
3042 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3043 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3044 /// the second operand.
3045 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3046 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3047 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3048 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3049 return (Mask[0] < 2 && Mask[1] < 2);
3053 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3054 SmallVector<int, 8> M;
3056 return ::isPSHUFDMask(M, N->getValueType(0));
3059 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3060 /// is suitable for input to PSHUFHW.
3061 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3062 if (VT != MVT::v8i16)
3065 // Lower quadword copied in order or undef.
3066 for (int i = 0; i != 4; ++i)
3067 if (Mask[i] >= 0 && Mask[i] != i)
3070 // Upper quadword shuffled.
3071 for (int i = 4; i != 8; ++i)
3072 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3078 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3079 SmallVector<int, 8> M;
3081 return ::isPSHUFHWMask(M, N->getValueType(0));
3084 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3085 /// is suitable for input to PSHUFLW.
3086 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3087 if (VT != MVT::v8i16)
3090 // Upper quadword copied in order.
3091 for (int i = 4; i != 8; ++i)
3092 if (Mask[i] >= 0 && Mask[i] != i)
3095 // Lower quadword shuffled.
3096 for (int i = 0; i != 4; ++i)
3103 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3104 SmallVector<int, 8> M;
3106 return ::isPSHUFLWMask(M, N->getValueType(0));
3109 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3110 /// is suitable for input to PALIGNR.
3111 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3113 int i, e = VT.getVectorNumElements();
3115 // Do not handle v2i64 / v2f64 shuffles with palignr.
3116 if (e < 4 || !hasSSSE3)
3119 for (i = 0; i != e; ++i)
3123 // All undef, not a palignr.
3127 // Determine if it's ok to perform a palignr with only the LHS, since we
3128 // don't have access to the actual shuffle elements to see if RHS is undef.
3129 bool Unary = Mask[i] < (int)e;
3130 bool NeedsUnary = false;
3132 int s = Mask[i] - i;
3134 // Check the rest of the elements to see if they are consecutive.
3135 for (++i; i != e; ++i) {
3140 Unary = Unary && (m < (int)e);
3141 NeedsUnary = NeedsUnary || (m < s);
3143 if (NeedsUnary && !Unary)
3145 if (Unary && m != ((s+i) & (e-1)))
3147 if (!Unary && m != (s+i))
3153 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3154 SmallVector<int, 8> M;
3156 return ::isPALIGNRMask(M, N->getValueType(0), true);
3159 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3160 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3161 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3162 int NumElems = VT.getVectorNumElements();
3163 if (NumElems != 2 && NumElems != 4)
3166 int Half = NumElems / 2;
3167 for (int i = 0; i < Half; ++i)
3168 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3170 for (int i = Half; i < NumElems; ++i)
3171 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3177 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3178 SmallVector<int, 8> M;
3180 return ::isSHUFPMask(M, N->getValueType(0));
3183 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3184 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3185 /// half elements to come from vector 1 (which would equal the dest.) and
3186 /// the upper half to come from vector 2.
3187 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3188 int NumElems = VT.getVectorNumElements();
3190 if (NumElems != 2 && NumElems != 4)
3193 int Half = NumElems / 2;
3194 for (int i = 0; i < Half; ++i)
3195 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3197 for (int i = Half; i < NumElems; ++i)
3198 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3203 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3204 SmallVector<int, 8> M;
3206 return isCommutedSHUFPMask(M, N->getValueType(0));
3209 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3210 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3211 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3212 if (N->getValueType(0).getVectorNumElements() != 4)
3215 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3216 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3217 isUndefOrEqual(N->getMaskElt(1), 7) &&
3218 isUndefOrEqual(N->getMaskElt(2), 2) &&
3219 isUndefOrEqual(N->getMaskElt(3), 3);
3222 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3223 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3225 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3226 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3231 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3232 isUndefOrEqual(N->getMaskElt(1), 3) &&
3233 isUndefOrEqual(N->getMaskElt(2), 2) &&
3234 isUndefOrEqual(N->getMaskElt(3), 3);
3237 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3238 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3239 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3240 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3242 if (NumElems != 2 && NumElems != 4)
3245 for (unsigned i = 0; i < NumElems/2; ++i)
3246 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3249 for (unsigned i = NumElems/2; i < NumElems; ++i)
3250 if (!isUndefOrEqual(N->getMaskElt(i), i))
3256 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3257 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3258 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3259 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3261 if ((NumElems != 2 && NumElems != 4)
3262 || N->getValueType(0).getSizeInBits() > 128)
3265 for (unsigned i = 0; i < NumElems/2; ++i)
3266 if (!isUndefOrEqual(N->getMaskElt(i), i))
3269 for (unsigned i = 0; i < NumElems/2; ++i)
3270 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3276 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3277 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3278 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3279 bool V2IsSplat = false) {
3280 int NumElts = VT.getVectorNumElements();
3281 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3284 // Handle vector lengths > 128 bits. Define a "section" as a set of
3285 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3287 unsigned NumSections = VT.getSizeInBits() / 128;
3288 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3289 unsigned NumSectionElts = NumElts / NumSections;
3292 unsigned End = NumSectionElts;
3293 for (unsigned s = 0; s < NumSections; ++s) {
3294 for (unsigned i = Start, j = s * NumSectionElts;
3298 int BitI1 = Mask[i+1];
3299 if (!isUndefOrEqual(BitI, j))
3302 if (!isUndefOrEqual(BitI1, NumElts))
3305 if (!isUndefOrEqual(BitI1, j + NumElts))
3309 // Process the next 128 bits.
3310 Start += NumSectionElts;
3311 End += NumSectionElts;
3317 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3318 SmallVector<int, 8> M;
3320 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3323 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3324 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3325 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3326 bool V2IsSplat = false) {
3327 int NumElts = VT.getVectorNumElements();
3328 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3331 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3333 int BitI1 = Mask[i+1];
3334 if (!isUndefOrEqual(BitI, j + NumElts/2))
3337 if (isUndefOrEqual(BitI1, NumElts))
3340 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3347 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3348 SmallVector<int, 8> M;
3350 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3353 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3354 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3356 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3357 int NumElems = VT.getVectorNumElements();
3358 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3361 // Handle vector lengths > 128 bits. Define a "section" as a set of
3362 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3364 unsigned NumSections = VT.getSizeInBits() / 128;
3365 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3366 unsigned NumSectionElts = NumElems / NumSections;
3368 for (unsigned s = 0; s < NumSections; ++s) {
3369 for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3370 i != NumSectionElts * (s + 1);
3373 int BitI1 = Mask[i+1];
3375 if (!isUndefOrEqual(BitI, j))
3377 if (!isUndefOrEqual(BitI1, j))
3385 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3386 SmallVector<int, 8> M;
3388 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3391 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3392 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3394 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3395 int NumElems = VT.getVectorNumElements();
3396 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3399 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3401 int BitI1 = Mask[i+1];
3402 if (!isUndefOrEqual(BitI, j))
3404 if (!isUndefOrEqual(BitI1, j))
3410 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3411 SmallVector<int, 8> M;
3413 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3416 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3417 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3418 /// MOVSD, and MOVD, i.e. setting the lowest element.
3419 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3420 if (VT.getVectorElementType().getSizeInBits() < 32)
3423 int NumElts = VT.getVectorNumElements();
3425 if (!isUndefOrEqual(Mask[0], NumElts))
3428 for (int i = 1; i < NumElts; ++i)
3429 if (!isUndefOrEqual(Mask[i], i))
3435 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3436 SmallVector<int, 8> M;
3438 return ::isMOVLMask(M, N->getValueType(0));
3441 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3442 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3443 /// element of vector 2 and the other elements to come from vector 1 in order.
3444 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3445 bool V2IsSplat = false, bool V2IsUndef = false) {
3446 int NumOps = VT.getVectorNumElements();
3447 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3450 if (!isUndefOrEqual(Mask[0], 0))
3453 for (int i = 1; i < NumOps; ++i)
3454 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3455 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3456 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3462 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3463 bool V2IsUndef = false) {
3464 SmallVector<int, 8> M;
3466 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3469 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3470 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3471 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3472 if (N->getValueType(0).getVectorNumElements() != 4)
3475 // Expect 1, 1, 3, 3
3476 for (unsigned i = 0; i < 2; ++i) {
3477 int Elt = N->getMaskElt(i);
3478 if (Elt >= 0 && Elt != 1)
3483 for (unsigned i = 2; i < 4; ++i) {
3484 int Elt = N->getMaskElt(i);
3485 if (Elt >= 0 && Elt != 3)
3490 // Don't use movshdup if it can be done with a shufps.
3491 // FIXME: verify that matching u, u, 3, 3 is what we want.
3495 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3496 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3497 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3498 if (N->getValueType(0).getVectorNumElements() != 4)
3501 // Expect 0, 0, 2, 2
3502 for (unsigned i = 0; i < 2; ++i)
3503 if (N->getMaskElt(i) > 0)
3507 for (unsigned i = 2; i < 4; ++i) {
3508 int Elt = N->getMaskElt(i);
3509 if (Elt >= 0 && Elt != 2)
3514 // Don't use movsldup if it can be done with a shufps.
3518 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3519 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3520 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3521 int e = N->getValueType(0).getVectorNumElements() / 2;
3523 for (int i = 0; i < e; ++i)
3524 if (!isUndefOrEqual(N->getMaskElt(i), i))
3526 for (int i = 0; i < e; ++i)
3527 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3532 /// isVEXTRACTF128Index - Return true if the specified
3533 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3534 /// suitable for input to VEXTRACTF128.
3535 bool X86::isVEXTRACTF128Index(SDNode *N) {
3536 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3539 // The index should be aligned on a 128-bit boundary.
3541 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3543 unsigned VL = N->getValueType(0).getVectorNumElements();
3544 unsigned VBits = N->getValueType(0).getSizeInBits();
3545 unsigned ElSize = VBits / VL;
3546 bool Result = (Index * ElSize) % 128 == 0;
3551 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3552 /// operand specifies a subvector insert that is suitable for input to
3554 bool X86::isVINSERTF128Index(SDNode *N) {
3555 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3558 // The index should be aligned on a 128-bit boundary.
3560 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3562 unsigned VL = N->getValueType(0).getVectorNumElements();
3563 unsigned VBits = N->getValueType(0).getSizeInBits();
3564 unsigned ElSize = VBits / VL;
3565 bool Result = (Index * ElSize) % 128 == 0;
3570 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3571 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3572 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3573 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3574 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3576 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3578 for (int i = 0; i < NumOperands; ++i) {
3579 int Val = SVOp->getMaskElt(NumOperands-i-1);
3580 if (Val < 0) Val = 0;
3581 if (Val >= NumOperands) Val -= NumOperands;
3583 if (i != NumOperands - 1)
3589 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3590 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3591 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3592 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3594 // 8 nodes, but we only care about the last 4.
3595 for (unsigned i = 7; i >= 4; --i) {
3596 int Val = SVOp->getMaskElt(i);
3605 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3606 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3607 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3608 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3610 // 8 nodes, but we only care about the first 4.
3611 for (int i = 3; i >= 0; --i) {
3612 int Val = SVOp->getMaskElt(i);
3621 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3622 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3623 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3624 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3625 EVT VVT = N->getValueType(0);
3626 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3630 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3631 Val = SVOp->getMaskElt(i);
3635 return (Val - i) * EltSize;
3638 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3639 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3641 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3642 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3643 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3646 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3648 EVT VecVT = N->getOperand(0).getValueType();
3649 EVT ElVT = VecVT.getVectorElementType();
3651 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3653 return Index / NumElemsPerChunk;
3656 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3657 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3659 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3660 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3661 llvm_unreachable("Illegal insert subvector for VINSERTF128");
3664 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3666 EVT VecVT = N->getValueType(0);
3667 EVT ElVT = VecVT.getVectorElementType();
3669 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3671 return Index / NumElemsPerChunk;
3674 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3676 bool X86::isZeroNode(SDValue Elt) {
3677 return ((isa<ConstantSDNode>(Elt) &&
3678 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3679 (isa<ConstantFPSDNode>(Elt) &&
3680 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3683 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3684 /// their permute mask.
3685 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3686 SelectionDAG &DAG) {
3687 EVT VT = SVOp->getValueType(0);
3688 unsigned NumElems = VT.getVectorNumElements();
3689 SmallVector<int, 8> MaskVec;
3691 for (unsigned i = 0; i != NumElems; ++i) {
3692 int idx = SVOp->getMaskElt(i);
3694 MaskVec.push_back(idx);
3695 else if (idx < (int)NumElems)
3696 MaskVec.push_back(idx + NumElems);
3698 MaskVec.push_back(idx - NumElems);
3700 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3701 SVOp->getOperand(0), &MaskVec[0]);
3704 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3705 /// the two vector operands have swapped position.
3706 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3707 unsigned NumElems = VT.getVectorNumElements();
3708 for (unsigned i = 0; i != NumElems; ++i) {
3712 else if (idx < (int)NumElems)
3713 Mask[i] = idx + NumElems;
3715 Mask[i] = idx - NumElems;
3719 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3720 /// match movhlps. The lower half elements should come from upper half of
3721 /// V1 (and in order), and the upper half elements should come from the upper
3722 /// half of V2 (and in order).
3723 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3724 if (Op->getValueType(0).getVectorNumElements() != 4)
3726 for (unsigned i = 0, e = 2; i != e; ++i)
3727 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3729 for (unsigned i = 2; i != 4; ++i)
3730 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3735 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3736 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3738 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3739 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3741 N = N->getOperand(0).getNode();
3742 if (!ISD::isNON_EXTLoad(N))
3745 *LD = cast<LoadSDNode>(N);
3749 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3750 /// match movlp{s|d}. The lower half elements should come from lower half of
3751 /// V1 (and in order), and the upper half elements should come from the upper
3752 /// half of V2 (and in order). And since V1 will become the source of the
3753 /// MOVLP, it must be either a vector load or a scalar load to vector.
3754 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3755 ShuffleVectorSDNode *Op) {
3756 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3758 // Is V2 is a vector load, don't do this transformation. We will try to use
3759 // load folding shufps op.
3760 if (ISD::isNON_EXTLoad(V2))
3763 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3765 if (NumElems != 2 && NumElems != 4)
3767 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3768 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3770 for (unsigned i = NumElems/2; i != NumElems; ++i)
3771 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3776 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3778 static bool isSplatVector(SDNode *N) {
3779 if (N->getOpcode() != ISD::BUILD_VECTOR)
3782 SDValue SplatValue = N->getOperand(0);
3783 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3784 if (N->getOperand(i) != SplatValue)
3789 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3790 /// to an zero vector.
3791 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3792 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3793 SDValue V1 = N->getOperand(0);
3794 SDValue V2 = N->getOperand(1);
3795 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3796 for (unsigned i = 0; i != NumElems; ++i) {
3797 int Idx = N->getMaskElt(i);
3798 if (Idx >= (int)NumElems) {
3799 unsigned Opc = V2.getOpcode();
3800 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3802 if (Opc != ISD::BUILD_VECTOR ||
3803 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3805 } else if (Idx >= 0) {
3806 unsigned Opc = V1.getOpcode();
3807 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3809 if (Opc != ISD::BUILD_VECTOR ||
3810 !X86::isZeroNode(V1.getOperand(Idx)))
3817 /// getZeroVector - Returns a vector of specified type with all zero elements.
3819 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3821 assert(VT.isVector() && "Expected a vector type");
3823 // Always build SSE zero vectors as <4 x i32> bitcasted
3824 // to their dest type. This ensures they get CSE'd.
3826 if (VT.getSizeInBits() == 128) { // SSE
3827 if (HasSSE2) { // SSE2
3828 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3829 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3831 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3832 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3834 } else if (VT.getSizeInBits() == 256) { // AVX
3835 // 256-bit logic and arithmetic instructions in AVX are
3836 // all floating-point, no support for integer ops. Default
3837 // to emitting fp zeroed vectors then.
3838 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3839 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3840 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3842 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3845 /// getOnesVector - Returns a vector of specified type with all bits set.
3847 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3848 assert(VT.isVector() && "Expected a vector type");
3850 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3851 // type. This ensures they get CSE'd.
3852 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3854 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3855 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3859 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3860 /// that point to V2 points to its first element.
3861 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3862 EVT VT = SVOp->getValueType(0);
3863 unsigned NumElems = VT.getVectorNumElements();
3865 bool Changed = false;
3866 SmallVector<int, 8> MaskVec;
3867 SVOp->getMask(MaskVec);
3869 for (unsigned i = 0; i != NumElems; ++i) {
3870 if (MaskVec[i] > (int)NumElems) {
3871 MaskVec[i] = NumElems;
3876 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3877 SVOp->getOperand(1), &MaskVec[0]);
3878 return SDValue(SVOp, 0);
3881 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3882 /// operation of specified width.
3883 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3885 unsigned NumElems = VT.getVectorNumElements();
3886 SmallVector<int, 8> Mask;
3887 Mask.push_back(NumElems);
3888 for (unsigned i = 1; i != NumElems; ++i)
3890 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3893 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3894 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3896 unsigned NumElems = VT.getVectorNumElements();
3897 SmallVector<int, 8> Mask;
3898 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3900 Mask.push_back(i + NumElems);
3902 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3905 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3906 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3908 unsigned NumElems = VT.getVectorNumElements();
3909 unsigned Half = NumElems/2;
3910 SmallVector<int, 8> Mask;
3911 for (unsigned i = 0; i != Half; ++i) {
3912 Mask.push_back(i + Half);
3913 Mask.push_back(i + NumElems + Half);
3915 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3918 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3919 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3920 EVT PVT = MVT::v4f32;
3921 EVT VT = SV->getValueType(0);
3922 DebugLoc dl = SV->getDebugLoc();
3923 SDValue V1 = SV->getOperand(0);
3924 int NumElems = VT.getVectorNumElements();
3925 int EltNo = SV->getSplatIndex();
3927 // unpack elements to the correct location
3928 while (NumElems > 4) {
3929 if (EltNo < NumElems/2) {
3930 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3932 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3933 EltNo -= NumElems/2;
3938 // Perform the splat.
3939 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3940 V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3941 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3942 return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3945 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3946 /// vector of zero or undef vector. This produces a shuffle where the low
3947 /// element of V2 is swizzled into the zero/undef vector, landing at element
3948 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3949 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3950 bool isZero, bool HasSSE2,
3951 SelectionDAG &DAG) {
3952 EVT VT = V2.getValueType();
3954 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3955 unsigned NumElems = VT.getVectorNumElements();
3956 SmallVector<int, 16> MaskVec;
3957 for (unsigned i = 0; i != NumElems; ++i)
3958 // If this is the insertion idx, put the low elt of V2 here.
3959 MaskVec.push_back(i == Idx ? NumElems : i);
3960 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3963 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3964 /// element of the result of the vector shuffle.
3965 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3968 return SDValue(); // Limit search depth.
3970 SDValue V = SDValue(N, 0);
3971 EVT VT = V.getValueType();
3972 unsigned Opcode = V.getOpcode();
3974 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3975 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3976 Index = SV->getMaskElt(Index);
3979 return DAG.getUNDEF(VT.getVectorElementType());
3981 int NumElems = VT.getVectorNumElements();
3982 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3983 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3986 // Recurse into target specific vector shuffles to find scalars.
3987 if (isTargetShuffle(Opcode)) {
3988 int NumElems = VT.getVectorNumElements();
3989 SmallVector<unsigned, 16> ShuffleMask;
3993 case X86ISD::SHUFPS:
3994 case X86ISD::SHUFPD:
3995 ImmN = N->getOperand(N->getNumOperands()-1);
3996 DecodeSHUFPSMask(NumElems,
3997 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4000 case X86ISD::PUNPCKHBW:
4001 case X86ISD::PUNPCKHWD:
4002 case X86ISD::PUNPCKHDQ:
4003 case X86ISD::PUNPCKHQDQ:
4004 DecodePUNPCKHMask(NumElems, ShuffleMask);
4006 case X86ISD::UNPCKHPS:
4007 case X86ISD::UNPCKHPD:
4008 DecodeUNPCKHPMask(NumElems, ShuffleMask);
4010 case X86ISD::PUNPCKLBW:
4011 case X86ISD::PUNPCKLWD:
4012 case X86ISD::PUNPCKLDQ:
4013 case X86ISD::PUNPCKLQDQ:
4014 DecodePUNPCKLMask(VT, ShuffleMask);
4016 case X86ISD::UNPCKLPS:
4017 case X86ISD::UNPCKLPD:
4018 case X86ISD::VUNPCKLPS:
4019 case X86ISD::VUNPCKLPD:
4020 case X86ISD::VUNPCKLPSY:
4021 case X86ISD::VUNPCKLPDY:
4022 DecodeUNPCKLPMask(VT, ShuffleMask);
4024 case X86ISD::MOVHLPS:
4025 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4027 case X86ISD::MOVLHPS:
4028 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4030 case X86ISD::PSHUFD:
4031 ImmN = N->getOperand(N->getNumOperands()-1);
4032 DecodePSHUFMask(NumElems,
4033 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4036 case X86ISD::PSHUFHW:
4037 ImmN = N->getOperand(N->getNumOperands()-1);
4038 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4041 case X86ISD::PSHUFLW:
4042 ImmN = N->getOperand(N->getNumOperands()-1);
4043 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4047 case X86ISD::MOVSD: {
4048 // The index 0 always comes from the first element of the second source,
4049 // this is why MOVSS and MOVSD are used in the first place. The other
4050 // elements come from the other positions of the first source vector.
4051 unsigned OpNum = (Index == 0) ? 1 : 0;
4052 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4056 assert("not implemented for target shuffle node");
4060 Index = ShuffleMask[Index];
4062 return DAG.getUNDEF(VT.getVectorElementType());
4064 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4065 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4069 // Actual nodes that may contain scalar elements
4070 if (Opcode == ISD::BITCAST) {
4071 V = V.getOperand(0);
4072 EVT SrcVT = V.getValueType();
4073 unsigned NumElems = VT.getVectorNumElements();
4075 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4079 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4080 return (Index == 0) ? V.getOperand(0)
4081 : DAG.getUNDEF(VT.getVectorElementType());
4083 if (V.getOpcode() == ISD::BUILD_VECTOR)
4084 return V.getOperand(Index);
4089 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4090 /// shuffle operation which come from a consecutively from a zero. The
4091 /// search can start in two different directions, from left or right.
4093 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4094 bool ZerosFromLeft, SelectionDAG &DAG) {
4097 while (i < NumElems) {
4098 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4099 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4100 if (!(Elt.getNode() &&
4101 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4109 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4110 /// MaskE correspond consecutively to elements from one of the vector operands,
4111 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4113 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4114 int OpIdx, int NumElems, unsigned &OpNum) {
4115 bool SeenV1 = false;
4116 bool SeenV2 = false;
4118 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4119 int Idx = SVOp->getMaskElt(i);
4120 // Ignore undef indicies
4129 // Only accept consecutive elements from the same vector
4130 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4134 OpNum = SeenV1 ? 0 : 1;
4138 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4139 /// logical left shift of a vector.
4140 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4141 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4142 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4143 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4144 false /* check zeros from right */, DAG);
4150 // Considering the elements in the mask that are not consecutive zeros,
4151 // check if they consecutively come from only one of the source vectors.
4153 // V1 = {X, A, B, C} 0
4155 // vector_shuffle V1, V2 <1, 2, 3, X>
4157 if (!isShuffleMaskConsecutive(SVOp,
4158 0, // Mask Start Index
4159 NumElems-NumZeros-1, // Mask End Index
4160 NumZeros, // Where to start looking in the src vector
4161 NumElems, // Number of elements in vector
4162 OpSrc)) // Which source operand ?
4167 ShVal = SVOp->getOperand(OpSrc);
4171 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4172 /// logical left shift of a vector.
4173 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4174 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4175 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4176 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4177 true /* check zeros from left */, DAG);
4183 // Considering the elements in the mask that are not consecutive zeros,
4184 // check if they consecutively come from only one of the source vectors.
4186 // 0 { A, B, X, X } = V2
4188 // vector_shuffle V1, V2 <X, X, 4, 5>
4190 if (!isShuffleMaskConsecutive(SVOp,
4191 NumZeros, // Mask Start Index
4192 NumElems-1, // Mask End Index
4193 0, // Where to start looking in the src vector
4194 NumElems, // Number of elements in vector
4195 OpSrc)) // Which source operand ?
4200 ShVal = SVOp->getOperand(OpSrc);
4204 /// isVectorShift - Returns true if the shuffle can be implemented as a
4205 /// logical left or right shift of a vector.
4206 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4207 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4208 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4209 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4215 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4217 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4218 unsigned NumNonZero, unsigned NumZero,
4220 const TargetLowering &TLI) {
4224 DebugLoc dl = Op.getDebugLoc();
4227 for (unsigned i = 0; i < 16; ++i) {
4228 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4229 if (ThisIsNonZero && First) {
4231 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4233 V = DAG.getUNDEF(MVT::v8i16);
4238 SDValue ThisElt(0, 0), LastElt(0, 0);
4239 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4240 if (LastIsNonZero) {
4241 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4242 MVT::i16, Op.getOperand(i-1));
4244 if (ThisIsNonZero) {
4245 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4246 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4247 ThisElt, DAG.getConstant(8, MVT::i8));
4249 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4253 if (ThisElt.getNode())
4254 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4255 DAG.getIntPtrConstant(i/2));
4259 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4262 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4264 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4265 unsigned NumNonZero, unsigned NumZero,
4267 const TargetLowering &TLI) {
4271 DebugLoc dl = Op.getDebugLoc();
4274 for (unsigned i = 0; i < 8; ++i) {
4275 bool isNonZero = (NonZeros & (1 << i)) != 0;
4279 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4281 V = DAG.getUNDEF(MVT::v8i16);
4284 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4285 MVT::v8i16, V, Op.getOperand(i),
4286 DAG.getIntPtrConstant(i));
4293 /// getVShift - Return a vector logical shift node.
4295 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4296 unsigned NumBits, SelectionDAG &DAG,
4297 const TargetLowering &TLI, DebugLoc dl) {
4298 EVT ShVT = MVT::v2i64;
4299 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4300 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4301 return DAG.getNode(ISD::BITCAST, dl, VT,
4302 DAG.getNode(Opc, dl, ShVT, SrcOp,
4303 DAG.getConstant(NumBits,
4304 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4308 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4309 SelectionDAG &DAG) const {
4311 // Check if the scalar load can be widened into a vector load. And if
4312 // the address is "base + cst" see if the cst can be "absorbed" into
4313 // the shuffle mask.
4314 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4315 SDValue Ptr = LD->getBasePtr();
4316 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4318 EVT PVT = LD->getValueType(0);
4319 if (PVT != MVT::i32 && PVT != MVT::f32)
4324 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4325 FI = FINode->getIndex();
4327 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4328 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4329 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4330 Offset = Ptr.getConstantOperandVal(1);
4331 Ptr = Ptr.getOperand(0);
4336 SDValue Chain = LD->getChain();
4337 // Make sure the stack object alignment is at least 16.
4338 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4339 if (DAG.InferPtrAlignment(Ptr) < 16) {
4340 if (MFI->isFixedObjectIndex(FI)) {
4341 // Can't change the alignment. FIXME: It's possible to compute
4342 // the exact stack offset and reference FI + adjust offset instead.
4343 // If someone *really* cares about this. That's the way to implement it.
4346 MFI->setObjectAlignment(FI, 16);
4350 // (Offset % 16) must be multiple of 4. Then address is then
4351 // Ptr + (Offset & ~15).
4354 if ((Offset % 16) & 3)
4356 int64_t StartOffset = Offset & ~15;
4358 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4359 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4361 int EltNo = (Offset - StartOffset) >> 2;
4362 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4363 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4364 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4365 LD->getPointerInfo().getWithOffset(StartOffset),
4367 // Canonicalize it to a v4i32 shuffle.
4368 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4369 return DAG.getNode(ISD::BITCAST, dl, VT,
4370 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4371 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4377 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4378 /// vector of type 'VT', see if the elements can be replaced by a single large
4379 /// load which has the same value as a build_vector whose operands are 'elts'.
4381 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4383 /// FIXME: we'd also like to handle the case where the last elements are zero
4384 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4385 /// There's even a handy isZeroNode for that purpose.
4386 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4387 DebugLoc &DL, SelectionDAG &DAG) {
4388 EVT EltVT = VT.getVectorElementType();
4389 unsigned NumElems = Elts.size();
4391 LoadSDNode *LDBase = NULL;
4392 unsigned LastLoadedElt = -1U;
4394 // For each element in the initializer, see if we've found a load or an undef.
4395 // If we don't find an initial load element, or later load elements are
4396 // non-consecutive, bail out.
4397 for (unsigned i = 0; i < NumElems; ++i) {
4398 SDValue Elt = Elts[i];
4400 if (!Elt.getNode() ||
4401 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4404 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4406 LDBase = cast<LoadSDNode>(Elt.getNode());
4410 if (Elt.getOpcode() == ISD::UNDEF)
4413 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4414 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4419 // If we have found an entire vector of loads and undefs, then return a large
4420 // load of the entire vector width starting at the base pointer. If we found
4421 // consecutive loads for the low half, generate a vzext_load node.
4422 if (LastLoadedElt == NumElems - 1) {
4423 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4424 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4425 LDBase->getPointerInfo(),
4426 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4427 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4428 LDBase->getPointerInfo(),
4429 LDBase->isVolatile(), LDBase->isNonTemporal(),
4430 LDBase->getAlignment());
4431 } else if (NumElems == 4 && LastLoadedElt == 1) {
4432 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4433 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4434 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4436 LDBase->getMemOperand());
4437 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4443 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4444 DebugLoc dl = Op.getDebugLoc();
4446 EVT VT = Op.getValueType();
4447 EVT ExtVT = VT.getVectorElementType();
4449 unsigned NumElems = Op.getNumOperands();
4451 // For AVX-length vectors, build the individual 128-bit pieces and
4452 // use shuffles to put them in place.
4453 if (VT.getSizeInBits() > 256 &&
4454 Subtarget->hasAVX() &&
4455 !ISD::isBuildVectorAllZeros(Op.getNode())) {
4456 SmallVector<SDValue, 8> V;
4458 for (unsigned i = 0; i < NumElems; ++i) {
4459 V[i] = Op.getOperand(i);
4462 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4464 // Build the lower subvector.
4465 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4466 // Build the upper subvector.
4467 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4470 return ConcatVectors(Lower, Upper, DAG);
4473 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4474 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4475 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4476 // is present, so AllOnes is ignored.
4477 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4478 (Op.getValueType().getSizeInBits() != 256 &&
4479 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4480 // Canonicalize this to <4 x i32> (SSE) to
4481 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4482 // eliminated on x86-32 hosts.
4483 if (Op.getValueType() == MVT::v4i32)
4486 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4487 return getOnesVector(Op.getValueType(), DAG, dl);
4488 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4491 unsigned EVTBits = ExtVT.getSizeInBits();
4493 unsigned NumZero = 0;
4494 unsigned NumNonZero = 0;
4495 unsigned NonZeros = 0;
4496 bool IsAllConstants = true;
4497 SmallSet<SDValue, 8> Values;
4498 for (unsigned i = 0; i < NumElems; ++i) {
4499 SDValue Elt = Op.getOperand(i);
4500 if (Elt.getOpcode() == ISD::UNDEF)
4503 if (Elt.getOpcode() != ISD::Constant &&
4504 Elt.getOpcode() != ISD::ConstantFP)
4505 IsAllConstants = false;
4506 if (X86::isZeroNode(Elt))
4509 NonZeros |= (1 << i);
4514 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4515 if (NumNonZero == 0)
4516 return DAG.getUNDEF(VT);
4518 // Special case for single non-zero, non-undef, element.
4519 if (NumNonZero == 1) {
4520 unsigned Idx = CountTrailingZeros_32(NonZeros);
4521 SDValue Item = Op.getOperand(Idx);
4523 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4524 // the value are obviously zero, truncate the value to i32 and do the
4525 // insertion that way. Only do this if the value is non-constant or if the
4526 // value is a constant being inserted into element 0. It is cheaper to do
4527 // a constant pool load than it is to do a movd + shuffle.
4528 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4529 (!IsAllConstants || Idx == 0)) {
4530 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4532 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4533 EVT VecVT = MVT::v4i32;
4534 unsigned VecElts = 4;
4536 // Truncate the value (which may itself be a constant) to i32, and
4537 // convert it to a vector with movd (S2V+shuffle to zero extend).
4538 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4539 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4540 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4541 Subtarget->hasSSE2(), DAG);
4543 // Now we have our 32-bit value zero extended in the low element of
4544 // a vector. If Idx != 0, swizzle it into place.
4546 SmallVector<int, 4> Mask;
4547 Mask.push_back(Idx);
4548 for (unsigned i = 1; i != VecElts; ++i)
4550 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4551 DAG.getUNDEF(Item.getValueType()),
4554 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4558 // If we have a constant or non-constant insertion into the low element of
4559 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4560 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4561 // depending on what the source datatype is.
4564 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4565 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4566 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4567 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4568 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4569 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4571 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4572 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4573 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4574 EVT MiddleVT = MVT::v4i32;
4575 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4576 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4577 Subtarget->hasSSE2(), DAG);
4578 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4582 // Is it a vector logical left shift?
4583 if (NumElems == 2 && Idx == 1 &&
4584 X86::isZeroNode(Op.getOperand(0)) &&
4585 !X86::isZeroNode(Op.getOperand(1))) {
4586 unsigned NumBits = VT.getSizeInBits();
4587 return getVShift(true, VT,
4588 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4589 VT, Op.getOperand(1)),
4590 NumBits/2, DAG, *this, dl);
4593 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4596 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4597 // is a non-constant being inserted into an element other than the low one,
4598 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4599 // movd/movss) to move this into the low element, then shuffle it into
4601 if (EVTBits == 32) {
4602 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4604 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4605 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4606 Subtarget->hasSSE2(), DAG);
4607 SmallVector<int, 8> MaskVec;
4608 for (unsigned i = 0; i < NumElems; i++)
4609 MaskVec.push_back(i == Idx ? 0 : 1);
4610 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4614 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4615 if (Values.size() == 1) {
4616 if (EVTBits == 32) {
4617 // Instead of a shuffle like this:
4618 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4619 // Check if it's possible to issue this instead.
4620 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4621 unsigned Idx = CountTrailingZeros_32(NonZeros);
4622 SDValue Item = Op.getOperand(Idx);
4623 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4624 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4629 // A vector full of immediates; various special cases are already
4630 // handled, so this is best done with a single constant-pool load.
4634 // Let legalizer expand 2-wide build_vectors.
4635 if (EVTBits == 64) {
4636 if (NumNonZero == 1) {
4637 // One half is zero or undef.
4638 unsigned Idx = CountTrailingZeros_32(NonZeros);
4639 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4640 Op.getOperand(Idx));
4641 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4642 Subtarget->hasSSE2(), DAG);
4647 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4648 if (EVTBits == 8 && NumElems == 16) {
4649 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4651 if (V.getNode()) return V;
4654 if (EVTBits == 16 && NumElems == 8) {
4655 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4657 if (V.getNode()) return V;
4660 // If element VT is == 32 bits, turn it into a number of shuffles.
4661 SmallVector<SDValue, 8> V;
4663 if (NumElems == 4 && NumZero > 0) {
4664 for (unsigned i = 0; i < 4; ++i) {
4665 bool isZero = !(NonZeros & (1 << i));
4667 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4669 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4672 for (unsigned i = 0; i < 2; ++i) {
4673 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4676 V[i] = V[i*2]; // Must be a zero vector.
4679 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4682 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4685 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4690 SmallVector<int, 8> MaskVec;
4691 bool Reverse = (NonZeros & 0x3) == 2;
4692 for (unsigned i = 0; i < 2; ++i)
4693 MaskVec.push_back(Reverse ? 1-i : i);
4694 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4695 for (unsigned i = 0; i < 2; ++i)
4696 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4697 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4700 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4701 // Check for a build vector of consecutive loads.
4702 for (unsigned i = 0; i < NumElems; ++i)
4703 V[i] = Op.getOperand(i);
4705 // Check for elements which are consecutive loads.
4706 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4710 // For SSE 4.1, use insertps to put the high elements into the low element.
4711 if (getSubtarget()->hasSSE41()) {
4713 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4714 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4716 Result = DAG.getUNDEF(VT);
4718 for (unsigned i = 1; i < NumElems; ++i) {
4719 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4720 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4721 Op.getOperand(i), DAG.getIntPtrConstant(i));
4726 // Otherwise, expand into a number of unpckl*, start by extending each of
4727 // our (non-undef) elements to the full vector width with the element in the
4728 // bottom slot of the vector (which generates no code for SSE).
4729 for (unsigned i = 0; i < NumElems; ++i) {
4730 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4731 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4733 V[i] = DAG.getUNDEF(VT);
4736 // Next, we iteratively mix elements, e.g. for v4f32:
4737 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4738 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4739 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4740 unsigned EltStride = NumElems >> 1;
4741 while (EltStride != 0) {
4742 for (unsigned i = 0; i < EltStride; ++i) {
4743 // If V[i+EltStride] is undef and this is the first round of mixing,
4744 // then it is safe to just drop this shuffle: V[i] is already in the
4745 // right place, the one element (since it's the first round) being
4746 // inserted as undef can be dropped. This isn't safe for successive
4747 // rounds because they will permute elements within both vectors.
4748 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4749 EltStride == NumElems/2)
4752 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4762 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4763 // We support concatenate two MMX registers and place them in a MMX
4764 // register. This is better than doing a stack convert.
4765 DebugLoc dl = Op.getDebugLoc();
4766 EVT ResVT = Op.getValueType();
4767 assert(Op.getNumOperands() == 2);
4768 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4769 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4771 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4772 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4773 InVec = Op.getOperand(1);
4774 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4775 unsigned NumElts = ResVT.getVectorNumElements();
4776 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4777 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4778 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4780 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4781 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4782 Mask[0] = 0; Mask[1] = 2;
4783 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4785 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4788 // v8i16 shuffles - Prefer shuffles in the following order:
4789 // 1. [all] pshuflw, pshufhw, optional move
4790 // 2. [ssse3] 1 x pshufb
4791 // 3. [ssse3] 2 x pshufb + 1 x por
4792 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4794 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4795 SelectionDAG &DAG) const {
4796 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4797 SDValue V1 = SVOp->getOperand(0);
4798 SDValue V2 = SVOp->getOperand(1);
4799 DebugLoc dl = SVOp->getDebugLoc();
4800 SmallVector<int, 8> MaskVals;
4802 // Determine if more than 1 of the words in each of the low and high quadwords
4803 // of the result come from the same quadword of one of the two inputs. Undef
4804 // mask values count as coming from any quadword, for better codegen.
4805 SmallVector<unsigned, 4> LoQuad(4);
4806 SmallVector<unsigned, 4> HiQuad(4);
4807 BitVector InputQuads(4);
4808 for (unsigned i = 0; i < 8; ++i) {
4809 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4810 int EltIdx = SVOp->getMaskElt(i);
4811 MaskVals.push_back(EltIdx);
4820 InputQuads.set(EltIdx / 4);
4823 int BestLoQuad = -1;
4824 unsigned MaxQuad = 1;
4825 for (unsigned i = 0; i < 4; ++i) {
4826 if (LoQuad[i] > MaxQuad) {
4828 MaxQuad = LoQuad[i];
4832 int BestHiQuad = -1;
4834 for (unsigned i = 0; i < 4; ++i) {
4835 if (HiQuad[i] > MaxQuad) {
4837 MaxQuad = HiQuad[i];
4841 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4842 // of the two input vectors, shuffle them into one input vector so only a
4843 // single pshufb instruction is necessary. If There are more than 2 input
4844 // quads, disable the next transformation since it does not help SSSE3.
4845 bool V1Used = InputQuads[0] || InputQuads[1];
4846 bool V2Used = InputQuads[2] || InputQuads[3];
4847 if (Subtarget->hasSSSE3()) {
4848 if (InputQuads.count() == 2 && V1Used && V2Used) {
4849 BestLoQuad = InputQuads.find_first();
4850 BestHiQuad = InputQuads.find_next(BestLoQuad);
4852 if (InputQuads.count() > 2) {
4858 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4859 // the shuffle mask. If a quad is scored as -1, that means that it contains
4860 // words from all 4 input quadwords.
4862 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4863 SmallVector<int, 8> MaskV;
4864 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4865 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4866 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4867 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4868 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4869 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4871 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4872 // source words for the shuffle, to aid later transformations.
4873 bool AllWordsInNewV = true;
4874 bool InOrder[2] = { true, true };
4875 for (unsigned i = 0; i != 8; ++i) {
4876 int idx = MaskVals[i];
4878 InOrder[i/4] = false;
4879 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4881 AllWordsInNewV = false;
4885 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4886 if (AllWordsInNewV) {
4887 for (int i = 0; i != 8; ++i) {
4888 int idx = MaskVals[i];
4891 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4892 if ((idx != i) && idx < 4)
4894 if ((idx != i) && idx > 3)
4903 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4904 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4905 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4906 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4907 unsigned TargetMask = 0;
4908 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4909 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4910 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4911 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4912 V1 = NewV.getOperand(0);
4913 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4917 // If we have SSSE3, and all words of the result are from 1 input vector,
4918 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4919 // is present, fall back to case 4.
4920 if (Subtarget->hasSSSE3()) {
4921 SmallVector<SDValue,16> pshufbMask;
4923 // If we have elements from both input vectors, set the high bit of the
4924 // shuffle mask element to zero out elements that come from V2 in the V1
4925 // mask, and elements that come from V1 in the V2 mask, so that the two
4926 // results can be OR'd together.
4927 bool TwoInputs = V1Used && V2Used;
4928 for (unsigned i = 0; i != 8; ++i) {
4929 int EltIdx = MaskVals[i] * 2;
4930 if (TwoInputs && (EltIdx >= 16)) {
4931 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4932 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4935 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4936 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4938 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4939 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4940 DAG.getNode(ISD::BUILD_VECTOR, dl,
4941 MVT::v16i8, &pshufbMask[0], 16));
4943 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4945 // Calculate the shuffle mask for the second input, shuffle it, and
4946 // OR it with the first shuffled input.
4948 for (unsigned i = 0; i != 8; ++i) {
4949 int EltIdx = MaskVals[i] * 2;
4951 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4952 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4955 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4956 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4958 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4959 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4960 DAG.getNode(ISD::BUILD_VECTOR, dl,
4961 MVT::v16i8, &pshufbMask[0], 16));
4962 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4963 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4966 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4967 // and update MaskVals with new element order.
4968 BitVector InOrder(8);
4969 if (BestLoQuad >= 0) {
4970 SmallVector<int, 8> MaskV;
4971 for (int i = 0; i != 4; ++i) {
4972 int idx = MaskVals[i];
4974 MaskV.push_back(-1);
4976 } else if ((idx / 4) == BestLoQuad) {
4977 MaskV.push_back(idx & 3);
4980 MaskV.push_back(-1);
4983 for (unsigned i = 4; i != 8; ++i)
4985 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4988 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4989 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4991 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4995 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4996 // and update MaskVals with the new element order.
4997 if (BestHiQuad >= 0) {
4998 SmallVector<int, 8> MaskV;
4999 for (unsigned i = 0; i != 4; ++i)
5001 for (unsigned i = 4; i != 8; ++i) {
5002 int idx = MaskVals[i];
5004 MaskV.push_back(-1);
5006 } else if ((idx / 4) == BestHiQuad) {
5007 MaskV.push_back((idx & 3) + 4);
5010 MaskV.push_back(-1);
5013 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5016 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5017 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5019 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5023 // In case BestHi & BestLo were both -1, which means each quadword has a word
5024 // from each of the four input quadwords, calculate the InOrder bitvector now
5025 // before falling through to the insert/extract cleanup.
5026 if (BestLoQuad == -1 && BestHiQuad == -1) {
5028 for (int i = 0; i != 8; ++i)
5029 if (MaskVals[i] < 0 || MaskVals[i] == i)
5033 // The other elements are put in the right place using pextrw and pinsrw.
5034 for (unsigned i = 0; i != 8; ++i) {
5037 int EltIdx = MaskVals[i];
5040 SDValue ExtOp = (EltIdx < 8)
5041 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5042 DAG.getIntPtrConstant(EltIdx))
5043 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5044 DAG.getIntPtrConstant(EltIdx - 8));
5045 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5046 DAG.getIntPtrConstant(i));
5051 // v16i8 shuffles - Prefer shuffles in the following order:
5052 // 1. [ssse3] 1 x pshufb
5053 // 2. [ssse3] 2 x pshufb + 1 x por
5054 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5056 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5058 const X86TargetLowering &TLI) {
5059 SDValue V1 = SVOp->getOperand(0);
5060 SDValue V2 = SVOp->getOperand(1);
5061 DebugLoc dl = SVOp->getDebugLoc();
5062 SmallVector<int, 16> MaskVals;
5063 SVOp->getMask(MaskVals);
5065 // If we have SSSE3, case 1 is generated when all result bytes come from
5066 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5067 // present, fall back to case 3.
5068 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5071 for (unsigned i = 0; i < 16; ++i) {
5072 int EltIdx = MaskVals[i];
5081 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5082 if (TLI.getSubtarget()->hasSSSE3()) {
5083 SmallVector<SDValue,16> pshufbMask;
5085 // If all result elements are from one input vector, then only translate
5086 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5088 // Otherwise, we have elements from both input vectors, and must zero out
5089 // elements that come from V2 in the first mask, and V1 in the second mask
5090 // so that we can OR them together.
5091 bool TwoInputs = !(V1Only || V2Only);
5092 for (unsigned i = 0; i != 16; ++i) {
5093 int EltIdx = MaskVals[i];
5094 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5095 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5098 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5100 // If all the elements are from V2, assign it to V1 and return after
5101 // building the first pshufb.
5104 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5105 DAG.getNode(ISD::BUILD_VECTOR, dl,
5106 MVT::v16i8, &pshufbMask[0], 16));
5110 // Calculate the shuffle mask for the second input, shuffle it, and
5111 // OR it with the first shuffled input.
5113 for (unsigned i = 0; i != 16; ++i) {
5114 int EltIdx = MaskVals[i];
5116 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5119 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5121 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5122 DAG.getNode(ISD::BUILD_VECTOR, dl,
5123 MVT::v16i8, &pshufbMask[0], 16));
5124 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5127 // No SSSE3 - Calculate in place words and then fix all out of place words
5128 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5129 // the 16 different words that comprise the two doublequadword input vectors.
5130 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5131 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5132 SDValue NewV = V2Only ? V2 : V1;
5133 for (int i = 0; i != 8; ++i) {
5134 int Elt0 = MaskVals[i*2];
5135 int Elt1 = MaskVals[i*2+1];
5137 // This word of the result is all undef, skip it.
5138 if (Elt0 < 0 && Elt1 < 0)
5141 // This word of the result is already in the correct place, skip it.
5142 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5144 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5147 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5148 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5151 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5152 // using a single extract together, load it and store it.
5153 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5154 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5155 DAG.getIntPtrConstant(Elt1 / 2));
5156 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5157 DAG.getIntPtrConstant(i));
5161 // If Elt1 is defined, extract it from the appropriate source. If the
5162 // source byte is not also odd, shift the extracted word left 8 bits
5163 // otherwise clear the bottom 8 bits if we need to do an or.
5165 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5166 DAG.getIntPtrConstant(Elt1 / 2));
5167 if ((Elt1 & 1) == 0)
5168 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5170 TLI.getShiftAmountTy(InsElt.getValueType())));
5172 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5173 DAG.getConstant(0xFF00, MVT::i16));
5175 // If Elt0 is defined, extract it from the appropriate source. If the
5176 // source byte is not also even, shift the extracted word right 8 bits. If
5177 // Elt1 was also defined, OR the extracted values together before
5178 // inserting them in the result.
5180 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5181 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5182 if ((Elt0 & 1) != 0)
5183 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5185 TLI.getShiftAmountTy(InsElt0.getValueType())));
5187 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5188 DAG.getConstant(0x00FF, MVT::i16));
5189 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5192 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5193 DAG.getIntPtrConstant(i));
5195 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5198 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5199 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5200 /// done when every pair / quad of shuffle mask elements point to elements in
5201 /// the right sequence. e.g.
5202 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5204 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5205 SelectionDAG &DAG, DebugLoc dl) {
5206 EVT VT = SVOp->getValueType(0);
5207 SDValue V1 = SVOp->getOperand(0);
5208 SDValue V2 = SVOp->getOperand(1);
5209 unsigned NumElems = VT.getVectorNumElements();
5210 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5212 switch (VT.getSimpleVT().SimpleTy) {
5213 default: assert(false && "Unexpected!");
5214 case MVT::v4f32: NewVT = MVT::v2f64; break;
5215 case MVT::v4i32: NewVT = MVT::v2i64; break;
5216 case MVT::v8i16: NewVT = MVT::v4i32; break;
5217 case MVT::v16i8: NewVT = MVT::v4i32; break;
5220 int Scale = NumElems / NewWidth;
5221 SmallVector<int, 8> MaskVec;
5222 for (unsigned i = 0; i < NumElems; i += Scale) {
5224 for (int j = 0; j < Scale; ++j) {
5225 int EltIdx = SVOp->getMaskElt(i+j);
5229 StartIdx = EltIdx - (EltIdx % Scale);
5230 if (EltIdx != StartIdx + j)
5234 MaskVec.push_back(-1);
5236 MaskVec.push_back(StartIdx / Scale);
5239 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5240 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5241 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5244 /// getVZextMovL - Return a zero-extending vector move low node.
5246 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5247 SDValue SrcOp, SelectionDAG &DAG,
5248 const X86Subtarget *Subtarget, DebugLoc dl) {
5249 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5250 LoadSDNode *LD = NULL;
5251 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5252 LD = dyn_cast<LoadSDNode>(SrcOp);
5254 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5256 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5257 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5258 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5259 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5260 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5262 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5263 return DAG.getNode(ISD::BITCAST, dl, VT,
5264 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5265 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5273 return DAG.getNode(ISD::BITCAST, dl, VT,
5274 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5275 DAG.getNode(ISD::BITCAST, dl,
5279 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5282 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5283 SDValue V1 = SVOp->getOperand(0);
5284 SDValue V2 = SVOp->getOperand(1);
5285 DebugLoc dl = SVOp->getDebugLoc();
5286 EVT VT = SVOp->getValueType(0);
5288 SmallVector<std::pair<int, int>, 8> Locs;
5290 SmallVector<int, 8> Mask1(4U, -1);
5291 SmallVector<int, 8> PermMask;
5292 SVOp->getMask(PermMask);
5296 for (unsigned i = 0; i != 4; ++i) {
5297 int Idx = PermMask[i];
5299 Locs[i] = std::make_pair(-1, -1);
5301 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5303 Locs[i] = std::make_pair(0, NumLo);
5307 Locs[i] = std::make_pair(1, NumHi);
5309 Mask1[2+NumHi] = Idx;
5315 if (NumLo <= 2 && NumHi <= 2) {
5316 // If no more than two elements come from either vector. This can be
5317 // implemented with two shuffles. First shuffle gather the elements.
5318 // The second shuffle, which takes the first shuffle as both of its
5319 // vector operands, put the elements into the right order.
5320 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5322 SmallVector<int, 8> Mask2(4U, -1);
5324 for (unsigned i = 0; i != 4; ++i) {
5325 if (Locs[i].first == -1)
5328 unsigned Idx = (i < 2) ? 0 : 4;
5329 Idx += Locs[i].first * 2 + Locs[i].second;
5334 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5335 } else if (NumLo == 3 || NumHi == 3) {
5336 // Otherwise, we must have three elements from one vector, call it X, and
5337 // one element from the other, call it Y. First, use a shufps to build an
5338 // intermediate vector with the one element from Y and the element from X
5339 // that will be in the same half in the final destination (the indexes don't
5340 // matter). Then, use a shufps to build the final vector, taking the half
5341 // containing the element from Y from the intermediate, and the other half
5344 // Normalize it so the 3 elements come from V1.
5345 CommuteVectorShuffleMask(PermMask, VT);
5349 // Find the element from V2.
5351 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5352 int Val = PermMask[HiIndex];
5359 Mask1[0] = PermMask[HiIndex];
5361 Mask1[2] = PermMask[HiIndex^1];
5363 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5366 Mask1[0] = PermMask[0];
5367 Mask1[1] = PermMask[1];
5368 Mask1[2] = HiIndex & 1 ? 6 : 4;
5369 Mask1[3] = HiIndex & 1 ? 4 : 6;
5370 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5372 Mask1[0] = HiIndex & 1 ? 2 : 0;
5373 Mask1[1] = HiIndex & 1 ? 0 : 2;
5374 Mask1[2] = PermMask[2];
5375 Mask1[3] = PermMask[3];
5380 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5384 // Break it into (shuffle shuffle_hi, shuffle_lo).
5387 SmallVector<int,8> LoMask(4U, -1);
5388 SmallVector<int,8> HiMask(4U, -1);
5390 SmallVector<int,8> *MaskPtr = &LoMask;
5391 unsigned MaskIdx = 0;
5394 for (unsigned i = 0; i != 4; ++i) {
5401 int Idx = PermMask[i];
5403 Locs[i] = std::make_pair(-1, -1);
5404 } else if (Idx < 4) {
5405 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5406 (*MaskPtr)[LoIdx] = Idx;
5409 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5410 (*MaskPtr)[HiIdx] = Idx;
5415 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5416 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5417 SmallVector<int, 8> MaskOps;
5418 for (unsigned i = 0; i != 4; ++i) {
5419 if (Locs[i].first == -1) {
5420 MaskOps.push_back(-1);
5422 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5423 MaskOps.push_back(Idx);
5426 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5429 static bool MayFoldVectorLoad(SDValue V) {
5430 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5431 V = V.getOperand(0);
5432 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5433 V = V.getOperand(0);
5439 // FIXME: the version above should always be used. Since there's
5440 // a bug where several vector shuffles can't be folded because the
5441 // DAG is not updated during lowering and a node claims to have two
5442 // uses while it only has one, use this version, and let isel match
5443 // another instruction if the load really happens to have more than
5444 // one use. Remove this version after this bug get fixed.
5445 // rdar://8434668, PR8156
5446 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5447 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5448 V = V.getOperand(0);
5449 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5450 V = V.getOperand(0);
5451 if (ISD::isNormalLoad(V.getNode()))
5456 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5457 /// a vector extract, and if both can be later optimized into a single load.
5458 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5459 /// here because otherwise a target specific shuffle node is going to be
5460 /// emitted for this shuffle, and the optimization not done.
5461 /// FIXME: This is probably not the best approach, but fix the problem
5462 /// until the right path is decided.
5464 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5465 const TargetLowering &TLI) {
5466 EVT VT = V.getValueType();
5467 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5469 // Be sure that the vector shuffle is present in a pattern like this:
5470 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5474 SDNode *N = *V.getNode()->use_begin();
5475 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5478 SDValue EltNo = N->getOperand(1);
5479 if (!isa<ConstantSDNode>(EltNo))
5482 // If the bit convert changed the number of elements, it is unsafe
5483 // to examine the mask.
5484 bool HasShuffleIntoBitcast = false;
5485 if (V.getOpcode() == ISD::BITCAST) {
5486 EVT SrcVT = V.getOperand(0).getValueType();
5487 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5489 V = V.getOperand(0);
5490 HasShuffleIntoBitcast = true;
5493 // Select the input vector, guarding against out of range extract vector.
5494 unsigned NumElems = VT.getVectorNumElements();
5495 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5496 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5497 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5499 // Skip one more bit_convert if necessary
5500 if (V.getOpcode() == ISD::BITCAST)
5501 V = V.getOperand(0);
5503 if (ISD::isNormalLoad(V.getNode())) {
5504 // Is the original load suitable?
5505 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5507 // FIXME: avoid the multi-use bug that is preventing lots of
5508 // of foldings to be detected, this is still wrong of course, but
5509 // give the temporary desired behavior, and if it happens that
5510 // the load has real more uses, during isel it will not fold, and
5511 // will generate poor code.
5512 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5515 if (!HasShuffleIntoBitcast)
5518 // If there's a bitcast before the shuffle, check if the load type and
5519 // alignment is valid.
5520 unsigned Align = LN0->getAlignment();
5522 TLI.getTargetData()->getABITypeAlignment(
5523 VT.getTypeForEVT(*DAG.getContext()));
5525 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5533 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5534 EVT VT = Op.getValueType();
5536 // Canonizalize to v2f64.
5537 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5538 return DAG.getNode(ISD::BITCAST, dl, VT,
5539 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5544 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5546 SDValue V1 = Op.getOperand(0);
5547 SDValue V2 = Op.getOperand(1);
5548 EVT VT = Op.getValueType();
5550 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5552 if (HasSSE2 && VT == MVT::v2f64)
5553 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5556 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5560 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5561 SDValue V1 = Op.getOperand(0);
5562 SDValue V2 = Op.getOperand(1);
5563 EVT VT = Op.getValueType();
5565 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5566 "unsupported shuffle type");
5568 if (V2.getOpcode() == ISD::UNDEF)
5572 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5576 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5577 SDValue V1 = Op.getOperand(0);
5578 SDValue V2 = Op.getOperand(1);
5579 EVT VT = Op.getValueType();
5580 unsigned NumElems = VT.getVectorNumElements();
5582 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5583 // operand of these instructions is only memory, so check if there's a
5584 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5586 bool CanFoldLoad = false;
5588 // Trivial case, when V2 comes from a load.
5589 if (MayFoldVectorLoad(V2))
5592 // When V1 is a load, it can be folded later into a store in isel, example:
5593 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5595 // (MOVLPSmr addr:$src1, VR128:$src2)
5596 // So, recognize this potential and also use MOVLPS or MOVLPD
5597 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5600 // Both of them can't be memory operations though.
5601 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5602 CanFoldLoad = false;
5605 if (HasSSE2 && NumElems == 2)
5606 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5609 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5612 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5613 // movl and movlp will both match v2i64, but v2i64 is never matched by
5614 // movl earlier because we make it strict to avoid messing with the movlp load
5615 // folding logic (see the code above getMOVLP call). Match it here then,
5616 // this is horrible, but will stay like this until we move all shuffle
5617 // matching to x86 specific nodes. Note that for the 1st condition all
5618 // types are matched with movsd.
5619 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5620 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5622 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5625 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5627 // Invert the operand order and use SHUFPS to match it.
5628 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5629 X86::getShuffleSHUFImmediate(SVOp), DAG);
5632 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5633 switch(VT.getSimpleVT().SimpleTy) {
5634 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5635 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5637 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5639 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5640 case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5641 case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5642 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5643 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5645 llvm_unreachable("Unknown type for unpckl");
5650 static inline unsigned getUNPCKHOpcode(EVT VT) {
5651 switch(VT.getSimpleVT().SimpleTy) {
5652 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5653 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5654 case MVT::v4f32: return X86ISD::UNPCKHPS;
5655 case MVT::v2f64: return X86ISD::UNPCKHPD;
5656 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5657 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5659 llvm_unreachable("Unknown type for unpckh");
5665 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5666 const TargetLowering &TLI,
5667 const X86Subtarget *Subtarget) {
5668 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5669 EVT VT = Op.getValueType();
5670 DebugLoc dl = Op.getDebugLoc();
5671 SDValue V1 = Op.getOperand(0);
5672 SDValue V2 = Op.getOperand(1);
5674 if (isZeroShuffle(SVOp))
5675 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5677 // Handle splat operations
5678 if (SVOp->isSplat()) {
5679 // Special case, this is the only place now where it's
5680 // allowed to return a vector_shuffle operation without
5681 // using a target specific node, because *hopefully* it
5682 // will be optimized away by the dag combiner.
5683 if (VT.getVectorNumElements() <= 4 &&
5684 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5687 // Handle splats by matching through known masks
5688 if (VT.getVectorNumElements() <= 4)
5691 // Canonicalize all of the remaining to v4f32.
5692 return PromoteSplat(SVOp, DAG);
5695 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5697 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5698 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5699 if (NewOp.getNode())
5700 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5701 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5702 // FIXME: Figure out a cleaner way to do this.
5703 // Try to make use of movq to zero out the top part.
5704 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5705 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5706 if (NewOp.getNode()) {
5707 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5708 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5709 DAG, Subtarget, dl);
5711 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5712 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5713 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5714 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5715 DAG, Subtarget, dl);
5722 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5723 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5724 SDValue V1 = Op.getOperand(0);
5725 SDValue V2 = Op.getOperand(1);
5726 EVT VT = Op.getValueType();
5727 DebugLoc dl = Op.getDebugLoc();
5728 unsigned NumElems = VT.getVectorNumElements();
5729 bool isMMX = VT.getSizeInBits() == 64;
5730 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5731 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5732 bool V1IsSplat = false;
5733 bool V2IsSplat = false;
5734 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5735 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5736 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5737 MachineFunction &MF = DAG.getMachineFunction();
5738 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5740 // Shuffle operations on MMX not supported.
5744 // Vector shuffle lowering takes 3 steps:
5746 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5747 // narrowing and commutation of operands should be handled.
5748 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5750 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5751 // so the shuffle can be broken into other shuffles and the legalizer can
5752 // try the lowering again.
5754 // The general ideia is that no vector_shuffle operation should be left to
5755 // be matched during isel, all of them must be converted to a target specific
5758 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5759 // narrowing and commutation of operands should be handled. The actual code
5760 // doesn't include all of those, work in progress...
5761 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5762 if (NewOp.getNode())
5765 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5766 // unpckh_undef). Only use pshufd if speed is more important than size.
5767 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5768 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5769 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5770 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5771 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5772 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5774 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5775 RelaxedMayFoldVectorLoad(V1))
5776 return getMOVDDup(Op, dl, V1, DAG);
5778 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5779 return getMOVHighToLow(Op, dl, DAG);
5781 // Use to match splats
5782 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5783 (VT == MVT::v2f64 || VT == MVT::v2i64))
5784 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5786 if (X86::isPSHUFDMask(SVOp)) {
5787 // The actual implementation will match the mask in the if above and then
5788 // during isel it can match several different instructions, not only pshufd
5789 // as its name says, sad but true, emulate the behavior for now...
5790 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5791 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5793 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5795 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5796 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5798 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5799 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5802 if (VT == MVT::v4f32)
5803 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5807 // Check if this can be converted into a logical shift.
5808 bool isLeft = false;
5811 bool isShift = getSubtarget()->hasSSE2() &&
5812 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5813 if (isShift && ShVal.hasOneUse()) {
5814 // If the shifted value has multiple uses, it may be cheaper to use
5815 // v_set0 + movlhps or movhlps, etc.
5816 EVT EltVT = VT.getVectorElementType();
5817 ShAmt *= EltVT.getSizeInBits();
5818 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5821 if (X86::isMOVLMask(SVOp)) {
5824 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5825 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5826 if (!X86::isMOVLPMask(SVOp)) {
5827 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5828 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5830 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5831 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5835 // FIXME: fold these into legal mask.
5836 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5837 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5839 if (X86::isMOVHLPSMask(SVOp))
5840 return getMOVHighToLow(Op, dl, DAG);
5842 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5843 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5845 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5846 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5848 if (X86::isMOVLPMask(SVOp))
5849 return getMOVLP(Op, dl, DAG, HasSSE2);
5851 if (ShouldXformToMOVHLPS(SVOp) ||
5852 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5853 return CommuteVectorShuffle(SVOp, DAG);
5856 // No better options. Use a vshl / vsrl.
5857 EVT EltVT = VT.getVectorElementType();
5858 ShAmt *= EltVT.getSizeInBits();
5859 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5862 bool Commuted = false;
5863 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5864 // 1,1,1,1 -> v8i16 though.
5865 V1IsSplat = isSplatVector(V1.getNode());
5866 V2IsSplat = isSplatVector(V2.getNode());
5868 // Canonicalize the splat or undef, if present, to be on the RHS.
5869 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5870 Op = CommuteVectorShuffle(SVOp, DAG);
5871 SVOp = cast<ShuffleVectorSDNode>(Op);
5872 V1 = SVOp->getOperand(0);
5873 V2 = SVOp->getOperand(1);
5874 std::swap(V1IsSplat, V2IsSplat);
5875 std::swap(V1IsUndef, V2IsUndef);
5879 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5880 // Shuffling low element of v1 into undef, just return v1.
5883 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5884 // the instruction selector will not match, so get a canonical MOVL with
5885 // swapped operands to undo the commute.
5886 return getMOVL(DAG, dl, VT, V2, V1);
5889 if (X86::isUNPCKLMask(SVOp))
5890 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5891 dl, VT, V1, V2, DAG);
5893 if (X86::isUNPCKHMask(SVOp))
5894 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5897 // Normalize mask so all entries that point to V2 points to its first
5898 // element then try to match unpck{h|l} again. If match, return a
5899 // new vector_shuffle with the corrected mask.
5900 SDValue NewMask = NormalizeMask(SVOp, DAG);
5901 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5902 if (NSVOp != SVOp) {
5903 if (X86::isUNPCKLMask(NSVOp, true)) {
5905 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5912 // Commute is back and try unpck* again.
5913 // FIXME: this seems wrong.
5914 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5915 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5917 if (X86::isUNPCKLMask(NewSVOp))
5918 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5919 dl, VT, V2, V1, DAG);
5921 if (X86::isUNPCKHMask(NewSVOp))
5922 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5925 // Normalize the node to match x86 shuffle ops if needed
5926 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5927 return CommuteVectorShuffle(SVOp, DAG);
5929 // The checks below are all present in isShuffleMaskLegal, but they are
5930 // inlined here right now to enable us to directly emit target specific
5931 // nodes, and remove one by one until they don't return Op anymore.
5932 SmallVector<int, 16> M;
5935 if (isPALIGNRMask(M, VT, HasSSSE3))
5936 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5937 X86::getShufflePALIGNRImmediate(SVOp),
5940 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5941 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5942 if (VT == MVT::v2f64) {
5943 X86ISD::NodeType Opcode =
5944 getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5945 return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5947 if (VT == MVT::v2i64)
5948 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5951 if (isPSHUFHWMask(M, VT))
5952 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5953 X86::getShufflePSHUFHWImmediate(SVOp),
5956 if (isPSHUFLWMask(M, VT))
5957 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5958 X86::getShufflePSHUFLWImmediate(SVOp),
5961 if (isSHUFPMask(M, VT)) {
5962 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5963 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5964 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5966 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5967 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5971 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5972 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5973 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5974 dl, VT, V1, V1, DAG);
5975 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5976 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5977 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5979 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5980 if (VT == MVT::v8i16) {
5981 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5982 if (NewOp.getNode())
5986 if (VT == MVT::v16i8) {
5987 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5988 if (NewOp.getNode())
5992 // Handle all 4 wide cases with a number of shuffles.
5994 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
6000 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6001 SelectionDAG &DAG) const {
6002 EVT VT = Op.getValueType();
6003 DebugLoc dl = Op.getDebugLoc();
6004 if (VT.getSizeInBits() == 8) {
6005 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6006 Op.getOperand(0), Op.getOperand(1));
6007 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6008 DAG.getValueType(VT));
6009 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6010 } else if (VT.getSizeInBits() == 16) {
6011 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6012 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6014 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6015 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6016 DAG.getNode(ISD::BITCAST, dl,
6020 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6021 Op.getOperand(0), Op.getOperand(1));
6022 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6023 DAG.getValueType(VT));
6024 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6025 } else if (VT == MVT::f32) {
6026 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6027 // the result back to FR32 register. It's only worth matching if the
6028 // result has a single use which is a store or a bitcast to i32. And in
6029 // the case of a store, it's not worth it if the index is a constant 0,
6030 // because a MOVSSmr can be used instead, which is smaller and faster.
6031 if (!Op.hasOneUse())
6033 SDNode *User = *Op.getNode()->use_begin();
6034 if ((User->getOpcode() != ISD::STORE ||
6035 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6036 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6037 (User->getOpcode() != ISD::BITCAST ||
6038 User->getValueType(0) != MVT::i32))
6040 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6041 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6044 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6045 } else if (VT == MVT::i32) {
6046 // ExtractPS works with constant index.
6047 if (isa<ConstantSDNode>(Op.getOperand(1)))
6055 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6056 SelectionDAG &DAG) const {
6057 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6060 SDValue Vec = Op.getOperand(0);
6061 EVT VecVT = Vec.getValueType();
6063 // If this is a 256-bit vector result, first extract the 128-bit
6064 // vector and then extract from the 128-bit vector.
6065 if (VecVT.getSizeInBits() > 128) {
6066 DebugLoc dl = Op.getNode()->getDebugLoc();
6067 unsigned NumElems = VecVT.getVectorNumElements();
6068 SDValue Idx = Op.getOperand(1);
6070 if (!isa<ConstantSDNode>(Idx))
6073 unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6074 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6076 // Get the 128-bit vector.
6077 bool Upper = IdxVal >= ExtractNumElems;
6078 Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6081 SDValue ScaledIdx = Idx;
6083 ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6084 DAG.getConstant(ExtractNumElems,
6085 Idx.getValueType()));
6086 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6090 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6092 if (Subtarget->hasSSE41()) {
6093 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6098 EVT VT = Op.getValueType();
6099 DebugLoc dl = Op.getDebugLoc();
6100 // TODO: handle v16i8.
6101 if (VT.getSizeInBits() == 16) {
6102 SDValue Vec = Op.getOperand(0);
6103 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6105 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6106 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6107 DAG.getNode(ISD::BITCAST, dl,
6110 // Transform it so it match pextrw which produces a 32-bit result.
6111 EVT EltVT = MVT::i32;
6112 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6113 Op.getOperand(0), Op.getOperand(1));
6114 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6115 DAG.getValueType(VT));
6116 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6117 } else if (VT.getSizeInBits() == 32) {
6118 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6122 // SHUFPS the element to the lowest double word, then movss.
6123 int Mask[4] = { Idx, -1, -1, -1 };
6124 EVT VVT = Op.getOperand(0).getValueType();
6125 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6126 DAG.getUNDEF(VVT), Mask);
6127 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6128 DAG.getIntPtrConstant(0));
6129 } else if (VT.getSizeInBits() == 64) {
6130 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6131 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6132 // to match extract_elt for f64.
6133 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6137 // UNPCKHPD the element to the lowest double word, then movsd.
6138 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6139 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6140 int Mask[2] = { 1, -1 };
6141 EVT VVT = Op.getOperand(0).getValueType();
6142 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6143 DAG.getUNDEF(VVT), Mask);
6144 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6145 DAG.getIntPtrConstant(0));
6152 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6153 SelectionDAG &DAG) const {
6154 EVT VT = Op.getValueType();
6155 EVT EltVT = VT.getVectorElementType();
6156 DebugLoc dl = Op.getDebugLoc();
6158 SDValue N0 = Op.getOperand(0);
6159 SDValue N1 = Op.getOperand(1);
6160 SDValue N2 = Op.getOperand(2);
6162 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6163 isa<ConstantSDNode>(N2)) {
6165 if (VT == MVT::v8i16)
6166 Opc = X86ISD::PINSRW;
6167 else if (VT == MVT::v16i8)
6168 Opc = X86ISD::PINSRB;
6170 Opc = X86ISD::PINSRB;
6172 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6174 if (N1.getValueType() != MVT::i32)
6175 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6176 if (N2.getValueType() != MVT::i32)
6177 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6178 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6179 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6180 // Bits [7:6] of the constant are the source select. This will always be
6181 // zero here. The DAG Combiner may combine an extract_elt index into these
6182 // bits. For example (insert (extract, 3), 2) could be matched by putting
6183 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6184 // Bits [5:4] of the constant are the destination select. This is the
6185 // value of the incoming immediate.
6186 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6187 // combine either bitwise AND or insert of float 0.0 to set these bits.
6188 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6189 // Create this as a scalar to vector..
6190 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6191 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6192 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6193 // PINSR* works with constant index.
6200 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6201 EVT VT = Op.getValueType();
6202 EVT EltVT = VT.getVectorElementType();
6204 DebugLoc dl = Op.getDebugLoc();
6205 SDValue N0 = Op.getOperand(0);
6206 SDValue N1 = Op.getOperand(1);
6207 SDValue N2 = Op.getOperand(2);
6209 // If this is a 256-bit vector result, first insert into a 128-bit
6210 // vector and then insert into the 256-bit vector.
6211 if (VT.getSizeInBits() > 128) {
6212 if (!isa<ConstantSDNode>(N2))
6215 // Get the 128-bit vector.
6216 unsigned NumElems = VT.getVectorNumElements();
6217 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6218 bool Upper = IdxVal >= NumElems / 2;
6220 SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6223 SDValue ScaledN2 = N2;
6225 ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6226 DAG.getConstant(NumElems /
6227 (VT.getSizeInBits() / 128),
6228 N2.getValueType()));
6229 Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6232 // Insert the 128-bit vector
6233 // FIXME: Why UNDEF?
6234 return Insert128BitVector(N0, Op, N2, DAG, dl);
6237 if (Subtarget->hasSSE41())
6238 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6240 if (EltVT == MVT::i8)
6243 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6244 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6245 // as its second argument.
6246 if (N1.getValueType() != MVT::i32)
6247 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6248 if (N2.getValueType() != MVT::i32)
6249 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6250 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6256 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6257 LLVMContext *Context = DAG.getContext();
6258 DebugLoc dl = Op.getDebugLoc();
6259 EVT OpVT = Op.getValueType();
6261 // If this is a 256-bit vector result, first insert into a 128-bit
6262 // vector and then insert into the 256-bit vector.
6263 if (OpVT.getSizeInBits() > 128) {
6264 // Insert into a 128-bit vector.
6265 EVT VT128 = EVT::getVectorVT(*Context,
6266 OpVT.getVectorElementType(),
6267 OpVT.getVectorNumElements() / 2);
6269 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6271 // Insert the 128-bit vector.
6272 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6273 DAG.getConstant(0, MVT::i32),
6277 if (Op.getValueType() == MVT::v1i64 &&
6278 Op.getOperand(0).getValueType() == MVT::i64)
6279 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6281 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6282 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6283 "Expected an SSE type!");
6284 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6285 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6288 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
6289 // a simple subregister reference or explicit instructions to grab
6290 // upper bits of a vector.
6292 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6293 if (Subtarget->hasAVX()) {
6294 DebugLoc dl = Op.getNode()->getDebugLoc();
6295 SDValue Vec = Op.getNode()->getOperand(0);
6296 SDValue Idx = Op.getNode()->getOperand(1);
6298 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6299 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6300 return Extract128BitVector(Vec, Idx, DAG, dl);
6306 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
6307 // simple superregister reference or explicit instructions to insert
6308 // the upper bits of a vector.
6310 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6311 if (Subtarget->hasAVX()) {
6312 DebugLoc dl = Op.getNode()->getDebugLoc();
6313 SDValue Vec = Op.getNode()->getOperand(0);
6314 SDValue SubVec = Op.getNode()->getOperand(1);
6315 SDValue Idx = Op.getNode()->getOperand(2);
6317 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6318 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6319 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6325 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6326 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6327 // one of the above mentioned nodes. It has to be wrapped because otherwise
6328 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6329 // be used to form addressing mode. These wrapped nodes will be selected
6332 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6333 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6335 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6337 unsigned char OpFlag = 0;
6338 unsigned WrapperKind = X86ISD::Wrapper;
6339 CodeModel::Model M = getTargetMachine().getCodeModel();
6341 if (Subtarget->isPICStyleRIPRel() &&
6342 (M == CodeModel::Small || M == CodeModel::Kernel))
6343 WrapperKind = X86ISD::WrapperRIP;
6344 else if (Subtarget->isPICStyleGOT())
6345 OpFlag = X86II::MO_GOTOFF;
6346 else if (Subtarget->isPICStyleStubPIC())
6347 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6349 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6351 CP->getOffset(), OpFlag);
6352 DebugLoc DL = CP->getDebugLoc();
6353 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6354 // With PIC, the address is actually $g + Offset.
6356 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6357 DAG.getNode(X86ISD::GlobalBaseReg,
6358 DebugLoc(), getPointerTy()),
6365 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6366 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6368 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6370 unsigned char OpFlag = 0;
6371 unsigned WrapperKind = X86ISD::Wrapper;
6372 CodeModel::Model M = getTargetMachine().getCodeModel();
6374 if (Subtarget->isPICStyleRIPRel() &&
6375 (M == CodeModel::Small || M == CodeModel::Kernel))
6376 WrapperKind = X86ISD::WrapperRIP;
6377 else if (Subtarget->isPICStyleGOT())
6378 OpFlag = X86II::MO_GOTOFF;
6379 else if (Subtarget->isPICStyleStubPIC())
6380 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6382 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6384 DebugLoc DL = JT->getDebugLoc();
6385 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6387 // With PIC, the address is actually $g + Offset.
6389 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6390 DAG.getNode(X86ISD::GlobalBaseReg,
6391 DebugLoc(), getPointerTy()),
6398 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6399 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6401 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6403 unsigned char OpFlag = 0;
6404 unsigned WrapperKind = X86ISD::Wrapper;
6405 CodeModel::Model M = getTargetMachine().getCodeModel();
6407 if (Subtarget->isPICStyleRIPRel() &&
6408 (M == CodeModel::Small || M == CodeModel::Kernel))
6409 WrapperKind = X86ISD::WrapperRIP;
6410 else if (Subtarget->isPICStyleGOT())
6411 OpFlag = X86II::MO_GOTOFF;
6412 else if (Subtarget->isPICStyleStubPIC())
6413 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6415 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6417 DebugLoc DL = Op.getDebugLoc();
6418 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6421 // With PIC, the address is actually $g + Offset.
6422 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6423 !Subtarget->is64Bit()) {
6424 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6425 DAG.getNode(X86ISD::GlobalBaseReg,
6426 DebugLoc(), getPointerTy()),
6434 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6435 // Create the TargetBlockAddressAddress node.
6436 unsigned char OpFlags =
6437 Subtarget->ClassifyBlockAddressReference();
6438 CodeModel::Model M = getTargetMachine().getCodeModel();
6439 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6440 DebugLoc dl = Op.getDebugLoc();
6441 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6442 /*isTarget=*/true, OpFlags);
6444 if (Subtarget->isPICStyleRIPRel() &&
6445 (M == CodeModel::Small || M == CodeModel::Kernel))
6446 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6448 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6450 // With PIC, the address is actually $g + Offset.
6451 if (isGlobalRelativeToPICBase(OpFlags)) {
6452 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6453 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6461 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6463 SelectionDAG &DAG) const {
6464 // Create the TargetGlobalAddress node, folding in the constant
6465 // offset if it is legal.
6466 unsigned char OpFlags =
6467 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6468 CodeModel::Model M = getTargetMachine().getCodeModel();
6470 if (OpFlags == X86II::MO_NO_FLAG &&
6471 X86::isOffsetSuitableForCodeModel(Offset, M)) {
6472 // A direct static reference to a global.
6473 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6476 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6479 if (Subtarget->isPICStyleRIPRel() &&
6480 (M == CodeModel::Small || M == CodeModel::Kernel))
6481 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6483 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6485 // With PIC, the address is actually $g + Offset.
6486 if (isGlobalRelativeToPICBase(OpFlags)) {
6487 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6488 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6492 // For globals that require a load from a stub to get the address, emit the
6494 if (isGlobalStubReference(OpFlags))
6495 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6496 MachinePointerInfo::getGOT(), false, false, 0);
6498 // If there was a non-zero offset that we didn't fold, create an explicit
6501 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6502 DAG.getConstant(Offset, getPointerTy()));
6508 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6509 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6510 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6511 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6515 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6516 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6517 unsigned char OperandFlags) {
6518 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6519 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6520 DebugLoc dl = GA->getDebugLoc();
6521 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6522 GA->getValueType(0),
6526 SDValue Ops[] = { Chain, TGA, *InFlag };
6527 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6529 SDValue Ops[] = { Chain, TGA };
6530 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6533 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6534 MFI->setAdjustsStack(true);
6536 SDValue Flag = Chain.getValue(1);
6537 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6540 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6542 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6545 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6546 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6547 DAG.getNode(X86ISD::GlobalBaseReg,
6548 DebugLoc(), PtrVT), InFlag);
6549 InFlag = Chain.getValue(1);
6551 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6554 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6556 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6558 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6559 X86::RAX, X86II::MO_TLSGD);
6562 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6563 // "local exec" model.
6564 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6565 const EVT PtrVT, TLSModel::Model model,
6567 DebugLoc dl = GA->getDebugLoc();
6569 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6570 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6571 is64Bit ? 257 : 256));
6573 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6574 DAG.getIntPtrConstant(0),
6575 MachinePointerInfo(Ptr), false, false, 0);
6577 unsigned char OperandFlags = 0;
6578 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6580 unsigned WrapperKind = X86ISD::Wrapper;
6581 if (model == TLSModel::LocalExec) {
6582 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6583 } else if (is64Bit) {
6584 assert(model == TLSModel::InitialExec);
6585 OperandFlags = X86II::MO_GOTTPOFF;
6586 WrapperKind = X86ISD::WrapperRIP;
6588 assert(model == TLSModel::InitialExec);
6589 OperandFlags = X86II::MO_INDNTPOFF;
6592 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6594 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6595 GA->getValueType(0),
6596 GA->getOffset(), OperandFlags);
6597 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6599 if (model == TLSModel::InitialExec)
6600 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6601 MachinePointerInfo::getGOT(), false, false, 0);
6603 // The address of the thread local variable is the add of the thread
6604 // pointer with the offset of the variable.
6605 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6609 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6611 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6612 const GlobalValue *GV = GA->getGlobal();
6614 if (Subtarget->isTargetELF()) {
6615 // TODO: implement the "local dynamic" model
6616 // TODO: implement the "initial exec"model for pic executables
6618 // If GV is an alias then use the aliasee for determining
6619 // thread-localness.
6620 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6621 GV = GA->resolveAliasedGlobal(false);
6623 TLSModel::Model model
6624 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6627 case TLSModel::GeneralDynamic:
6628 case TLSModel::LocalDynamic: // not implemented
6629 if (Subtarget->is64Bit())
6630 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6631 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6633 case TLSModel::InitialExec:
6634 case TLSModel::LocalExec:
6635 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6636 Subtarget->is64Bit());
6638 } else if (Subtarget->isTargetDarwin()) {
6639 // Darwin only has one model of TLS. Lower to that.
6640 unsigned char OpFlag = 0;
6641 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6642 X86ISD::WrapperRIP : X86ISD::Wrapper;
6644 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6646 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6647 !Subtarget->is64Bit();
6649 OpFlag = X86II::MO_TLVP_PIC_BASE;
6651 OpFlag = X86II::MO_TLVP;
6652 DebugLoc DL = Op.getDebugLoc();
6653 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6654 GA->getValueType(0),
6655 GA->getOffset(), OpFlag);
6656 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6658 // With PIC32, the address is actually $g + Offset.
6660 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6661 DAG.getNode(X86ISD::GlobalBaseReg,
6662 DebugLoc(), getPointerTy()),
6665 // Lowering the machine isd will make sure everything is in the right
6667 SDValue Chain = DAG.getEntryNode();
6668 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6669 SDValue Args[] = { Chain, Offset };
6670 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6672 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6673 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6674 MFI->setAdjustsStack(true);
6676 // And our return value (tls address) is in the standard call return value
6678 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6679 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6683 "TLS not implemented for this target.");
6685 llvm_unreachable("Unreachable");
6690 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6691 /// take a 2 x i32 value to shift plus a shift amount.
6692 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6693 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6694 EVT VT = Op.getValueType();
6695 unsigned VTBits = VT.getSizeInBits();
6696 DebugLoc dl = Op.getDebugLoc();
6697 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6698 SDValue ShOpLo = Op.getOperand(0);
6699 SDValue ShOpHi = Op.getOperand(1);
6700 SDValue ShAmt = Op.getOperand(2);
6701 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6702 DAG.getConstant(VTBits - 1, MVT::i8))
6703 : DAG.getConstant(0, VT);
6706 if (Op.getOpcode() == ISD::SHL_PARTS) {
6707 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6708 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6710 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6711 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6714 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6715 DAG.getConstant(VTBits, MVT::i8));
6716 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6717 AndNode, DAG.getConstant(0, MVT::i8));
6720 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6721 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6722 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6724 if (Op.getOpcode() == ISD::SHL_PARTS) {
6725 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6726 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6728 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6729 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6732 SDValue Ops[2] = { Lo, Hi };
6733 return DAG.getMergeValues(Ops, 2, dl);
6736 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6737 SelectionDAG &DAG) const {
6738 EVT SrcVT = Op.getOperand(0).getValueType();
6740 if (SrcVT.isVector())
6743 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6744 "Unknown SINT_TO_FP to lower!");
6746 // These are really Legal; return the operand so the caller accepts it as
6748 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6750 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6751 Subtarget->is64Bit()) {
6755 DebugLoc dl = Op.getDebugLoc();
6756 unsigned Size = SrcVT.getSizeInBits()/8;
6757 MachineFunction &MF = DAG.getMachineFunction();
6758 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6759 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6760 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6762 MachinePointerInfo::getFixedStack(SSFI),
6764 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6767 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6769 SelectionDAG &DAG) const {
6771 DebugLoc DL = Op.getDebugLoc();
6773 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6775 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6777 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6779 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6781 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6782 MachineMemOperand *MMO =
6783 DAG.getMachineFunction()
6784 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6785 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6787 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6788 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6790 Tys, Ops, array_lengthof(Ops),
6794 Chain = Result.getValue(1);
6795 SDValue InFlag = Result.getValue(2);
6797 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6798 // shouldn't be necessary except that RFP cannot be live across
6799 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6800 MachineFunction &MF = DAG.getMachineFunction();
6801 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6802 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6803 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6804 Tys = DAG.getVTList(MVT::Other);
6806 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6808 MachineMemOperand *MMO =
6809 DAG.getMachineFunction()
6810 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6811 MachineMemOperand::MOStore, SSFISize, SSFISize);
6813 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6814 Ops, array_lengthof(Ops),
6815 Op.getValueType(), MMO);
6816 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6817 MachinePointerInfo::getFixedStack(SSFI),
6824 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6825 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6826 SelectionDAG &DAG) const {
6827 // This algorithm is not obvious. Here it is in C code, more or less:
6829 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6830 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6831 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6833 // Copy ints to xmm registers.
6834 __m128i xh = _mm_cvtsi32_si128( hi );
6835 __m128i xl = _mm_cvtsi32_si128( lo );
6837 // Combine into low half of a single xmm register.
6838 __m128i x = _mm_unpacklo_epi32( xh, xl );
6842 // Merge in appropriate exponents to give the integer bits the right
6844 x = _mm_unpacklo_epi32( x, exp );
6846 // Subtract away the biases to deal with the IEEE-754 double precision
6848 d = _mm_sub_pd( (__m128d) x, bias );
6850 // All conversions up to here are exact. The correctly rounded result is
6851 // calculated using the current rounding mode using the following
6853 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6854 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6855 // store doesn't really need to be here (except
6856 // maybe to zero the other double)
6861 DebugLoc dl = Op.getDebugLoc();
6862 LLVMContext *Context = DAG.getContext();
6864 // Build some magic constants.
6865 std::vector<Constant*> CV0;
6866 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6867 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6868 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6869 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6870 Constant *C0 = ConstantVector::get(CV0);
6871 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6873 std::vector<Constant*> CV1;
6875 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6877 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6878 Constant *C1 = ConstantVector::get(CV1);
6879 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6881 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6882 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6884 DAG.getIntPtrConstant(1)));
6885 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6886 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6888 DAG.getIntPtrConstant(0)));
6889 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6890 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6891 MachinePointerInfo::getConstantPool(),
6893 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6894 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6895 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6896 MachinePointerInfo::getConstantPool(),
6898 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6900 // Add the halves; easiest way is to swap them into another reg first.
6901 int ShufMask[2] = { 1, -1 };
6902 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6903 DAG.getUNDEF(MVT::v2f64), ShufMask);
6904 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6905 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6906 DAG.getIntPtrConstant(0));
6909 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6910 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6911 SelectionDAG &DAG) const {
6912 DebugLoc dl = Op.getDebugLoc();
6913 // FP constant to bias correct the final result.
6914 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6917 // Load the 32-bit value into an XMM register.
6918 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6919 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6921 DAG.getIntPtrConstant(0)));
6923 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6924 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6925 DAG.getIntPtrConstant(0));
6927 // Or the load with the bias.
6928 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6929 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6930 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6932 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6933 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6934 MVT::v2f64, Bias)));
6935 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6936 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6937 DAG.getIntPtrConstant(0));
6939 // Subtract the bias.
6940 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6942 // Handle final rounding.
6943 EVT DestVT = Op.getValueType();
6945 if (DestVT.bitsLT(MVT::f64)) {
6946 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6947 DAG.getIntPtrConstant(0));
6948 } else if (DestVT.bitsGT(MVT::f64)) {
6949 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6952 // Handle final rounding.
6956 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6957 SelectionDAG &DAG) const {
6958 SDValue N0 = Op.getOperand(0);
6959 DebugLoc dl = Op.getDebugLoc();
6961 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6962 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6963 // the optimization here.
6964 if (DAG.SignBitIsZero(N0))
6965 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6967 EVT SrcVT = N0.getValueType();
6968 EVT DstVT = Op.getValueType();
6969 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6970 return LowerUINT_TO_FP_i64(Op, DAG);
6971 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6972 return LowerUINT_TO_FP_i32(Op, DAG);
6974 // Make a 64-bit buffer, and use it to build an FILD.
6975 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6976 if (SrcVT == MVT::i32) {
6977 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6978 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6979 getPointerTy(), StackSlot, WordOff);
6980 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6981 StackSlot, MachinePointerInfo(),
6983 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6984 OffsetSlot, MachinePointerInfo(),
6986 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6990 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6991 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6992 StackSlot, MachinePointerInfo(),
6994 // For i64 source, we need to add the appropriate power of 2 if the input
6995 // was negative. This is the same as the optimization in
6996 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6997 // we must be careful to do the computation in x87 extended precision, not
6998 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6999 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7000 MachineMemOperand *MMO =
7001 DAG.getMachineFunction()
7002 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7003 MachineMemOperand::MOLoad, 8, 8);
7005 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7006 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7007 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7010 APInt FF(32, 0x5F800000ULL);
7012 // Check whether the sign bit is set.
7013 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7014 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7017 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7018 SDValue FudgePtr = DAG.getConstantPool(
7019 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7022 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7023 SDValue Zero = DAG.getIntPtrConstant(0);
7024 SDValue Four = DAG.getIntPtrConstant(4);
7025 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7027 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7029 // Load the value out, extending it from f32 to f80.
7030 // FIXME: Avoid the extend by constructing the right constant pool?
7031 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7032 FudgePtr, MachinePointerInfo::getConstantPool(),
7033 MVT::f32, false, false, 4);
7034 // Extend everything to 80 bits to force it to be done on x87.
7035 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7036 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7039 std::pair<SDValue,SDValue> X86TargetLowering::
7040 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7041 DebugLoc DL = Op.getDebugLoc();
7043 EVT DstTy = Op.getValueType();
7046 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7050 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7051 DstTy.getSimpleVT() >= MVT::i16 &&
7052 "Unknown FP_TO_SINT to lower!");
7054 // These are really Legal.
7055 if (DstTy == MVT::i32 &&
7056 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7057 return std::make_pair(SDValue(), SDValue());
7058 if (Subtarget->is64Bit() &&
7059 DstTy == MVT::i64 &&
7060 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7061 return std::make_pair(SDValue(), SDValue());
7063 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7065 MachineFunction &MF = DAG.getMachineFunction();
7066 unsigned MemSize = DstTy.getSizeInBits()/8;
7067 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7068 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7073 switch (DstTy.getSimpleVT().SimpleTy) {
7074 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7075 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7076 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7077 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7080 SDValue Chain = DAG.getEntryNode();
7081 SDValue Value = Op.getOperand(0);
7082 EVT TheVT = Op.getOperand(0).getValueType();
7083 if (isScalarFPTypeInSSEReg(TheVT)) {
7084 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7085 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7086 MachinePointerInfo::getFixedStack(SSFI),
7088 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7090 Chain, StackSlot, DAG.getValueType(TheVT)
7093 MachineMemOperand *MMO =
7094 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7095 MachineMemOperand::MOLoad, MemSize, MemSize);
7096 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7098 Chain = Value.getValue(1);
7099 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7100 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7103 MachineMemOperand *MMO =
7104 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7105 MachineMemOperand::MOStore, MemSize, MemSize);
7107 // Build the FP_TO_INT*_IN_MEM
7108 SDValue Ops[] = { Chain, Value, StackSlot };
7109 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7110 Ops, 3, DstTy, MMO);
7112 return std::make_pair(FIST, StackSlot);
7115 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7116 SelectionDAG &DAG) const {
7117 if (Op.getValueType().isVector())
7120 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7121 SDValue FIST = Vals.first, StackSlot = Vals.second;
7122 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7123 if (FIST.getNode() == 0) return Op;
7126 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7127 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7130 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7131 SelectionDAG &DAG) const {
7132 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7133 SDValue FIST = Vals.first, StackSlot = Vals.second;
7134 assert(FIST.getNode() && "Unexpected failure");
7137 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7138 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7141 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7142 SelectionDAG &DAG) const {
7143 LLVMContext *Context = DAG.getContext();
7144 DebugLoc dl = Op.getDebugLoc();
7145 EVT VT = Op.getValueType();
7148 EltVT = VT.getVectorElementType();
7149 std::vector<Constant*> CV;
7150 if (EltVT == MVT::f64) {
7151 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7155 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7161 Constant *C = ConstantVector::get(CV);
7162 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7163 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7164 MachinePointerInfo::getConstantPool(),
7166 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7169 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7170 LLVMContext *Context = DAG.getContext();
7171 DebugLoc dl = Op.getDebugLoc();
7172 EVT VT = Op.getValueType();
7175 EltVT = VT.getVectorElementType();
7176 std::vector<Constant*> CV;
7177 if (EltVT == MVT::f64) {
7178 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7182 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7188 Constant *C = ConstantVector::get(CV);
7189 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7190 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7191 MachinePointerInfo::getConstantPool(),
7193 if (VT.isVector()) {
7194 return DAG.getNode(ISD::BITCAST, dl, VT,
7195 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7196 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7198 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7200 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7204 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7205 LLVMContext *Context = DAG.getContext();
7206 SDValue Op0 = Op.getOperand(0);
7207 SDValue Op1 = Op.getOperand(1);
7208 DebugLoc dl = Op.getDebugLoc();
7209 EVT VT = Op.getValueType();
7210 EVT SrcVT = Op1.getValueType();
7212 // If second operand is smaller, extend it first.
7213 if (SrcVT.bitsLT(VT)) {
7214 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7217 // And if it is bigger, shrink it first.
7218 if (SrcVT.bitsGT(VT)) {
7219 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7223 // At this point the operands and the result should have the same
7224 // type, and that won't be f80 since that is not custom lowered.
7226 // First get the sign bit of second operand.
7227 std::vector<Constant*> CV;
7228 if (SrcVT == MVT::f64) {
7229 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7230 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7232 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7233 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7234 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7235 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7237 Constant *C = ConstantVector::get(CV);
7238 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7239 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7240 MachinePointerInfo::getConstantPool(),
7242 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7244 // Shift sign bit right or left if the two operands have different types.
7245 if (SrcVT.bitsGT(VT)) {
7246 // Op0 is MVT::f32, Op1 is MVT::f64.
7247 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7248 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7249 DAG.getConstant(32, MVT::i32));
7250 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7251 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7252 DAG.getIntPtrConstant(0));
7255 // Clear first operand sign bit.
7257 if (VT == MVT::f64) {
7258 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7259 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7261 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7262 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7263 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7264 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7266 C = ConstantVector::get(CV);
7267 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7268 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7269 MachinePointerInfo::getConstantPool(),
7271 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7273 // Or the value with the sign bit.
7274 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7277 /// Emit nodes that will be selected as "test Op0,Op0", or something
7279 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7280 SelectionDAG &DAG) const {
7281 DebugLoc dl = Op.getDebugLoc();
7283 // CF and OF aren't always set the way we want. Determine which
7284 // of these we need.
7285 bool NeedCF = false;
7286 bool NeedOF = false;
7289 case X86::COND_A: case X86::COND_AE:
7290 case X86::COND_B: case X86::COND_BE:
7293 case X86::COND_G: case X86::COND_GE:
7294 case X86::COND_L: case X86::COND_LE:
7295 case X86::COND_O: case X86::COND_NO:
7300 // See if we can use the EFLAGS value from the operand instead of
7301 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7302 // we prove that the arithmetic won't overflow, we can't use OF or CF.
7303 if (Op.getResNo() != 0 || NeedOF || NeedCF)
7304 // Emit a CMP with 0, which is the TEST pattern.
7305 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7306 DAG.getConstant(0, Op.getValueType()));
7308 unsigned Opcode = 0;
7309 unsigned NumOperands = 0;
7310 switch (Op.getNode()->getOpcode()) {
7312 // Due to an isel shortcoming, be conservative if this add is likely to be
7313 // selected as part of a load-modify-store instruction. When the root node
7314 // in a match is a store, isel doesn't know how to remap non-chain non-flag
7315 // uses of other nodes in the match, such as the ADD in this case. This
7316 // leads to the ADD being left around and reselected, with the result being
7317 // two adds in the output. Alas, even if none our users are stores, that
7318 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
7319 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
7320 // climbing the DAG back to the root, and it doesn't seem to be worth the
7322 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7323 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7324 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7327 if (ConstantSDNode *C =
7328 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7329 // An add of one will be selected as an INC.
7330 if (C->getAPIntValue() == 1) {
7331 Opcode = X86ISD::INC;
7336 // An add of negative one (subtract of one) will be selected as a DEC.
7337 if (C->getAPIntValue().isAllOnesValue()) {
7338 Opcode = X86ISD::DEC;
7344 // Otherwise use a regular EFLAGS-setting add.
7345 Opcode = X86ISD::ADD;
7349 // If the primary and result isn't used, don't bother using X86ISD::AND,
7350 // because a TEST instruction will be better.
7351 bool NonFlagUse = false;
7352 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7353 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7355 unsigned UOpNo = UI.getOperandNo();
7356 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7357 // Look pass truncate.
7358 UOpNo = User->use_begin().getOperandNo();
7359 User = *User->use_begin();
7362 if (User->getOpcode() != ISD::BRCOND &&
7363 User->getOpcode() != ISD::SETCC &&
7364 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7377 // Due to the ISEL shortcoming noted above, be conservative if this op is
7378 // likely to be selected as part of a load-modify-store instruction.
7379 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7380 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7381 if (UI->getOpcode() == ISD::STORE)
7384 // Otherwise use a regular EFLAGS-setting instruction.
7385 switch (Op.getNode()->getOpcode()) {
7386 default: llvm_unreachable("unexpected operator!");
7387 case ISD::SUB: Opcode = X86ISD::SUB; break;
7388 case ISD::OR: Opcode = X86ISD::OR; break;
7389 case ISD::XOR: Opcode = X86ISD::XOR; break;
7390 case ISD::AND: Opcode = X86ISD::AND; break;
7402 return SDValue(Op.getNode(), 1);
7409 // Emit a CMP with 0, which is the TEST pattern.
7410 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7411 DAG.getConstant(0, Op.getValueType()));
7413 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7414 SmallVector<SDValue, 4> Ops;
7415 for (unsigned i = 0; i != NumOperands; ++i)
7416 Ops.push_back(Op.getOperand(i));
7418 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7419 DAG.ReplaceAllUsesWith(Op, New);
7420 return SDValue(New.getNode(), 1);
7423 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7425 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7426 SelectionDAG &DAG) const {
7427 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7428 if (C->getAPIntValue() == 0)
7429 return EmitTest(Op0, X86CC, DAG);
7431 DebugLoc dl = Op0.getDebugLoc();
7432 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7435 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7436 /// if it's possible.
7437 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7438 DebugLoc dl, SelectionDAG &DAG) const {
7439 SDValue Op0 = And.getOperand(0);
7440 SDValue Op1 = And.getOperand(1);
7441 if (Op0.getOpcode() == ISD::TRUNCATE)
7442 Op0 = Op0.getOperand(0);
7443 if (Op1.getOpcode() == ISD::TRUNCATE)
7444 Op1 = Op1.getOperand(0);
7447 if (Op1.getOpcode() == ISD::SHL)
7448 std::swap(Op0, Op1);
7449 if (Op0.getOpcode() == ISD::SHL) {
7450 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7451 if (And00C->getZExtValue() == 1) {
7452 // If we looked past a truncate, check that it's only truncating away
7454 unsigned BitWidth = Op0.getValueSizeInBits();
7455 unsigned AndBitWidth = And.getValueSizeInBits();
7456 if (BitWidth > AndBitWidth) {
7457 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7458 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7459 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7463 RHS = Op0.getOperand(1);
7465 } else if (Op1.getOpcode() == ISD::Constant) {
7466 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7467 SDValue AndLHS = Op0;
7468 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7469 LHS = AndLHS.getOperand(0);
7470 RHS = AndLHS.getOperand(1);
7474 if (LHS.getNode()) {
7475 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
7476 // instruction. Since the shift amount is in-range-or-undefined, we know
7477 // that doing a bittest on the i32 value is ok. We extend to i32 because
7478 // the encoding for the i16 version is larger than the i32 version.
7479 // Also promote i16 to i32 for performance / code size reason.
7480 if (LHS.getValueType() == MVT::i8 ||
7481 LHS.getValueType() == MVT::i16)
7482 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7484 // If the operand types disagree, extend the shift amount to match. Since
7485 // BT ignores high bits (like shifts) we can use anyextend.
7486 if (LHS.getValueType() != RHS.getValueType())
7487 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7489 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7490 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7491 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7492 DAG.getConstant(Cond, MVT::i8), BT);
7498 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7499 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7500 SDValue Op0 = Op.getOperand(0);
7501 SDValue Op1 = Op.getOperand(1);
7502 DebugLoc dl = Op.getDebugLoc();
7503 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7505 // Optimize to BT if possible.
7506 // Lower (X & (1 << N)) == 0 to BT(X, N).
7507 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7508 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7509 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7510 Op1.getOpcode() == ISD::Constant &&
7511 cast<ConstantSDNode>(Op1)->isNullValue() &&
7512 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7513 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7514 if (NewSetCC.getNode())
7518 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
7520 if (Op1.getOpcode() == ISD::Constant &&
7521 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7522 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7523 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7525 // If the input is a setcc, then reuse the input setcc or use a new one with
7526 // the inverted condition.
7527 if (Op0.getOpcode() == X86ISD::SETCC) {
7528 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7529 bool Invert = (CC == ISD::SETNE) ^
7530 cast<ConstantSDNode>(Op1)->isNullValue();
7531 if (!Invert) return Op0;
7533 CCode = X86::GetOppositeBranchCondition(CCode);
7534 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7535 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7539 bool isFP = Op1.getValueType().isFloatingPoint();
7540 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7541 if (X86CC == X86::COND_INVALID)
7544 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7545 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7546 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7549 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7551 SDValue Op0 = Op.getOperand(0);
7552 SDValue Op1 = Op.getOperand(1);
7553 SDValue CC = Op.getOperand(2);
7554 EVT VT = Op.getValueType();
7555 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7556 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7557 DebugLoc dl = Op.getDebugLoc();
7561 EVT VT0 = Op0.getValueType();
7562 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7563 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7566 switch (SetCCOpcode) {
7569 case ISD::SETEQ: SSECC = 0; break;
7571 case ISD::SETGT: Swap = true; // Fallthrough
7573 case ISD::SETOLT: SSECC = 1; break;
7575 case ISD::SETGE: Swap = true; // Fallthrough
7577 case ISD::SETOLE: SSECC = 2; break;
7578 case ISD::SETUO: SSECC = 3; break;
7580 case ISD::SETNE: SSECC = 4; break;
7581 case ISD::SETULE: Swap = true;
7582 case ISD::SETUGE: SSECC = 5; break;
7583 case ISD::SETULT: Swap = true;
7584 case ISD::SETUGT: SSECC = 6; break;
7585 case ISD::SETO: SSECC = 7; break;
7588 std::swap(Op0, Op1);
7590 // In the two special cases we can't handle, emit two comparisons.
7592 if (SetCCOpcode == ISD::SETUEQ) {
7594 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7595 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7596 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7598 else if (SetCCOpcode == ISD::SETONE) {
7600 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7601 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7602 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7604 llvm_unreachable("Illegal FP comparison");
7606 // Handle all other FP comparisons here.
7607 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7610 // We are handling one of the integer comparisons here. Since SSE only has
7611 // GT and EQ comparisons for integer, swapping operands and multiple
7612 // operations may be required for some comparisons.
7613 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7614 bool Swap = false, Invert = false, FlipSigns = false;
7616 switch (VT.getSimpleVT().SimpleTy) {
7618 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7619 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7620 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7621 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7624 switch (SetCCOpcode) {
7626 case ISD::SETNE: Invert = true;
7627 case ISD::SETEQ: Opc = EQOpc; break;
7628 case ISD::SETLT: Swap = true;
7629 case ISD::SETGT: Opc = GTOpc; break;
7630 case ISD::SETGE: Swap = true;
7631 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7632 case ISD::SETULT: Swap = true;
7633 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7634 case ISD::SETUGE: Swap = true;
7635 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7638 std::swap(Op0, Op1);
7640 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7641 // bits of the inputs before performing those operations.
7643 EVT EltVT = VT.getVectorElementType();
7644 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7646 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7647 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7649 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7650 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7653 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7655 // If the logical-not of the result is required, perform that now.
7657 Result = DAG.getNOT(dl, Result, VT);
7662 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7663 static bool isX86LogicalCmp(SDValue Op) {
7664 unsigned Opc = Op.getNode()->getOpcode();
7665 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7667 if (Op.getResNo() == 1 &&
7668 (Opc == X86ISD::ADD ||
7669 Opc == X86ISD::SUB ||
7670 Opc == X86ISD::ADC ||
7671 Opc == X86ISD::SBB ||
7672 Opc == X86ISD::SMUL ||
7673 Opc == X86ISD::UMUL ||
7674 Opc == X86ISD::INC ||
7675 Opc == X86ISD::DEC ||
7676 Opc == X86ISD::OR ||
7677 Opc == X86ISD::XOR ||
7678 Opc == X86ISD::AND))
7681 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7687 static bool isZero(SDValue V) {
7688 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7689 return C && C->isNullValue();
7692 static bool isAllOnes(SDValue V) {
7693 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7694 return C && C->isAllOnesValue();
7697 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7698 bool addTest = true;
7699 SDValue Cond = Op.getOperand(0);
7700 SDValue Op1 = Op.getOperand(1);
7701 SDValue Op2 = Op.getOperand(2);
7702 DebugLoc DL = Op.getDebugLoc();
7705 if (Cond.getOpcode() == ISD::SETCC) {
7706 SDValue NewCond = LowerSETCC(Cond, DAG);
7707 if (NewCond.getNode())
7711 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7712 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7713 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7714 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7715 if (Cond.getOpcode() == X86ISD::SETCC &&
7716 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7717 isZero(Cond.getOperand(1).getOperand(1))) {
7718 SDValue Cmp = Cond.getOperand(1);
7720 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7722 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7723 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7724 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7726 SDValue CmpOp0 = Cmp.getOperand(0);
7727 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7728 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7730 SDValue Res = // Res = 0 or -1.
7731 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7732 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7734 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7735 Res = DAG.getNOT(DL, Res, Res.getValueType());
7737 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7738 if (N2C == 0 || !N2C->isNullValue())
7739 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7744 // Look past (and (setcc_carry (cmp ...)), 1).
7745 if (Cond.getOpcode() == ISD::AND &&
7746 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7747 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7748 if (C && C->getAPIntValue() == 1)
7749 Cond = Cond.getOperand(0);
7752 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7753 // setting operand in place of the X86ISD::SETCC.
7754 if (Cond.getOpcode() == X86ISD::SETCC ||
7755 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7756 CC = Cond.getOperand(0);
7758 SDValue Cmp = Cond.getOperand(1);
7759 unsigned Opc = Cmp.getOpcode();
7760 EVT VT = Op.getValueType();
7762 bool IllegalFPCMov = false;
7763 if (VT.isFloatingPoint() && !VT.isVector() &&
7764 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7765 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7767 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7768 Opc == X86ISD::BT) { // FIXME
7775 // Look pass the truncate.
7776 if (Cond.getOpcode() == ISD::TRUNCATE)
7777 Cond = Cond.getOperand(0);
7779 // We know the result of AND is compared against zero. Try to match
7781 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7782 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7783 if (NewSetCC.getNode()) {
7784 CC = NewSetCC.getOperand(0);
7785 Cond = NewSetCC.getOperand(1);
7792 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7793 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7796 // a < b ? -1 : 0 -> RES = ~setcc_carry
7797 // a < b ? 0 : -1 -> RES = setcc_carry
7798 // a >= b ? -1 : 0 -> RES = setcc_carry
7799 // a >= b ? 0 : -1 -> RES = ~setcc_carry
7800 if (Cond.getOpcode() == X86ISD::CMP) {
7801 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7803 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7804 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7805 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7806 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7807 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7808 return DAG.getNOT(DL, Res, Res.getValueType());
7813 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7814 // condition is true.
7815 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7816 SDValue Ops[] = { Op2, Op1, CC, Cond };
7817 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7820 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7821 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7822 // from the AND / OR.
7823 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7824 Opc = Op.getOpcode();
7825 if (Opc != ISD::OR && Opc != ISD::AND)
7827 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7828 Op.getOperand(0).hasOneUse() &&
7829 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7830 Op.getOperand(1).hasOneUse());
7833 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7834 // 1 and that the SETCC node has a single use.
7835 static bool isXor1OfSetCC(SDValue Op) {
7836 if (Op.getOpcode() != ISD::XOR)
7838 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7839 if (N1C && N1C->getAPIntValue() == 1) {
7840 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7841 Op.getOperand(0).hasOneUse();
7846 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7847 bool addTest = true;
7848 SDValue Chain = Op.getOperand(0);
7849 SDValue Cond = Op.getOperand(1);
7850 SDValue Dest = Op.getOperand(2);
7851 DebugLoc dl = Op.getDebugLoc();
7854 if (Cond.getOpcode() == ISD::SETCC) {
7855 SDValue NewCond = LowerSETCC(Cond, DAG);
7856 if (NewCond.getNode())
7860 // FIXME: LowerXALUO doesn't handle these!!
7861 else if (Cond.getOpcode() == X86ISD::ADD ||
7862 Cond.getOpcode() == X86ISD::SUB ||
7863 Cond.getOpcode() == X86ISD::SMUL ||
7864 Cond.getOpcode() == X86ISD::UMUL)
7865 Cond = LowerXALUO(Cond, DAG);
7868 // Look pass (and (setcc_carry (cmp ...)), 1).
7869 if (Cond.getOpcode() == ISD::AND &&
7870 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7871 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7872 if (C && C->getAPIntValue() == 1)
7873 Cond = Cond.getOperand(0);
7876 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7877 // setting operand in place of the X86ISD::SETCC.
7878 if (Cond.getOpcode() == X86ISD::SETCC ||
7879 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7880 CC = Cond.getOperand(0);
7882 SDValue Cmp = Cond.getOperand(1);
7883 unsigned Opc = Cmp.getOpcode();
7884 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7885 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7889 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7893 // These can only come from an arithmetic instruction with overflow,
7894 // e.g. SADDO, UADDO.
7895 Cond = Cond.getNode()->getOperand(1);
7902 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7903 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7904 if (CondOpc == ISD::OR) {
7905 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7906 // two branches instead of an explicit OR instruction with a
7908 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7909 isX86LogicalCmp(Cmp)) {
7910 CC = Cond.getOperand(0).getOperand(0);
7911 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7912 Chain, Dest, CC, Cmp);
7913 CC = Cond.getOperand(1).getOperand(0);
7917 } else { // ISD::AND
7918 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7919 // two branches instead of an explicit AND instruction with a
7920 // separate test. However, we only do this if this block doesn't
7921 // have a fall-through edge, because this requires an explicit
7922 // jmp when the condition is false.
7923 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7924 isX86LogicalCmp(Cmp) &&
7925 Op.getNode()->hasOneUse()) {
7926 X86::CondCode CCode =
7927 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7928 CCode = X86::GetOppositeBranchCondition(CCode);
7929 CC = DAG.getConstant(CCode, MVT::i8);
7930 SDNode *User = *Op.getNode()->use_begin();
7931 // Look for an unconditional branch following this conditional branch.
7932 // We need this because we need to reverse the successors in order
7933 // to implement FCMP_OEQ.
7934 if (User->getOpcode() == ISD::BR) {
7935 SDValue FalseBB = User->getOperand(1);
7937 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7938 assert(NewBR == User);
7942 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7943 Chain, Dest, CC, Cmp);
7944 X86::CondCode CCode =
7945 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7946 CCode = X86::GetOppositeBranchCondition(CCode);
7947 CC = DAG.getConstant(CCode, MVT::i8);
7953 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7954 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7955 // It should be transformed during dag combiner except when the condition
7956 // is set by a arithmetics with overflow node.
7957 X86::CondCode CCode =
7958 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7959 CCode = X86::GetOppositeBranchCondition(CCode);
7960 CC = DAG.getConstant(CCode, MVT::i8);
7961 Cond = Cond.getOperand(0).getOperand(1);
7967 // Look pass the truncate.
7968 if (Cond.getOpcode() == ISD::TRUNCATE)
7969 Cond = Cond.getOperand(0);
7971 // We know the result of AND is compared against zero. Try to match
7973 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7974 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7975 if (NewSetCC.getNode()) {
7976 CC = NewSetCC.getOperand(0);
7977 Cond = NewSetCC.getOperand(1);
7984 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7985 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7987 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7988 Chain, Dest, CC, Cond);
7992 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7993 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7994 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7995 // that the guard pages used by the OS virtual memory manager are allocated in
7996 // correct sequence.
7998 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7999 SelectionDAG &DAG) const {
8000 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8001 "This should be used only on Windows targets");
8002 assert(!Subtarget->isTargetEnvMacho());
8003 DebugLoc dl = Op.getDebugLoc();
8006 SDValue Chain = Op.getOperand(0);
8007 SDValue Size = Op.getOperand(1);
8008 // FIXME: Ensure alignment here
8012 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8013 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8015 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8016 Flag = Chain.getValue(1);
8018 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8020 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8021 Flag = Chain.getValue(1);
8023 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8025 SDValue Ops1[2] = { Chain.getValue(0), Chain };
8026 return DAG.getMergeValues(Ops1, 2, dl);
8029 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8030 MachineFunction &MF = DAG.getMachineFunction();
8031 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8033 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8034 DebugLoc DL = Op.getDebugLoc();
8036 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8037 // vastart just stores the address of the VarArgsFrameIndex slot into the
8038 // memory location argument.
8039 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8041 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8042 MachinePointerInfo(SV), false, false, 0);
8046 // gp_offset (0 - 6 * 8)
8047 // fp_offset (48 - 48 + 8 * 16)
8048 // overflow_arg_area (point to parameters coming in memory).
8050 SmallVector<SDValue, 8> MemOps;
8051 SDValue FIN = Op.getOperand(1);
8053 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8054 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8056 FIN, MachinePointerInfo(SV), false, false, 0);
8057 MemOps.push_back(Store);
8060 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8061 FIN, DAG.getIntPtrConstant(4));
8062 Store = DAG.getStore(Op.getOperand(0), DL,
8063 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8065 FIN, MachinePointerInfo(SV, 4), false, false, 0);
8066 MemOps.push_back(Store);
8068 // Store ptr to overflow_arg_area
8069 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8070 FIN, DAG.getIntPtrConstant(4));
8071 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8073 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8074 MachinePointerInfo(SV, 8),
8076 MemOps.push_back(Store);
8078 // Store ptr to reg_save_area.
8079 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8080 FIN, DAG.getIntPtrConstant(8));
8081 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8083 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8084 MachinePointerInfo(SV, 16), false, false, 0);
8085 MemOps.push_back(Store);
8086 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8087 &MemOps[0], MemOps.size());
8090 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8091 assert(Subtarget->is64Bit() &&
8092 "LowerVAARG only handles 64-bit va_arg!");
8093 assert((Subtarget->isTargetLinux() ||
8094 Subtarget->isTargetDarwin()) &&
8095 "Unhandled target in LowerVAARG");
8096 assert(Op.getNode()->getNumOperands() == 4);
8097 SDValue Chain = Op.getOperand(0);
8098 SDValue SrcPtr = Op.getOperand(1);
8099 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8100 unsigned Align = Op.getConstantOperandVal(3);
8101 DebugLoc dl = Op.getDebugLoc();
8103 EVT ArgVT = Op.getNode()->getValueType(0);
8104 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8105 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8108 // Decide which area this value should be read from.
8109 // TODO: Implement the AMD64 ABI in its entirety. This simple
8110 // selection mechanism works only for the basic types.
8111 if (ArgVT == MVT::f80) {
8112 llvm_unreachable("va_arg for f80 not yet implemented");
8113 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8114 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
8115 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8116 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
8118 llvm_unreachable("Unhandled argument type in LowerVAARG");
8122 // Sanity Check: Make sure using fp_offset makes sense.
8123 assert(!UseSoftFloat &&
8124 !(DAG.getMachineFunction()
8125 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8126 Subtarget->hasXMM());
8129 // Insert VAARG_64 node into the DAG
8130 // VAARG_64 returns two values: Variable Argument Address, Chain
8131 SmallVector<SDValue, 11> InstOps;
8132 InstOps.push_back(Chain);
8133 InstOps.push_back(SrcPtr);
8134 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8135 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8136 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8137 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8138 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8139 VTs, &InstOps[0], InstOps.size(),
8141 MachinePointerInfo(SV),
8146 Chain = VAARG.getValue(1);
8148 // Load the next argument and return it
8149 return DAG.getLoad(ArgVT, dl,
8152 MachinePointerInfo(),
8156 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8157 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8158 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8159 SDValue Chain = Op.getOperand(0);
8160 SDValue DstPtr = Op.getOperand(1);
8161 SDValue SrcPtr = Op.getOperand(2);
8162 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8163 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8164 DebugLoc DL = Op.getDebugLoc();
8166 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8167 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8169 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8173 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8174 DebugLoc dl = Op.getDebugLoc();
8175 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8177 default: return SDValue(); // Don't custom lower most intrinsics.
8178 // Comparison intrinsics.
8179 case Intrinsic::x86_sse_comieq_ss:
8180 case Intrinsic::x86_sse_comilt_ss:
8181 case Intrinsic::x86_sse_comile_ss:
8182 case Intrinsic::x86_sse_comigt_ss:
8183 case Intrinsic::x86_sse_comige_ss:
8184 case Intrinsic::x86_sse_comineq_ss:
8185 case Intrinsic::x86_sse_ucomieq_ss:
8186 case Intrinsic::x86_sse_ucomilt_ss:
8187 case Intrinsic::x86_sse_ucomile_ss:
8188 case Intrinsic::x86_sse_ucomigt_ss:
8189 case Intrinsic::x86_sse_ucomige_ss:
8190 case Intrinsic::x86_sse_ucomineq_ss:
8191 case Intrinsic::x86_sse2_comieq_sd:
8192 case Intrinsic::x86_sse2_comilt_sd:
8193 case Intrinsic::x86_sse2_comile_sd:
8194 case Intrinsic::x86_sse2_comigt_sd:
8195 case Intrinsic::x86_sse2_comige_sd:
8196 case Intrinsic::x86_sse2_comineq_sd:
8197 case Intrinsic::x86_sse2_ucomieq_sd:
8198 case Intrinsic::x86_sse2_ucomilt_sd:
8199 case Intrinsic::x86_sse2_ucomile_sd:
8200 case Intrinsic::x86_sse2_ucomigt_sd:
8201 case Intrinsic::x86_sse2_ucomige_sd:
8202 case Intrinsic::x86_sse2_ucomineq_sd: {
8204 ISD::CondCode CC = ISD::SETCC_INVALID;
8207 case Intrinsic::x86_sse_comieq_ss:
8208 case Intrinsic::x86_sse2_comieq_sd:
8212 case Intrinsic::x86_sse_comilt_ss:
8213 case Intrinsic::x86_sse2_comilt_sd:
8217 case Intrinsic::x86_sse_comile_ss:
8218 case Intrinsic::x86_sse2_comile_sd:
8222 case Intrinsic::x86_sse_comigt_ss:
8223 case Intrinsic::x86_sse2_comigt_sd:
8227 case Intrinsic::x86_sse_comige_ss:
8228 case Intrinsic::x86_sse2_comige_sd:
8232 case Intrinsic::x86_sse_comineq_ss:
8233 case Intrinsic::x86_sse2_comineq_sd:
8237 case Intrinsic::x86_sse_ucomieq_ss:
8238 case Intrinsic::x86_sse2_ucomieq_sd:
8239 Opc = X86ISD::UCOMI;
8242 case Intrinsic::x86_sse_ucomilt_ss:
8243 case Intrinsic::x86_sse2_ucomilt_sd:
8244 Opc = X86ISD::UCOMI;
8247 case Intrinsic::x86_sse_ucomile_ss:
8248 case Intrinsic::x86_sse2_ucomile_sd:
8249 Opc = X86ISD::UCOMI;
8252 case Intrinsic::x86_sse_ucomigt_ss:
8253 case Intrinsic::x86_sse2_ucomigt_sd:
8254 Opc = X86ISD::UCOMI;
8257 case Intrinsic::x86_sse_ucomige_ss:
8258 case Intrinsic::x86_sse2_ucomige_sd:
8259 Opc = X86ISD::UCOMI;
8262 case Intrinsic::x86_sse_ucomineq_ss:
8263 case Intrinsic::x86_sse2_ucomineq_sd:
8264 Opc = X86ISD::UCOMI;
8269 SDValue LHS = Op.getOperand(1);
8270 SDValue RHS = Op.getOperand(2);
8271 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8272 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8273 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8274 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8275 DAG.getConstant(X86CC, MVT::i8), Cond);
8276 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8278 // ptest and testp intrinsics. The intrinsic these come from are designed to
8279 // return an integer value, not just an instruction so lower it to the ptest
8280 // or testp pattern and a setcc for the result.
8281 case Intrinsic::x86_sse41_ptestz:
8282 case Intrinsic::x86_sse41_ptestc:
8283 case Intrinsic::x86_sse41_ptestnzc:
8284 case Intrinsic::x86_avx_ptestz_256:
8285 case Intrinsic::x86_avx_ptestc_256:
8286 case Intrinsic::x86_avx_ptestnzc_256:
8287 case Intrinsic::x86_avx_vtestz_ps:
8288 case Intrinsic::x86_avx_vtestc_ps:
8289 case Intrinsic::x86_avx_vtestnzc_ps:
8290 case Intrinsic::x86_avx_vtestz_pd:
8291 case Intrinsic::x86_avx_vtestc_pd:
8292 case Intrinsic::x86_avx_vtestnzc_pd:
8293 case Intrinsic::x86_avx_vtestz_ps_256:
8294 case Intrinsic::x86_avx_vtestc_ps_256:
8295 case Intrinsic::x86_avx_vtestnzc_ps_256:
8296 case Intrinsic::x86_avx_vtestz_pd_256:
8297 case Intrinsic::x86_avx_vtestc_pd_256:
8298 case Intrinsic::x86_avx_vtestnzc_pd_256: {
8299 bool IsTestPacked = false;
8302 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8303 case Intrinsic::x86_avx_vtestz_ps:
8304 case Intrinsic::x86_avx_vtestz_pd:
8305 case Intrinsic::x86_avx_vtestz_ps_256:
8306 case Intrinsic::x86_avx_vtestz_pd_256:
8307 IsTestPacked = true; // Fallthrough
8308 case Intrinsic::x86_sse41_ptestz:
8309 case Intrinsic::x86_avx_ptestz_256:
8311 X86CC = X86::COND_E;
8313 case Intrinsic::x86_avx_vtestc_ps:
8314 case Intrinsic::x86_avx_vtestc_pd:
8315 case Intrinsic::x86_avx_vtestc_ps_256:
8316 case Intrinsic::x86_avx_vtestc_pd_256:
8317 IsTestPacked = true; // Fallthrough
8318 case Intrinsic::x86_sse41_ptestc:
8319 case Intrinsic::x86_avx_ptestc_256:
8321 X86CC = X86::COND_B;
8323 case Intrinsic::x86_avx_vtestnzc_ps:
8324 case Intrinsic::x86_avx_vtestnzc_pd:
8325 case Intrinsic::x86_avx_vtestnzc_ps_256:
8326 case Intrinsic::x86_avx_vtestnzc_pd_256:
8327 IsTestPacked = true; // Fallthrough
8328 case Intrinsic::x86_sse41_ptestnzc:
8329 case Intrinsic::x86_avx_ptestnzc_256:
8331 X86CC = X86::COND_A;
8335 SDValue LHS = Op.getOperand(1);
8336 SDValue RHS = Op.getOperand(2);
8337 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8338 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8339 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8340 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8341 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8344 // Fix vector shift instructions where the last operand is a non-immediate
8346 case Intrinsic::x86_sse2_pslli_w:
8347 case Intrinsic::x86_sse2_pslli_d:
8348 case Intrinsic::x86_sse2_pslli_q:
8349 case Intrinsic::x86_sse2_psrli_w:
8350 case Intrinsic::x86_sse2_psrli_d:
8351 case Intrinsic::x86_sse2_psrli_q:
8352 case Intrinsic::x86_sse2_psrai_w:
8353 case Intrinsic::x86_sse2_psrai_d:
8354 case Intrinsic::x86_mmx_pslli_w:
8355 case Intrinsic::x86_mmx_pslli_d:
8356 case Intrinsic::x86_mmx_pslli_q:
8357 case Intrinsic::x86_mmx_psrli_w:
8358 case Intrinsic::x86_mmx_psrli_d:
8359 case Intrinsic::x86_mmx_psrli_q:
8360 case Intrinsic::x86_mmx_psrai_w:
8361 case Intrinsic::x86_mmx_psrai_d: {
8362 SDValue ShAmt = Op.getOperand(2);
8363 if (isa<ConstantSDNode>(ShAmt))
8366 unsigned NewIntNo = 0;
8367 EVT ShAmtVT = MVT::v4i32;
8369 case Intrinsic::x86_sse2_pslli_w:
8370 NewIntNo = Intrinsic::x86_sse2_psll_w;
8372 case Intrinsic::x86_sse2_pslli_d:
8373 NewIntNo = Intrinsic::x86_sse2_psll_d;
8375 case Intrinsic::x86_sse2_pslli_q:
8376 NewIntNo = Intrinsic::x86_sse2_psll_q;
8378 case Intrinsic::x86_sse2_psrli_w:
8379 NewIntNo = Intrinsic::x86_sse2_psrl_w;
8381 case Intrinsic::x86_sse2_psrli_d:
8382 NewIntNo = Intrinsic::x86_sse2_psrl_d;
8384 case Intrinsic::x86_sse2_psrli_q:
8385 NewIntNo = Intrinsic::x86_sse2_psrl_q;
8387 case Intrinsic::x86_sse2_psrai_w:
8388 NewIntNo = Intrinsic::x86_sse2_psra_w;
8390 case Intrinsic::x86_sse2_psrai_d:
8391 NewIntNo = Intrinsic::x86_sse2_psra_d;
8394 ShAmtVT = MVT::v2i32;
8396 case Intrinsic::x86_mmx_pslli_w:
8397 NewIntNo = Intrinsic::x86_mmx_psll_w;
8399 case Intrinsic::x86_mmx_pslli_d:
8400 NewIntNo = Intrinsic::x86_mmx_psll_d;
8402 case Intrinsic::x86_mmx_pslli_q:
8403 NewIntNo = Intrinsic::x86_mmx_psll_q;
8405 case Intrinsic::x86_mmx_psrli_w:
8406 NewIntNo = Intrinsic::x86_mmx_psrl_w;
8408 case Intrinsic::x86_mmx_psrli_d:
8409 NewIntNo = Intrinsic::x86_mmx_psrl_d;
8411 case Intrinsic::x86_mmx_psrli_q:
8412 NewIntNo = Intrinsic::x86_mmx_psrl_q;
8414 case Intrinsic::x86_mmx_psrai_w:
8415 NewIntNo = Intrinsic::x86_mmx_psra_w;
8417 case Intrinsic::x86_mmx_psrai_d:
8418 NewIntNo = Intrinsic::x86_mmx_psra_d;
8420 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8426 // The vector shift intrinsics with scalars uses 32b shift amounts but
8427 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8431 ShOps[1] = DAG.getConstant(0, MVT::i32);
8432 if (ShAmtVT == MVT::v4i32) {
8433 ShOps[2] = DAG.getUNDEF(MVT::i32);
8434 ShOps[3] = DAG.getUNDEF(MVT::i32);
8435 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8437 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8438 // FIXME this must be lowered to get rid of the invalid type.
8441 EVT VT = Op.getValueType();
8442 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8443 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8444 DAG.getConstant(NewIntNo, MVT::i32),
8445 Op.getOperand(1), ShAmt);
8450 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8451 SelectionDAG &DAG) const {
8452 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8453 MFI->setReturnAddressIsTaken(true);
8455 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8456 DebugLoc dl = Op.getDebugLoc();
8459 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8461 DAG.getConstant(TD->getPointerSize(),
8462 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8463 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8464 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8466 MachinePointerInfo(), false, false, 0);
8469 // Just load the return address.
8470 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8471 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8472 RetAddrFI, MachinePointerInfo(), false, false, 0);
8475 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8476 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8477 MFI->setFrameAddressIsTaken(true);
8479 EVT VT = Op.getValueType();
8480 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
8481 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8482 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8483 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8485 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8486 MachinePointerInfo(),
8491 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8492 SelectionDAG &DAG) const {
8493 return DAG.getIntPtrConstant(2*TD->getPointerSize());
8496 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8497 MachineFunction &MF = DAG.getMachineFunction();
8498 SDValue Chain = Op.getOperand(0);
8499 SDValue Offset = Op.getOperand(1);
8500 SDValue Handler = Op.getOperand(2);
8501 DebugLoc dl = Op.getDebugLoc();
8503 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8504 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8506 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8508 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8509 DAG.getIntPtrConstant(TD->getPointerSize()));
8510 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8511 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8513 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8514 MF.getRegInfo().addLiveOut(StoreAddrReg);
8516 return DAG.getNode(X86ISD::EH_RETURN, dl,
8518 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8521 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8522 SelectionDAG &DAG) const {
8523 SDValue Root = Op.getOperand(0);
8524 SDValue Trmp = Op.getOperand(1); // trampoline
8525 SDValue FPtr = Op.getOperand(2); // nested function
8526 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8527 DebugLoc dl = Op.getDebugLoc();
8529 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8531 if (Subtarget->is64Bit()) {
8532 SDValue OutChains[6];
8534 // Large code-model.
8535 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8536 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8538 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8539 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8541 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8543 // Load the pointer to the nested function into R11.
8544 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8545 SDValue Addr = Trmp;
8546 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8547 Addr, MachinePointerInfo(TrmpAddr),
8550 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8551 DAG.getConstant(2, MVT::i64));
8552 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8553 MachinePointerInfo(TrmpAddr, 2),
8556 // Load the 'nest' parameter value into R10.
8557 // R10 is specified in X86CallingConv.td
8558 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8559 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8560 DAG.getConstant(10, MVT::i64));
8561 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8562 Addr, MachinePointerInfo(TrmpAddr, 10),
8565 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8566 DAG.getConstant(12, MVT::i64));
8567 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8568 MachinePointerInfo(TrmpAddr, 12),
8571 // Jump to the nested function.
8572 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8573 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8574 DAG.getConstant(20, MVT::i64));
8575 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8576 Addr, MachinePointerInfo(TrmpAddr, 20),
8579 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8580 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8581 DAG.getConstant(22, MVT::i64));
8582 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8583 MachinePointerInfo(TrmpAddr, 22),
8587 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8588 return DAG.getMergeValues(Ops, 2, dl);
8590 const Function *Func =
8591 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8592 CallingConv::ID CC = Func->getCallingConv();
8597 llvm_unreachable("Unsupported calling convention");
8598 case CallingConv::C:
8599 case CallingConv::X86_StdCall: {
8600 // Pass 'nest' parameter in ECX.
8601 // Must be kept in sync with X86CallingConv.td
8604 // Check that ECX wasn't needed by an 'inreg' parameter.
8605 const FunctionType *FTy = Func->getFunctionType();
8606 const AttrListPtr &Attrs = Func->getAttributes();
8608 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8609 unsigned InRegCount = 0;
8612 for (FunctionType::param_iterator I = FTy->param_begin(),
8613 E = FTy->param_end(); I != E; ++I, ++Idx)
8614 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8615 // FIXME: should only count parameters that are lowered to integers.
8616 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8618 if (InRegCount > 2) {
8619 report_fatal_error("Nest register in use - reduce number of inreg"
8625 case CallingConv::X86_FastCall:
8626 case CallingConv::X86_ThisCall:
8627 case CallingConv::Fast:
8628 // Pass 'nest' parameter in EAX.
8629 // Must be kept in sync with X86CallingConv.td
8634 SDValue OutChains[4];
8637 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8638 DAG.getConstant(10, MVT::i32));
8639 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8641 // This is storing the opcode for MOV32ri.
8642 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8643 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8644 OutChains[0] = DAG.getStore(Root, dl,
8645 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8646 Trmp, MachinePointerInfo(TrmpAddr),
8649 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8650 DAG.getConstant(1, MVT::i32));
8651 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8652 MachinePointerInfo(TrmpAddr, 1),
8655 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8656 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8657 DAG.getConstant(5, MVT::i32));
8658 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8659 MachinePointerInfo(TrmpAddr, 5),
8662 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8663 DAG.getConstant(6, MVT::i32));
8664 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8665 MachinePointerInfo(TrmpAddr, 6),
8669 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8670 return DAG.getMergeValues(Ops, 2, dl);
8674 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8675 SelectionDAG &DAG) const {
8677 The rounding mode is in bits 11:10 of FPSR, and has the following
8684 FLT_ROUNDS, on the other hand, expects the following:
8691 To perform the conversion, we do:
8692 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8695 MachineFunction &MF = DAG.getMachineFunction();
8696 const TargetMachine &TM = MF.getTarget();
8697 const TargetFrameLowering &TFI = *TM.getFrameLowering();
8698 unsigned StackAlignment = TFI.getStackAlignment();
8699 EVT VT = Op.getValueType();
8700 DebugLoc DL = Op.getDebugLoc();
8702 // Save FP Control Word to stack slot
8703 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8704 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8707 MachineMemOperand *MMO =
8708 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8709 MachineMemOperand::MOStore, 2, 2);
8711 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8712 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8713 DAG.getVTList(MVT::Other),
8714 Ops, 2, MVT::i16, MMO);
8716 // Load FP Control Word from stack slot
8717 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8718 MachinePointerInfo(), false, false, 0);
8720 // Transform as necessary
8722 DAG.getNode(ISD::SRL, DL, MVT::i16,
8723 DAG.getNode(ISD::AND, DL, MVT::i16,
8724 CWD, DAG.getConstant(0x800, MVT::i16)),
8725 DAG.getConstant(11, MVT::i8));
8727 DAG.getNode(ISD::SRL, DL, MVT::i16,
8728 DAG.getNode(ISD::AND, DL, MVT::i16,
8729 CWD, DAG.getConstant(0x400, MVT::i16)),
8730 DAG.getConstant(9, MVT::i8));
8733 DAG.getNode(ISD::AND, DL, MVT::i16,
8734 DAG.getNode(ISD::ADD, DL, MVT::i16,
8735 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8736 DAG.getConstant(1, MVT::i16)),
8737 DAG.getConstant(3, MVT::i16));
8740 return DAG.getNode((VT.getSizeInBits() < 16 ?
8741 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8744 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8745 EVT VT = Op.getValueType();
8747 unsigned NumBits = VT.getSizeInBits();
8748 DebugLoc dl = Op.getDebugLoc();
8750 Op = Op.getOperand(0);
8751 if (VT == MVT::i8) {
8752 // Zero extend to i32 since there is not an i8 bsr.
8754 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8757 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8758 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8759 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8761 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8764 DAG.getConstant(NumBits+NumBits-1, OpVT),
8765 DAG.getConstant(X86::COND_E, MVT::i8),
8768 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8770 // Finally xor with NumBits-1.
8771 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8774 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8778 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8779 EVT VT = Op.getValueType();
8781 unsigned NumBits = VT.getSizeInBits();
8782 DebugLoc dl = Op.getDebugLoc();
8784 Op = Op.getOperand(0);
8785 if (VT == MVT::i8) {
8787 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8790 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8791 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8792 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8794 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8797 DAG.getConstant(NumBits, OpVT),
8798 DAG.getConstant(X86::COND_E, MVT::i8),
8801 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8804 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8808 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8809 EVT VT = Op.getValueType();
8810 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8811 DebugLoc dl = Op.getDebugLoc();
8813 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8814 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8815 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8816 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8817 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8819 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8820 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8821 // return AloBlo + AloBhi + AhiBlo;
8823 SDValue A = Op.getOperand(0);
8824 SDValue B = Op.getOperand(1);
8826 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8827 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8828 A, DAG.getConstant(32, MVT::i32));
8829 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8830 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8831 B, DAG.getConstant(32, MVT::i32));
8832 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8833 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8835 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8836 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8838 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8839 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8841 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8842 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8843 AloBhi, DAG.getConstant(32, MVT::i32));
8844 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8845 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8846 AhiBlo, DAG.getConstant(32, MVT::i32));
8847 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8848 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8852 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8854 EVT VT = Op.getValueType();
8855 DebugLoc dl = Op.getDebugLoc();
8856 SDValue R = Op.getOperand(0);
8857 SDValue Amt = Op.getOperand(1);
8859 LLVMContext *Context = DAG.getContext();
8862 if (!Subtarget->hasSSE2()) return SDValue();
8864 // Optimize shl/srl/sra with constant shift amount.
8865 if (isSplatVector(Amt.getNode())) {
8866 SDValue SclrAmt = Amt->getOperand(0);
8867 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8868 uint64_t ShiftAmt = C->getZExtValue();
8870 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8871 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8872 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8873 R, DAG.getConstant(ShiftAmt, MVT::i32));
8875 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
8876 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8877 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8878 R, DAG.getConstant(ShiftAmt, MVT::i32));
8880 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
8881 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8882 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8883 R, DAG.getConstant(ShiftAmt, MVT::i32));
8885 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
8886 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8887 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8888 R, DAG.getConstant(ShiftAmt, MVT::i32));
8890 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
8891 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8892 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8893 R, DAG.getConstant(ShiftAmt, MVT::i32));
8895 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
8896 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8897 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8898 R, DAG.getConstant(ShiftAmt, MVT::i32));
8900 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
8901 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8902 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8903 R, DAG.getConstant(ShiftAmt, MVT::i32));
8905 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
8906 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8907 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8908 R, DAG.getConstant(ShiftAmt, MVT::i32));
8912 // Lower SHL with variable shift amount.
8913 // Cannot lower SHL without SSE4.1 or later.
8914 if (!Subtarget->hasSSE41()) return SDValue();
8916 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
8917 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8918 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8919 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8921 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8923 std::vector<Constant*> CV(4, CI);
8924 Constant *C = ConstantVector::get(CV);
8925 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8926 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8927 MachinePointerInfo::getConstantPool(),
8930 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8931 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8932 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8933 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8935 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
8937 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8938 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8939 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8941 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8942 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8944 std::vector<Constant*> CVM1(16, CM1);
8945 std::vector<Constant*> CVM2(16, CM2);
8946 Constant *C = ConstantVector::get(CVM1);
8947 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8948 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8949 MachinePointerInfo::getConstantPool(),
8952 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8953 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8954 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8955 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8956 DAG.getConstant(4, MVT::i32));
8957 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8959 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8961 C = ConstantVector::get(CVM2);
8962 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8963 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8964 MachinePointerInfo::getConstantPool(),
8967 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8968 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8969 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8970 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8971 DAG.getConstant(2, MVT::i32));
8972 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8974 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8976 // return pblendv(r, r+r, a);
8977 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8978 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8984 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8985 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8986 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8987 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8988 // has only one use.
8989 SDNode *N = Op.getNode();
8990 SDValue LHS = N->getOperand(0);
8991 SDValue RHS = N->getOperand(1);
8992 unsigned BaseOp = 0;
8994 DebugLoc DL = Op.getDebugLoc();
8995 switch (Op.getOpcode()) {
8996 default: llvm_unreachable("Unknown ovf instruction!");
8998 // A subtract of one will be selected as a INC. Note that INC doesn't
8999 // set CF, so we can't do this for UADDO.
9000 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9002 BaseOp = X86ISD::INC;
9006 BaseOp = X86ISD::ADD;
9010 BaseOp = X86ISD::ADD;
9014 // A subtract of one will be selected as a DEC. Note that DEC doesn't
9015 // set CF, so we can't do this for USUBO.
9016 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9018 BaseOp = X86ISD::DEC;
9022 BaseOp = X86ISD::SUB;
9026 BaseOp = X86ISD::SUB;
9030 BaseOp = X86ISD::SMUL;
9033 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9034 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9036 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9039 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9040 DAG.getConstant(X86::COND_O, MVT::i32),
9041 SDValue(Sum.getNode(), 2));
9043 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9048 // Also sets EFLAGS.
9049 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9050 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9053 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9054 DAG.getConstant(Cond, MVT::i32),
9055 SDValue(Sum.getNode(), 1));
9057 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9061 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9062 DebugLoc dl = Op.getDebugLoc();
9064 if (!Subtarget->hasSSE2()) {
9065 SDValue Chain = Op.getOperand(0);
9066 SDValue Zero = DAG.getConstant(0,
9067 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9069 DAG.getRegister(X86::ESP, MVT::i32), // Base
9070 DAG.getTargetConstant(1, MVT::i8), // Scale
9071 DAG.getRegister(0, MVT::i32), // Index
9072 DAG.getTargetConstant(0, MVT::i32), // Disp
9073 DAG.getRegister(0, MVT::i32), // Segment.
9078 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9079 array_lengthof(Ops));
9080 return SDValue(Res, 0);
9083 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9085 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9087 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9088 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9089 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9090 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9092 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9093 if (!Op1 && !Op2 && !Op3 && Op4)
9094 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9096 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9097 if (Op1 && !Op2 && !Op3 && !Op4)
9098 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9100 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9102 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9105 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9106 EVT T = Op.getValueType();
9107 DebugLoc DL = Op.getDebugLoc();
9110 switch(T.getSimpleVT().SimpleTy) {
9112 assert(false && "Invalid value type!");
9113 case MVT::i8: Reg = X86::AL; size = 1; break;
9114 case MVT::i16: Reg = X86::AX; size = 2; break;
9115 case MVT::i32: Reg = X86::EAX; size = 4; break;
9117 assert(Subtarget->is64Bit() && "Node not type legal!");
9118 Reg = X86::RAX; size = 8;
9121 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9122 Op.getOperand(2), SDValue());
9123 SDValue Ops[] = { cpIn.getValue(0),
9126 DAG.getTargetConstant(size, MVT::i8),
9128 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9129 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9130 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9133 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9137 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9138 SelectionDAG &DAG) const {
9139 assert(Subtarget->is64Bit() && "Result not type legalized?");
9140 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9141 SDValue TheChain = Op.getOperand(0);
9142 DebugLoc dl = Op.getDebugLoc();
9143 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9144 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9145 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9147 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9148 DAG.getConstant(32, MVT::i8));
9150 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9153 return DAG.getMergeValues(Ops, 2, dl);
9156 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9157 SelectionDAG &DAG) const {
9158 EVT SrcVT = Op.getOperand(0).getValueType();
9159 EVT DstVT = Op.getValueType();
9160 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9161 Subtarget->hasMMX() && "Unexpected custom BITCAST");
9162 assert((DstVT == MVT::i64 ||
9163 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9164 "Unexpected custom BITCAST");
9165 // i64 <=> MMX conversions are Legal.
9166 if (SrcVT==MVT::i64 && DstVT.isVector())
9168 if (DstVT==MVT::i64 && SrcVT.isVector())
9170 // MMX <=> MMX conversions are Legal.
9171 if (SrcVT.isVector() && DstVT.isVector())
9173 // All other conversions need to be expanded.
9177 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9178 SDNode *Node = Op.getNode();
9179 DebugLoc dl = Node->getDebugLoc();
9180 EVT T = Node->getValueType(0);
9181 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9182 DAG.getConstant(0, T), Node->getOperand(2));
9183 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9184 cast<AtomicSDNode>(Node)->getMemoryVT(),
9185 Node->getOperand(0),
9186 Node->getOperand(1), negOp,
9187 cast<AtomicSDNode>(Node)->getSrcValue(),
9188 cast<AtomicSDNode>(Node)->getAlignment());
9191 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9192 EVT VT = Op.getNode()->getValueType(0);
9194 // Let legalize expand this if it isn't a legal type yet.
9195 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9198 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9201 bool ExtraOp = false;
9202 switch (Op.getOpcode()) {
9203 default: assert(0 && "Invalid code");
9204 case ISD::ADDC: Opc = X86ISD::ADD; break;
9205 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9206 case ISD::SUBC: Opc = X86ISD::SUB; break;
9207 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9211 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9213 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9214 Op.getOperand(1), Op.getOperand(2));
9217 /// LowerOperation - Provide custom lowering hooks for some operations.
9219 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9220 switch (Op.getOpcode()) {
9221 default: llvm_unreachable("Should not custom lower this!");
9222 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
9223 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
9224 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
9225 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
9226 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
9227 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
9228 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9229 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9230 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
9231 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
9232 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
9233 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9234 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9235 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9236 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
9237 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
9238 case ISD::SHL_PARTS:
9239 case ISD::SRA_PARTS:
9240 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
9241 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
9242 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
9243 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
9244 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
9245 case ISD::FABS: return LowerFABS(Op, DAG);
9246 case ISD::FNEG: return LowerFNEG(Op, DAG);
9247 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
9248 case ISD::SETCC: return LowerSETCC(Op, DAG);
9249 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
9250 case ISD::SELECT: return LowerSELECT(Op, DAG);
9251 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
9252 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
9253 case ISD::VASTART: return LowerVASTART(Op, DAG);
9254 case ISD::VAARG: return LowerVAARG(Op, DAG);
9255 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
9256 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9257 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9258 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9259 case ISD::FRAME_TO_ARGS_OFFSET:
9260 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9261 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9262 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
9263 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
9264 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9265 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
9266 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
9267 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
9270 case ISD::SHL: return LowerShift(Op, DAG);
9276 case ISD::UMULO: return LowerXALUO(Op, DAG);
9277 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
9278 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
9282 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9286 void X86TargetLowering::
9287 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9288 SelectionDAG &DAG, unsigned NewOp) const {
9289 EVT T = Node->getValueType(0);
9290 DebugLoc dl = Node->getDebugLoc();
9291 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9293 SDValue Chain = Node->getOperand(0);
9294 SDValue In1 = Node->getOperand(1);
9295 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9296 Node->getOperand(2), DAG.getIntPtrConstant(0));
9297 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9298 Node->getOperand(2), DAG.getIntPtrConstant(1));
9299 SDValue Ops[] = { Chain, In1, In2L, In2H };
9300 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9302 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9303 cast<MemSDNode>(Node)->getMemOperand());
9304 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9305 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9306 Results.push_back(Result.getValue(2));
9309 /// ReplaceNodeResults - Replace a node with an illegal result type
9310 /// with a new node built out of custom code.
9311 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9312 SmallVectorImpl<SDValue>&Results,
9313 SelectionDAG &DAG) const {
9314 DebugLoc dl = N->getDebugLoc();
9315 switch (N->getOpcode()) {
9317 assert(false && "Do not know how to custom type legalize this operation!");
9323 // We don't want to expand or promote these.
9325 case ISD::FP_TO_SINT: {
9326 std::pair<SDValue,SDValue> Vals =
9327 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9328 SDValue FIST = Vals.first, StackSlot = Vals.second;
9329 if (FIST.getNode() != 0) {
9330 EVT VT = N->getValueType(0);
9331 // Return a load from the stack slot.
9332 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9333 MachinePointerInfo(), false, false, 0));
9337 case ISD::READCYCLECOUNTER: {
9338 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9339 SDValue TheChain = N->getOperand(0);
9340 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9341 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9343 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9345 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9346 SDValue Ops[] = { eax, edx };
9347 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9348 Results.push_back(edx.getValue(1));
9351 case ISD::ATOMIC_CMP_SWAP: {
9352 EVT T = N->getValueType(0);
9353 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9354 SDValue cpInL, cpInH;
9355 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9356 DAG.getConstant(0, MVT::i32));
9357 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9358 DAG.getConstant(1, MVT::i32));
9359 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9360 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9362 SDValue swapInL, swapInH;
9363 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9364 DAG.getConstant(0, MVT::i32));
9365 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9366 DAG.getConstant(1, MVT::i32));
9367 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9369 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9370 swapInL.getValue(1));
9371 SDValue Ops[] = { swapInH.getValue(0),
9373 swapInH.getValue(1) };
9374 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9375 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9376 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9378 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9379 MVT::i32, Result.getValue(1));
9380 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9381 MVT::i32, cpOutL.getValue(2));
9382 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9383 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9384 Results.push_back(cpOutH.getValue(1));
9387 case ISD::ATOMIC_LOAD_ADD:
9388 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9390 case ISD::ATOMIC_LOAD_AND:
9391 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9393 case ISD::ATOMIC_LOAD_NAND:
9394 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9396 case ISD::ATOMIC_LOAD_OR:
9397 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9399 case ISD::ATOMIC_LOAD_SUB:
9400 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9402 case ISD::ATOMIC_LOAD_XOR:
9403 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9405 case ISD::ATOMIC_SWAP:
9406 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9411 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9413 default: return NULL;
9414 case X86ISD::BSF: return "X86ISD::BSF";
9415 case X86ISD::BSR: return "X86ISD::BSR";
9416 case X86ISD::SHLD: return "X86ISD::SHLD";
9417 case X86ISD::SHRD: return "X86ISD::SHRD";
9418 case X86ISD::FAND: return "X86ISD::FAND";
9419 case X86ISD::FOR: return "X86ISD::FOR";
9420 case X86ISD::FXOR: return "X86ISD::FXOR";
9421 case X86ISD::FSRL: return "X86ISD::FSRL";
9422 case X86ISD::FILD: return "X86ISD::FILD";
9423 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
9424 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9425 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9426 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9427 case X86ISD::FLD: return "X86ISD::FLD";
9428 case X86ISD::FST: return "X86ISD::FST";
9429 case X86ISD::CALL: return "X86ISD::CALL";
9430 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
9431 case X86ISD::BT: return "X86ISD::BT";
9432 case X86ISD::CMP: return "X86ISD::CMP";
9433 case X86ISD::COMI: return "X86ISD::COMI";
9434 case X86ISD::UCOMI: return "X86ISD::UCOMI";
9435 case X86ISD::SETCC: return "X86ISD::SETCC";
9436 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
9437 case X86ISD::CMOV: return "X86ISD::CMOV";
9438 case X86ISD::BRCOND: return "X86ISD::BRCOND";
9439 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
9440 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
9441 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
9442 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
9443 case X86ISD::Wrapper: return "X86ISD::Wrapper";
9444 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
9445 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
9446 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
9447 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
9448 case X86ISD::PINSRB: return "X86ISD::PINSRB";
9449 case X86ISD::PINSRW: return "X86ISD::PINSRW";
9450 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
9451 case X86ISD::PANDN: return "X86ISD::PANDN";
9452 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
9453 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
9454 case X86ISD::PSIGND: return "X86ISD::PSIGND";
9455 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB";
9456 case X86ISD::FMAX: return "X86ISD::FMAX";
9457 case X86ISD::FMIN: return "X86ISD::FMIN";
9458 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
9459 case X86ISD::FRCP: return "X86ISD::FRCP";
9460 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
9461 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
9462 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
9463 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
9464 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
9465 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
9466 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
9467 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
9468 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
9469 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
9470 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
9471 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
9472 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
9473 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
9474 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
9475 case X86ISD::VSHL: return "X86ISD::VSHL";
9476 case X86ISD::VSRL: return "X86ISD::VSRL";
9477 case X86ISD::CMPPD: return "X86ISD::CMPPD";
9478 case X86ISD::CMPPS: return "X86ISD::CMPPS";
9479 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
9480 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
9481 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
9482 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
9483 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
9484 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
9485 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
9486 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
9487 case X86ISD::ADD: return "X86ISD::ADD";
9488 case X86ISD::SUB: return "X86ISD::SUB";
9489 case X86ISD::ADC: return "X86ISD::ADC";
9490 case X86ISD::SBB: return "X86ISD::SBB";
9491 case X86ISD::SMUL: return "X86ISD::SMUL";
9492 case X86ISD::UMUL: return "X86ISD::UMUL";
9493 case X86ISD::INC: return "X86ISD::INC";
9494 case X86ISD::DEC: return "X86ISD::DEC";
9495 case X86ISD::OR: return "X86ISD::OR";
9496 case X86ISD::XOR: return "X86ISD::XOR";
9497 case X86ISD::AND: return "X86ISD::AND";
9498 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
9499 case X86ISD::PTEST: return "X86ISD::PTEST";
9500 case X86ISD::TESTP: return "X86ISD::TESTP";
9501 case X86ISD::PALIGN: return "X86ISD::PALIGN";
9502 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
9503 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
9504 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
9505 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
9506 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
9507 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
9508 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
9509 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
9510 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
9511 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
9512 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
9513 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
9514 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
9515 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
9516 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
9517 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
9518 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
9519 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
9520 case X86ISD::MOVSD: return "X86ISD::MOVSD";
9521 case X86ISD::MOVSS: return "X86ISD::MOVSS";
9522 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
9523 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
9524 case X86ISD::VUNPCKLPS: return "X86ISD::VUNPCKLPS";
9525 case X86ISD::VUNPCKLPD: return "X86ISD::VUNPCKLPD";
9526 case X86ISD::VUNPCKLPSY: return "X86ISD::VUNPCKLPSY";
9527 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
9528 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
9529 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
9530 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
9531 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
9532 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
9533 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
9534 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
9535 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
9536 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
9537 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
9538 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9539 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
9540 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
9544 // isLegalAddressingMode - Return true if the addressing mode represented
9545 // by AM is legal for this target, for a load/store of the specified type.
9546 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9547 const Type *Ty) const {
9548 // X86 supports extremely general addressing modes.
9549 CodeModel::Model M = getTargetMachine().getCodeModel();
9550 Reloc::Model R = getTargetMachine().getRelocationModel();
9552 // X86 allows a sign-extended 32-bit immediate field as a displacement.
9553 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9558 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9560 // If a reference to this global requires an extra load, we can't fold it.
9561 if (isGlobalStubReference(GVFlags))
9564 // If BaseGV requires a register for the PIC base, we cannot also have a
9565 // BaseReg specified.
9566 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9569 // If lower 4G is not available, then we must use rip-relative addressing.
9570 if ((M != CodeModel::Small || R != Reloc::Static) &&
9571 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9581 // These scales always work.
9586 // These scales are formed with basereg+scalereg. Only accept if there is
9591 default: // Other stuff never works.
9599 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9600 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9602 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9603 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9604 if (NumBits1 <= NumBits2)
9609 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9610 if (!VT1.isInteger() || !VT2.isInteger())
9612 unsigned NumBits1 = VT1.getSizeInBits();
9613 unsigned NumBits2 = VT2.getSizeInBits();
9614 if (NumBits1 <= NumBits2)
9619 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9620 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9621 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9624 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9625 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9626 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9629 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9630 // i16 instructions are longer (0x66 prefix) and potentially slower.
9631 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9634 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9635 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9636 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9637 /// are assumed to be legal.
9639 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9641 // Very little shuffling can be done for 64-bit vectors right now.
9642 if (VT.getSizeInBits() == 64)
9643 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9645 // FIXME: pshufb, blends, shifts.
9646 return (VT.getVectorNumElements() == 2 ||
9647 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9648 isMOVLMask(M, VT) ||
9649 isSHUFPMask(M, VT) ||
9650 isPSHUFDMask(M, VT) ||
9651 isPSHUFHWMask(M, VT) ||
9652 isPSHUFLWMask(M, VT) ||
9653 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9654 isUNPCKLMask(M, VT) ||
9655 isUNPCKHMask(M, VT) ||
9656 isUNPCKL_v_undef_Mask(M, VT) ||
9657 isUNPCKH_v_undef_Mask(M, VT));
9661 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9663 unsigned NumElts = VT.getVectorNumElements();
9664 // FIXME: This collection of masks seems suspect.
9667 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9668 return (isMOVLMask(Mask, VT) ||
9669 isCommutedMOVLMask(Mask, VT, true) ||
9670 isSHUFPMask(Mask, VT) ||
9671 isCommutedSHUFPMask(Mask, VT));
9676 //===----------------------------------------------------------------------===//
9677 // X86 Scheduler Hooks
9678 //===----------------------------------------------------------------------===//
9680 // private utility function
9682 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9683 MachineBasicBlock *MBB,
9690 TargetRegisterClass *RC,
9691 bool invSrc) const {
9692 // For the atomic bitwise operator, we generate
9695 // ld t1 = [bitinstr.addr]
9696 // op t2 = t1, [bitinstr.val]
9698 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9700 // fallthrough -->nextMBB
9701 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9702 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9703 MachineFunction::iterator MBBIter = MBB;
9706 /// First build the CFG
9707 MachineFunction *F = MBB->getParent();
9708 MachineBasicBlock *thisMBB = MBB;
9709 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9710 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9711 F->insert(MBBIter, newMBB);
9712 F->insert(MBBIter, nextMBB);
9714 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9715 nextMBB->splice(nextMBB->begin(), thisMBB,
9716 llvm::next(MachineBasicBlock::iterator(bInstr)),
9718 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9720 // Update thisMBB to fall through to newMBB
9721 thisMBB->addSuccessor(newMBB);
9723 // newMBB jumps to itself and fall through to nextMBB
9724 newMBB->addSuccessor(nextMBB);
9725 newMBB->addSuccessor(newMBB);
9727 // Insert instructions into newMBB based on incoming instruction
9728 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9729 "unexpected number of operands");
9730 DebugLoc dl = bInstr->getDebugLoc();
9731 MachineOperand& destOper = bInstr->getOperand(0);
9732 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9733 int numArgs = bInstr->getNumOperands() - 1;
9734 for (int i=0; i < numArgs; ++i)
9735 argOpers[i] = &bInstr->getOperand(i+1);
9737 // x86 address has 4 operands: base, index, scale, and displacement
9738 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9739 int valArgIndx = lastAddrIndx + 1;
9741 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9742 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9743 for (int i=0; i <= lastAddrIndx; ++i)
9744 (*MIB).addOperand(*argOpers[i]);
9746 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9748 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9753 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9754 assert((argOpers[valArgIndx]->isReg() ||
9755 argOpers[valArgIndx]->isImm()) &&
9757 if (argOpers[valArgIndx]->isReg())
9758 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9760 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9762 (*MIB).addOperand(*argOpers[valArgIndx]);
9764 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9767 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9768 for (int i=0; i <= lastAddrIndx; ++i)
9769 (*MIB).addOperand(*argOpers[i]);
9771 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9772 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9773 bInstr->memoperands_end());
9775 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9779 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9781 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9785 // private utility function: 64 bit atomics on 32 bit host.
9787 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9788 MachineBasicBlock *MBB,
9793 bool invSrc) const {
9794 // For the atomic bitwise operator, we generate
9795 // thisMBB (instructions are in pairs, except cmpxchg8b)
9796 // ld t1,t2 = [bitinstr.addr]
9798 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9799 // op t5, t6 <- out1, out2, [bitinstr.val]
9800 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9801 // mov ECX, EBX <- t5, t6
9802 // mov EAX, EDX <- t1, t2
9803 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9804 // mov t3, t4 <- EAX, EDX
9806 // result in out1, out2
9807 // fallthrough -->nextMBB
9809 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9810 const unsigned LoadOpc = X86::MOV32rm;
9811 const unsigned NotOpc = X86::NOT32r;
9812 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9813 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9814 MachineFunction::iterator MBBIter = MBB;
9817 /// First build the CFG
9818 MachineFunction *F = MBB->getParent();
9819 MachineBasicBlock *thisMBB = MBB;
9820 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9821 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9822 F->insert(MBBIter, newMBB);
9823 F->insert(MBBIter, nextMBB);
9825 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9826 nextMBB->splice(nextMBB->begin(), thisMBB,
9827 llvm::next(MachineBasicBlock::iterator(bInstr)),
9829 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9831 // Update thisMBB to fall through to newMBB
9832 thisMBB->addSuccessor(newMBB);
9834 // newMBB jumps to itself and fall through to nextMBB
9835 newMBB->addSuccessor(nextMBB);
9836 newMBB->addSuccessor(newMBB);
9838 DebugLoc dl = bInstr->getDebugLoc();
9839 // Insert instructions into newMBB based on incoming instruction
9840 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9841 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9842 "unexpected number of operands");
9843 MachineOperand& dest1Oper = bInstr->getOperand(0);
9844 MachineOperand& dest2Oper = bInstr->getOperand(1);
9845 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9846 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9847 argOpers[i] = &bInstr->getOperand(i+2);
9849 // We use some of the operands multiple times, so conservatively just
9850 // clear any kill flags that might be present.
9851 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9852 argOpers[i]->setIsKill(false);
9855 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9856 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9858 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9859 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9860 for (int i=0; i <= lastAddrIndx; ++i)
9861 (*MIB).addOperand(*argOpers[i]);
9862 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9863 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9864 // add 4 to displacement.
9865 for (int i=0; i <= lastAddrIndx-2; ++i)
9866 (*MIB).addOperand(*argOpers[i]);
9867 MachineOperand newOp3 = *(argOpers[3]);
9869 newOp3.setImm(newOp3.getImm()+4);
9871 newOp3.setOffset(newOp3.getOffset()+4);
9872 (*MIB).addOperand(newOp3);
9873 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9875 // t3/4 are defined later, at the bottom of the loop
9876 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9877 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9878 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9879 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9880 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9881 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9883 // The subsequent operations should be using the destination registers of
9884 //the PHI instructions.
9886 t1 = F->getRegInfo().createVirtualRegister(RC);
9887 t2 = F->getRegInfo().createVirtualRegister(RC);
9888 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9889 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9891 t1 = dest1Oper.getReg();
9892 t2 = dest2Oper.getReg();
9895 int valArgIndx = lastAddrIndx + 1;
9896 assert((argOpers[valArgIndx]->isReg() ||
9897 argOpers[valArgIndx]->isImm()) &&
9899 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9900 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9901 if (argOpers[valArgIndx]->isReg())
9902 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9904 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9905 if (regOpcL != X86::MOV32rr)
9907 (*MIB).addOperand(*argOpers[valArgIndx]);
9908 assert(argOpers[valArgIndx + 1]->isReg() ==
9909 argOpers[valArgIndx]->isReg());
9910 assert(argOpers[valArgIndx + 1]->isImm() ==
9911 argOpers[valArgIndx]->isImm());
9912 if (argOpers[valArgIndx + 1]->isReg())
9913 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9915 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9916 if (regOpcH != X86::MOV32rr)
9918 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9920 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9922 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9925 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9927 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9930 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9931 for (int i=0; i <= lastAddrIndx; ++i)
9932 (*MIB).addOperand(*argOpers[i]);
9934 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9935 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9936 bInstr->memoperands_end());
9938 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9939 MIB.addReg(X86::EAX);
9940 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9941 MIB.addReg(X86::EDX);
9944 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9946 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9950 // private utility function
9952 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9953 MachineBasicBlock *MBB,
9954 unsigned cmovOpc) const {
9955 // For the atomic min/max operator, we generate
9958 // ld t1 = [min/max.addr]
9959 // mov t2 = [min/max.val]
9961 // cmov[cond] t2 = t1
9963 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9965 // fallthrough -->nextMBB
9967 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9968 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9969 MachineFunction::iterator MBBIter = MBB;
9972 /// First build the CFG
9973 MachineFunction *F = MBB->getParent();
9974 MachineBasicBlock *thisMBB = MBB;
9975 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9976 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9977 F->insert(MBBIter, newMBB);
9978 F->insert(MBBIter, nextMBB);
9980 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9981 nextMBB->splice(nextMBB->begin(), thisMBB,
9982 llvm::next(MachineBasicBlock::iterator(mInstr)),
9984 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9986 // Update thisMBB to fall through to newMBB
9987 thisMBB->addSuccessor(newMBB);
9989 // newMBB jumps to newMBB and fall through to nextMBB
9990 newMBB->addSuccessor(nextMBB);
9991 newMBB->addSuccessor(newMBB);
9993 DebugLoc dl = mInstr->getDebugLoc();
9994 // Insert instructions into newMBB based on incoming instruction
9995 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9996 "unexpected number of operands");
9997 MachineOperand& destOper = mInstr->getOperand(0);
9998 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9999 int numArgs = mInstr->getNumOperands() - 1;
10000 for (int i=0; i < numArgs; ++i)
10001 argOpers[i] = &mInstr->getOperand(i+1);
10003 // x86 address has 4 operands: base, index, scale, and displacement
10004 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10005 int valArgIndx = lastAddrIndx + 1;
10007 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10008 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10009 for (int i=0; i <= lastAddrIndx; ++i)
10010 (*MIB).addOperand(*argOpers[i]);
10012 // We only support register and immediate values
10013 assert((argOpers[valArgIndx]->isReg() ||
10014 argOpers[valArgIndx]->isImm()) &&
10015 "invalid operand");
10017 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10018 if (argOpers[valArgIndx]->isReg())
10019 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10021 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10022 (*MIB).addOperand(*argOpers[valArgIndx]);
10024 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10027 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10032 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10033 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10037 // Cmp and exchange if none has modified the memory location
10038 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10039 for (int i=0; i <= lastAddrIndx; ++i)
10040 (*MIB).addOperand(*argOpers[i]);
10042 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10043 (*MIB).setMemRefs(mInstr->memoperands_begin(),
10044 mInstr->memoperands_end());
10046 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10047 MIB.addReg(X86::EAX);
10050 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10052 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
10056 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10057 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10058 // in the .td file.
10059 MachineBasicBlock *
10060 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10061 unsigned numArgs, bool memArg) const {
10062 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10063 "Target must have SSE4.2 or AVX features enabled");
10065 DebugLoc dl = MI->getDebugLoc();
10066 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10068 if (!Subtarget->hasAVX()) {
10070 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10072 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10075 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10077 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10080 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10081 for (unsigned i = 0; i < numArgs; ++i) {
10082 MachineOperand &Op = MI->getOperand(i+1);
10083 if (!(Op.isReg() && Op.isImplicit()))
10084 MIB.addOperand(Op);
10086 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10087 .addReg(X86::XMM0);
10089 MI->eraseFromParent();
10093 MachineBasicBlock *
10094 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10095 DebugLoc dl = MI->getDebugLoc();
10096 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10098 // Address into RAX/EAX, other two args into ECX, EDX.
10099 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10100 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10101 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10102 for (int i = 0; i < X86::AddrNumOperands; ++i)
10103 MIB.addOperand(MI->getOperand(i));
10105 unsigned ValOps = X86::AddrNumOperands;
10106 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10107 .addReg(MI->getOperand(ValOps).getReg());
10108 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10109 .addReg(MI->getOperand(ValOps+1).getReg());
10111 // The instruction doesn't actually take any operands though.
10112 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10114 MI->eraseFromParent(); // The pseudo is gone now.
10118 MachineBasicBlock *
10119 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10120 DebugLoc dl = MI->getDebugLoc();
10121 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10123 // First arg in ECX, the second in EAX.
10124 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10125 .addReg(MI->getOperand(0).getReg());
10126 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10127 .addReg(MI->getOperand(1).getReg());
10129 // The instruction doesn't actually take any operands though.
10130 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10132 MI->eraseFromParent(); // The pseudo is gone now.
10136 MachineBasicBlock *
10137 X86TargetLowering::EmitVAARG64WithCustomInserter(
10139 MachineBasicBlock *MBB) const {
10140 // Emit va_arg instruction on X86-64.
10142 // Operands to this pseudo-instruction:
10143 // 0 ) Output : destination address (reg)
10144 // 1-5) Input : va_list address (addr, i64mem)
10145 // 6 ) ArgSize : Size (in bytes) of vararg type
10146 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10147 // 8 ) Align : Alignment of type
10148 // 9 ) EFLAGS (implicit-def)
10150 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10151 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10153 unsigned DestReg = MI->getOperand(0).getReg();
10154 MachineOperand &Base = MI->getOperand(1);
10155 MachineOperand &Scale = MI->getOperand(2);
10156 MachineOperand &Index = MI->getOperand(3);
10157 MachineOperand &Disp = MI->getOperand(4);
10158 MachineOperand &Segment = MI->getOperand(5);
10159 unsigned ArgSize = MI->getOperand(6).getImm();
10160 unsigned ArgMode = MI->getOperand(7).getImm();
10161 unsigned Align = MI->getOperand(8).getImm();
10163 // Memory Reference
10164 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10165 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10166 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10168 // Machine Information
10169 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10170 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10171 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10172 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10173 DebugLoc DL = MI->getDebugLoc();
10175 // struct va_list {
10178 // i64 overflow_area (address)
10179 // i64 reg_save_area (address)
10181 // sizeof(va_list) = 24
10182 // alignment(va_list) = 8
10184 unsigned TotalNumIntRegs = 6;
10185 unsigned TotalNumXMMRegs = 8;
10186 bool UseGPOffset = (ArgMode == 1);
10187 bool UseFPOffset = (ArgMode == 2);
10188 unsigned MaxOffset = TotalNumIntRegs * 8 +
10189 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10191 /* Align ArgSize to a multiple of 8 */
10192 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10193 bool NeedsAlign = (Align > 8);
10195 MachineBasicBlock *thisMBB = MBB;
10196 MachineBasicBlock *overflowMBB;
10197 MachineBasicBlock *offsetMBB;
10198 MachineBasicBlock *endMBB;
10200 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
10201 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
10202 unsigned OffsetReg = 0;
10204 if (!UseGPOffset && !UseFPOffset) {
10205 // If we only pull from the overflow region, we don't create a branch.
10206 // We don't need to alter control flow.
10207 OffsetDestReg = 0; // unused
10208 OverflowDestReg = DestReg;
10211 overflowMBB = thisMBB;
10214 // First emit code to check if gp_offset (or fp_offset) is below the bound.
10215 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10216 // If not, pull from overflow_area. (branch to overflowMBB)
10221 // offsetMBB overflowMBB
10226 // Registers for the PHI in endMBB
10227 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10228 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10230 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10231 MachineFunction *MF = MBB->getParent();
10232 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10233 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10234 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10236 MachineFunction::iterator MBBIter = MBB;
10239 // Insert the new basic blocks
10240 MF->insert(MBBIter, offsetMBB);
10241 MF->insert(MBBIter, overflowMBB);
10242 MF->insert(MBBIter, endMBB);
10244 // Transfer the remainder of MBB and its successor edges to endMBB.
10245 endMBB->splice(endMBB->begin(), thisMBB,
10246 llvm::next(MachineBasicBlock::iterator(MI)),
10248 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10250 // Make offsetMBB and overflowMBB successors of thisMBB
10251 thisMBB->addSuccessor(offsetMBB);
10252 thisMBB->addSuccessor(overflowMBB);
10254 // endMBB is a successor of both offsetMBB and overflowMBB
10255 offsetMBB->addSuccessor(endMBB);
10256 overflowMBB->addSuccessor(endMBB);
10258 // Load the offset value into a register
10259 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10260 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10264 .addDisp(Disp, UseFPOffset ? 4 : 0)
10265 .addOperand(Segment)
10266 .setMemRefs(MMOBegin, MMOEnd);
10268 // Check if there is enough room left to pull this argument.
10269 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10271 .addImm(MaxOffset + 8 - ArgSizeA8);
10273 // Branch to "overflowMBB" if offset >= max
10274 // Fall through to "offsetMBB" otherwise
10275 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10276 .addMBB(overflowMBB);
10279 // In offsetMBB, emit code to use the reg_save_area.
10281 assert(OffsetReg != 0);
10283 // Read the reg_save_area address.
10284 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10285 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10290 .addOperand(Segment)
10291 .setMemRefs(MMOBegin, MMOEnd);
10293 // Zero-extend the offset
10294 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10295 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10298 .addImm(X86::sub_32bit);
10300 // Add the offset to the reg_save_area to get the final address.
10301 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10302 .addReg(OffsetReg64)
10303 .addReg(RegSaveReg);
10305 // Compute the offset for the next argument
10306 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10307 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10309 .addImm(UseFPOffset ? 16 : 8);
10311 // Store it back into the va_list.
10312 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10316 .addDisp(Disp, UseFPOffset ? 4 : 0)
10317 .addOperand(Segment)
10318 .addReg(NextOffsetReg)
10319 .setMemRefs(MMOBegin, MMOEnd);
10322 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10327 // Emit code to use overflow area
10330 // Load the overflow_area address into a register.
10331 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10332 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10337 .addOperand(Segment)
10338 .setMemRefs(MMOBegin, MMOEnd);
10340 // If we need to align it, do so. Otherwise, just copy the address
10341 // to OverflowDestReg.
10343 // Align the overflow address
10344 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10345 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10347 // aligned_addr = (addr + (align-1)) & ~(align-1)
10348 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10349 .addReg(OverflowAddrReg)
10352 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10354 .addImm(~(uint64_t)(Align-1));
10356 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10357 .addReg(OverflowAddrReg);
10360 // Compute the next overflow address after this argument.
10361 // (the overflow address should be kept 8-byte aligned)
10362 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10363 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10364 .addReg(OverflowDestReg)
10365 .addImm(ArgSizeA8);
10367 // Store the new overflow address.
10368 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10373 .addOperand(Segment)
10374 .addReg(NextAddrReg)
10375 .setMemRefs(MMOBegin, MMOEnd);
10377 // If we branched, emit the PHI to the front of endMBB.
10379 BuildMI(*endMBB, endMBB->begin(), DL,
10380 TII->get(X86::PHI), DestReg)
10381 .addReg(OffsetDestReg).addMBB(offsetMBB)
10382 .addReg(OverflowDestReg).addMBB(overflowMBB);
10385 // Erase the pseudo instruction
10386 MI->eraseFromParent();
10391 MachineBasicBlock *
10392 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10394 MachineBasicBlock *MBB) const {
10395 // Emit code to save XMM registers to the stack. The ABI says that the
10396 // number of registers to save is given in %al, so it's theoretically
10397 // possible to do an indirect jump trick to avoid saving all of them,
10398 // however this code takes a simpler approach and just executes all
10399 // of the stores if %al is non-zero. It's less code, and it's probably
10400 // easier on the hardware branch predictor, and stores aren't all that
10401 // expensive anyway.
10403 // Create the new basic blocks. One block contains all the XMM stores,
10404 // and one block is the final destination regardless of whether any
10405 // stores were performed.
10406 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10407 MachineFunction *F = MBB->getParent();
10408 MachineFunction::iterator MBBIter = MBB;
10410 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10411 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10412 F->insert(MBBIter, XMMSaveMBB);
10413 F->insert(MBBIter, EndMBB);
10415 // Transfer the remainder of MBB and its successor edges to EndMBB.
10416 EndMBB->splice(EndMBB->begin(), MBB,
10417 llvm::next(MachineBasicBlock::iterator(MI)),
10419 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10421 // The original block will now fall through to the XMM save block.
10422 MBB->addSuccessor(XMMSaveMBB);
10423 // The XMMSaveMBB will fall through to the end block.
10424 XMMSaveMBB->addSuccessor(EndMBB);
10426 // Now add the instructions.
10427 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10428 DebugLoc DL = MI->getDebugLoc();
10430 unsigned CountReg = MI->getOperand(0).getReg();
10431 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10432 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10434 if (!Subtarget->isTargetWin64()) {
10435 // If %al is 0, branch around the XMM save block.
10436 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10437 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10438 MBB->addSuccessor(EndMBB);
10441 // In the XMM save block, save all the XMM argument registers.
10442 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10443 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10444 MachineMemOperand *MMO =
10445 F->getMachineMemOperand(
10446 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10447 MachineMemOperand::MOStore,
10448 /*Size=*/16, /*Align=*/16);
10449 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10450 .addFrameIndex(RegSaveFrameIndex)
10451 .addImm(/*Scale=*/1)
10452 .addReg(/*IndexReg=*/0)
10453 .addImm(/*Disp=*/Offset)
10454 .addReg(/*Segment=*/0)
10455 .addReg(MI->getOperand(i).getReg())
10456 .addMemOperand(MMO);
10459 MI->eraseFromParent(); // The pseudo instruction is gone now.
10464 MachineBasicBlock *
10465 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10466 MachineBasicBlock *BB) const {
10467 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10468 DebugLoc DL = MI->getDebugLoc();
10470 // To "insert" a SELECT_CC instruction, we actually have to insert the
10471 // diamond control-flow pattern. The incoming instruction knows the
10472 // destination vreg to set, the condition code register to branch on, the
10473 // true/false values to select between, and a branch opcode to use.
10474 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10475 MachineFunction::iterator It = BB;
10481 // cmpTY ccX, r1, r2
10483 // fallthrough --> copy0MBB
10484 MachineBasicBlock *thisMBB = BB;
10485 MachineFunction *F = BB->getParent();
10486 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10487 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10488 F->insert(It, copy0MBB);
10489 F->insert(It, sinkMBB);
10491 // If the EFLAGS register isn't dead in the terminator, then claim that it's
10492 // live into the sink and copy blocks.
10493 const MachineFunction *MF = BB->getParent();
10494 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10495 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10497 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10498 const MachineOperand &MO = MI->getOperand(I);
10499 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10500 unsigned Reg = MO.getReg();
10501 if (Reg != X86::EFLAGS) continue;
10502 copy0MBB->addLiveIn(Reg);
10503 sinkMBB->addLiveIn(Reg);
10506 // Transfer the remainder of BB and its successor edges to sinkMBB.
10507 sinkMBB->splice(sinkMBB->begin(), BB,
10508 llvm::next(MachineBasicBlock::iterator(MI)),
10510 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10512 // Add the true and fallthrough blocks as its successors.
10513 BB->addSuccessor(copy0MBB);
10514 BB->addSuccessor(sinkMBB);
10516 // Create the conditional branch instruction.
10518 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10519 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10522 // %FalseValue = ...
10523 // # fallthrough to sinkMBB
10524 copy0MBB->addSuccessor(sinkMBB);
10527 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10529 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10530 TII->get(X86::PHI), MI->getOperand(0).getReg())
10531 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10532 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10534 MI->eraseFromParent(); // The pseudo instruction is gone now.
10538 MachineBasicBlock *
10539 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10540 MachineBasicBlock *BB) const {
10541 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10542 DebugLoc DL = MI->getDebugLoc();
10544 assert(!Subtarget->isTargetEnvMacho());
10546 // The lowering is pretty easy: we're just emitting the call to _alloca. The
10547 // non-trivial part is impdef of ESP.
10549 if (Subtarget->isTargetWin64()) {
10550 if (Subtarget->isTargetCygMing()) {
10551 // ___chkstk(Mingw64):
10552 // Clobbers R10, R11, RAX and EFLAGS.
10554 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10555 .addExternalSymbol("___chkstk")
10556 .addReg(X86::RAX, RegState::Implicit)
10557 .addReg(X86::RSP, RegState::Implicit)
10558 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10559 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10560 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10562 // __chkstk(MSVCRT): does not update stack pointer.
10563 // Clobbers R10, R11 and EFLAGS.
10564 // FIXME: RAX(allocated size) might be reused and not killed.
10565 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10566 .addExternalSymbol("__chkstk")
10567 .addReg(X86::RAX, RegState::Implicit)
10568 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10569 // RAX has the offset to subtracted from RSP.
10570 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10575 const char *StackProbeSymbol =
10576 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10578 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10579 .addExternalSymbol(StackProbeSymbol)
10580 .addReg(X86::EAX, RegState::Implicit)
10581 .addReg(X86::ESP, RegState::Implicit)
10582 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10583 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10584 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10587 MI->eraseFromParent(); // The pseudo instruction is gone now.
10591 MachineBasicBlock *
10592 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10593 MachineBasicBlock *BB) const {
10594 // This is pretty easy. We're taking the value that we received from
10595 // our load from the relocation, sticking it in either RDI (x86-64)
10596 // or EAX and doing an indirect call. The return value will then
10597 // be in the normal return register.
10598 const X86InstrInfo *TII
10599 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10600 DebugLoc DL = MI->getDebugLoc();
10601 MachineFunction *F = BB->getParent();
10603 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10604 assert(MI->getOperand(3).isGlobal() && "This should be a global");
10606 if (Subtarget->is64Bit()) {
10607 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10608 TII->get(X86::MOV64rm), X86::RDI)
10610 .addImm(0).addReg(0)
10611 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10612 MI->getOperand(3).getTargetFlags())
10614 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10615 addDirectMem(MIB, X86::RDI);
10616 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10617 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10618 TII->get(X86::MOV32rm), X86::EAX)
10620 .addImm(0).addReg(0)
10621 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10622 MI->getOperand(3).getTargetFlags())
10624 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10625 addDirectMem(MIB, X86::EAX);
10627 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10628 TII->get(X86::MOV32rm), X86::EAX)
10629 .addReg(TII->getGlobalBaseReg(F))
10630 .addImm(0).addReg(0)
10631 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10632 MI->getOperand(3).getTargetFlags())
10634 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10635 addDirectMem(MIB, X86::EAX);
10638 MI->eraseFromParent(); // The pseudo instruction is gone now.
10642 MachineBasicBlock *
10643 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10644 MachineBasicBlock *BB) const {
10645 switch (MI->getOpcode()) {
10646 default: assert(false && "Unexpected instr type to insert");
10647 case X86::TAILJMPd64:
10648 case X86::TAILJMPr64:
10649 case X86::TAILJMPm64:
10650 assert(!"TAILJMP64 would not be touched here.");
10651 case X86::TCRETURNdi64:
10652 case X86::TCRETURNri64:
10653 case X86::TCRETURNmi64:
10654 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10655 // On AMD64, additional defs should be added before register allocation.
10656 if (!Subtarget->isTargetWin64()) {
10657 MI->addRegisterDefined(X86::RSI);
10658 MI->addRegisterDefined(X86::RDI);
10659 MI->addRegisterDefined(X86::XMM6);
10660 MI->addRegisterDefined(X86::XMM7);
10661 MI->addRegisterDefined(X86::XMM8);
10662 MI->addRegisterDefined(X86::XMM9);
10663 MI->addRegisterDefined(X86::XMM10);
10664 MI->addRegisterDefined(X86::XMM11);
10665 MI->addRegisterDefined(X86::XMM12);
10666 MI->addRegisterDefined(X86::XMM13);
10667 MI->addRegisterDefined(X86::XMM14);
10668 MI->addRegisterDefined(X86::XMM15);
10671 case X86::WIN_ALLOCA:
10672 return EmitLoweredWinAlloca(MI, BB);
10673 case X86::TLSCall_32:
10674 case X86::TLSCall_64:
10675 return EmitLoweredTLSCall(MI, BB);
10676 case X86::CMOV_GR8:
10677 case X86::CMOV_FR32:
10678 case X86::CMOV_FR64:
10679 case X86::CMOV_V4F32:
10680 case X86::CMOV_V2F64:
10681 case X86::CMOV_V2I64:
10682 case X86::CMOV_GR16:
10683 case X86::CMOV_GR32:
10684 case X86::CMOV_RFP32:
10685 case X86::CMOV_RFP64:
10686 case X86::CMOV_RFP80:
10687 return EmitLoweredSelect(MI, BB);
10689 case X86::FP32_TO_INT16_IN_MEM:
10690 case X86::FP32_TO_INT32_IN_MEM:
10691 case X86::FP32_TO_INT64_IN_MEM:
10692 case X86::FP64_TO_INT16_IN_MEM:
10693 case X86::FP64_TO_INT32_IN_MEM:
10694 case X86::FP64_TO_INT64_IN_MEM:
10695 case X86::FP80_TO_INT16_IN_MEM:
10696 case X86::FP80_TO_INT32_IN_MEM:
10697 case X86::FP80_TO_INT64_IN_MEM: {
10698 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10699 DebugLoc DL = MI->getDebugLoc();
10701 // Change the floating point control register to use "round towards zero"
10702 // mode when truncating to an integer value.
10703 MachineFunction *F = BB->getParent();
10704 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10705 addFrameReference(BuildMI(*BB, MI, DL,
10706 TII->get(X86::FNSTCW16m)), CWFrameIdx);
10708 // Load the old value of the high byte of the control word...
10710 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10711 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10714 // Set the high part to be round to zero...
10715 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10718 // Reload the modified control word now...
10719 addFrameReference(BuildMI(*BB, MI, DL,
10720 TII->get(X86::FLDCW16m)), CWFrameIdx);
10722 // Restore the memory image of control word to original value
10723 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10726 // Get the X86 opcode to use.
10728 switch (MI->getOpcode()) {
10729 default: llvm_unreachable("illegal opcode!");
10730 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10731 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10732 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10733 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10734 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10735 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10736 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10737 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10738 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10742 MachineOperand &Op = MI->getOperand(0);
10744 AM.BaseType = X86AddressMode::RegBase;
10745 AM.Base.Reg = Op.getReg();
10747 AM.BaseType = X86AddressMode::FrameIndexBase;
10748 AM.Base.FrameIndex = Op.getIndex();
10750 Op = MI->getOperand(1);
10752 AM.Scale = Op.getImm();
10753 Op = MI->getOperand(2);
10755 AM.IndexReg = Op.getImm();
10756 Op = MI->getOperand(3);
10757 if (Op.isGlobal()) {
10758 AM.GV = Op.getGlobal();
10760 AM.Disp = Op.getImm();
10762 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10763 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10765 // Reload the original control word now.
10766 addFrameReference(BuildMI(*BB, MI, DL,
10767 TII->get(X86::FLDCW16m)), CWFrameIdx);
10769 MI->eraseFromParent(); // The pseudo instruction is gone now.
10772 // String/text processing lowering.
10773 case X86::PCMPISTRM128REG:
10774 case X86::VPCMPISTRM128REG:
10775 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10776 case X86::PCMPISTRM128MEM:
10777 case X86::VPCMPISTRM128MEM:
10778 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10779 case X86::PCMPESTRM128REG:
10780 case X86::VPCMPESTRM128REG:
10781 return EmitPCMP(MI, BB, 5, false /* in mem */);
10782 case X86::PCMPESTRM128MEM:
10783 case X86::VPCMPESTRM128MEM:
10784 return EmitPCMP(MI, BB, 5, true /* in mem */);
10786 // Thread synchronization.
10788 return EmitMonitor(MI, BB);
10790 return EmitMwait(MI, BB);
10792 // Atomic Lowering.
10793 case X86::ATOMAND32:
10794 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10795 X86::AND32ri, X86::MOV32rm,
10797 X86::NOT32r, X86::EAX,
10798 X86::GR32RegisterClass);
10799 case X86::ATOMOR32:
10800 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10801 X86::OR32ri, X86::MOV32rm,
10803 X86::NOT32r, X86::EAX,
10804 X86::GR32RegisterClass);
10805 case X86::ATOMXOR32:
10806 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10807 X86::XOR32ri, X86::MOV32rm,
10809 X86::NOT32r, X86::EAX,
10810 X86::GR32RegisterClass);
10811 case X86::ATOMNAND32:
10812 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10813 X86::AND32ri, X86::MOV32rm,
10815 X86::NOT32r, X86::EAX,
10816 X86::GR32RegisterClass, true);
10817 case X86::ATOMMIN32:
10818 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10819 case X86::ATOMMAX32:
10820 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10821 case X86::ATOMUMIN32:
10822 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10823 case X86::ATOMUMAX32:
10824 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10826 case X86::ATOMAND16:
10827 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10828 X86::AND16ri, X86::MOV16rm,
10830 X86::NOT16r, X86::AX,
10831 X86::GR16RegisterClass);
10832 case X86::ATOMOR16:
10833 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10834 X86::OR16ri, X86::MOV16rm,
10836 X86::NOT16r, X86::AX,
10837 X86::GR16RegisterClass);
10838 case X86::ATOMXOR16:
10839 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10840 X86::XOR16ri, X86::MOV16rm,
10842 X86::NOT16r, X86::AX,
10843 X86::GR16RegisterClass);
10844 case X86::ATOMNAND16:
10845 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10846 X86::AND16ri, X86::MOV16rm,
10848 X86::NOT16r, X86::AX,
10849 X86::GR16RegisterClass, true);
10850 case X86::ATOMMIN16:
10851 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10852 case X86::ATOMMAX16:
10853 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10854 case X86::ATOMUMIN16:
10855 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10856 case X86::ATOMUMAX16:
10857 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10859 case X86::ATOMAND8:
10860 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10861 X86::AND8ri, X86::MOV8rm,
10863 X86::NOT8r, X86::AL,
10864 X86::GR8RegisterClass);
10866 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10867 X86::OR8ri, X86::MOV8rm,
10869 X86::NOT8r, X86::AL,
10870 X86::GR8RegisterClass);
10871 case X86::ATOMXOR8:
10872 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10873 X86::XOR8ri, X86::MOV8rm,
10875 X86::NOT8r, X86::AL,
10876 X86::GR8RegisterClass);
10877 case X86::ATOMNAND8:
10878 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10879 X86::AND8ri, X86::MOV8rm,
10881 X86::NOT8r, X86::AL,
10882 X86::GR8RegisterClass, true);
10883 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10884 // This group is for 64-bit host.
10885 case X86::ATOMAND64:
10886 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10887 X86::AND64ri32, X86::MOV64rm,
10889 X86::NOT64r, X86::RAX,
10890 X86::GR64RegisterClass);
10891 case X86::ATOMOR64:
10892 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10893 X86::OR64ri32, X86::MOV64rm,
10895 X86::NOT64r, X86::RAX,
10896 X86::GR64RegisterClass);
10897 case X86::ATOMXOR64:
10898 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10899 X86::XOR64ri32, X86::MOV64rm,
10901 X86::NOT64r, X86::RAX,
10902 X86::GR64RegisterClass);
10903 case X86::ATOMNAND64:
10904 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10905 X86::AND64ri32, X86::MOV64rm,
10907 X86::NOT64r, X86::RAX,
10908 X86::GR64RegisterClass, true);
10909 case X86::ATOMMIN64:
10910 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10911 case X86::ATOMMAX64:
10912 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10913 case X86::ATOMUMIN64:
10914 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10915 case X86::ATOMUMAX64:
10916 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10918 // This group does 64-bit operations on a 32-bit host.
10919 case X86::ATOMAND6432:
10920 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10921 X86::AND32rr, X86::AND32rr,
10922 X86::AND32ri, X86::AND32ri,
10924 case X86::ATOMOR6432:
10925 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10926 X86::OR32rr, X86::OR32rr,
10927 X86::OR32ri, X86::OR32ri,
10929 case X86::ATOMXOR6432:
10930 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10931 X86::XOR32rr, X86::XOR32rr,
10932 X86::XOR32ri, X86::XOR32ri,
10934 case X86::ATOMNAND6432:
10935 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10936 X86::AND32rr, X86::AND32rr,
10937 X86::AND32ri, X86::AND32ri,
10939 case X86::ATOMADD6432:
10940 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10941 X86::ADD32rr, X86::ADC32rr,
10942 X86::ADD32ri, X86::ADC32ri,
10944 case X86::ATOMSUB6432:
10945 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10946 X86::SUB32rr, X86::SBB32rr,
10947 X86::SUB32ri, X86::SBB32ri,
10949 case X86::ATOMSWAP6432:
10950 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10951 X86::MOV32rr, X86::MOV32rr,
10952 X86::MOV32ri, X86::MOV32ri,
10954 case X86::VASTART_SAVE_XMM_REGS:
10955 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10957 case X86::VAARG_64:
10958 return EmitVAARG64WithCustomInserter(MI, BB);
10962 //===----------------------------------------------------------------------===//
10963 // X86 Optimization Hooks
10964 //===----------------------------------------------------------------------===//
10966 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10970 const SelectionDAG &DAG,
10971 unsigned Depth) const {
10972 unsigned Opc = Op.getOpcode();
10973 assert((Opc >= ISD::BUILTIN_OP_END ||
10974 Opc == ISD::INTRINSIC_WO_CHAIN ||
10975 Opc == ISD::INTRINSIC_W_CHAIN ||
10976 Opc == ISD::INTRINSIC_VOID) &&
10977 "Should use MaskedValueIsZero if you don't know whether Op"
10978 " is a target node!");
10980 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
10994 // These nodes' second result is a boolean.
10995 if (Op.getResNo() == 0)
10998 case X86ISD::SETCC:
10999 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11000 Mask.getBitWidth() - 1);
11005 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11006 unsigned Depth) const {
11007 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11008 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11009 return Op.getValueType().getScalarType().getSizeInBits();
11015 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11016 /// node is a GlobalAddress + offset.
11017 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11018 const GlobalValue* &GA,
11019 int64_t &Offset) const {
11020 if (N->getOpcode() == X86ISD::Wrapper) {
11021 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11022 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11023 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11027 return TargetLowering::isGAPlusOffset(N, GA, Offset);
11030 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
11031 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
11032 /// if the load addresses are consecutive, non-overlapping, and in the right
11034 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11035 TargetLowering::DAGCombinerInfo &DCI) {
11036 DebugLoc dl = N->getDebugLoc();
11037 EVT VT = N->getValueType(0);
11039 if (VT.getSizeInBits() != 128)
11042 // Don't create instructions with illegal types after legalize types has run.
11043 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11044 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11047 SmallVector<SDValue, 16> Elts;
11048 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11049 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11051 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11054 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11055 /// generation and convert it from being a bunch of shuffles and extracts
11056 /// to a simple store and scalar loads to extract the elements.
11057 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11058 const TargetLowering &TLI) {
11059 SDValue InputVector = N->getOperand(0);
11061 // Only operate on vectors of 4 elements, where the alternative shuffling
11062 // gets to be more expensive.
11063 if (InputVector.getValueType() != MVT::v4i32)
11066 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11067 // single use which is a sign-extend or zero-extend, and all elements are
11069 SmallVector<SDNode *, 4> Uses;
11070 unsigned ExtractedElements = 0;
11071 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11072 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11073 if (UI.getUse().getResNo() != InputVector.getResNo())
11076 SDNode *Extract = *UI;
11077 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11080 if (Extract->getValueType(0) != MVT::i32)
11082 if (!Extract->hasOneUse())
11084 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11085 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11087 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11090 // Record which element was extracted.
11091 ExtractedElements |=
11092 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11094 Uses.push_back(Extract);
11097 // If not all the elements were used, this may not be worthwhile.
11098 if (ExtractedElements != 15)
11101 // Ok, we've now decided to do the transformation.
11102 DebugLoc dl = InputVector.getDebugLoc();
11104 // Store the value to a temporary stack slot.
11105 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11106 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11107 MachinePointerInfo(), false, false, 0);
11109 // Replace each use (extract) with a load of the appropriate element.
11110 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11111 UE = Uses.end(); UI != UE; ++UI) {
11112 SDNode *Extract = *UI;
11114 // cOMpute the element's address.
11115 SDValue Idx = Extract->getOperand(1);
11117 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11118 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11119 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11121 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11122 StackPtr, OffsetVal);
11124 // Load the scalar.
11125 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11126 ScalarAddr, MachinePointerInfo(),
11129 // Replace the exact with the load.
11130 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11133 // The replacement was made in place; don't return anything.
11137 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11138 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11139 const X86Subtarget *Subtarget) {
11140 DebugLoc DL = N->getDebugLoc();
11141 SDValue Cond = N->getOperand(0);
11142 // Get the LHS/RHS of the select.
11143 SDValue LHS = N->getOperand(1);
11144 SDValue RHS = N->getOperand(2);
11146 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11147 // instructions match the semantics of the common C idiom x<y?x:y but not
11148 // x<=y?x:y, because of how they handle negative zero (which can be
11149 // ignored in unsafe-math mode).
11150 if (Subtarget->hasSSE2() &&
11151 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11152 Cond.getOpcode() == ISD::SETCC) {
11153 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11155 unsigned Opcode = 0;
11156 // Check for x CC y ? x : y.
11157 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11158 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11162 // Converting this to a min would handle NaNs incorrectly, and swapping
11163 // the operands would cause it to handle comparisons between positive
11164 // and negative zero incorrectly.
11165 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11166 if (!UnsafeFPMath &&
11167 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11169 std::swap(LHS, RHS);
11171 Opcode = X86ISD::FMIN;
11174 // Converting this to a min would handle comparisons between positive
11175 // and negative zero incorrectly.
11176 if (!UnsafeFPMath &&
11177 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11179 Opcode = X86ISD::FMIN;
11182 // Converting this to a min would handle both negative zeros and NaNs
11183 // incorrectly, but we can swap the operands to fix both.
11184 std::swap(LHS, RHS);
11188 Opcode = X86ISD::FMIN;
11192 // Converting this to a max would handle comparisons between positive
11193 // and negative zero incorrectly.
11194 if (!UnsafeFPMath &&
11195 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11197 Opcode = X86ISD::FMAX;
11200 // Converting this to a max would handle NaNs incorrectly, and swapping
11201 // the operands would cause it to handle comparisons between positive
11202 // and negative zero incorrectly.
11203 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11204 if (!UnsafeFPMath &&
11205 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11207 std::swap(LHS, RHS);
11209 Opcode = X86ISD::FMAX;
11212 // Converting this to a max would handle both negative zeros and NaNs
11213 // incorrectly, but we can swap the operands to fix both.
11214 std::swap(LHS, RHS);
11218 Opcode = X86ISD::FMAX;
11221 // Check for x CC y ? y : x -- a min/max with reversed arms.
11222 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11223 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11227 // Converting this to a min would handle comparisons between positive
11228 // and negative zero incorrectly, and swapping the operands would
11229 // cause it to handle NaNs incorrectly.
11230 if (!UnsafeFPMath &&
11231 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11232 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11234 std::swap(LHS, RHS);
11236 Opcode = X86ISD::FMIN;
11239 // Converting this to a min would handle NaNs incorrectly.
11240 if (!UnsafeFPMath &&
11241 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11243 Opcode = X86ISD::FMIN;
11246 // Converting this to a min would handle both negative zeros and NaNs
11247 // incorrectly, but we can swap the operands to fix both.
11248 std::swap(LHS, RHS);
11252 Opcode = X86ISD::FMIN;
11256 // Converting this to a max would handle NaNs incorrectly.
11257 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11259 Opcode = X86ISD::FMAX;
11262 // Converting this to a max would handle comparisons between positive
11263 // and negative zero incorrectly, and swapping the operands would
11264 // cause it to handle NaNs incorrectly.
11265 if (!UnsafeFPMath &&
11266 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11267 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11269 std::swap(LHS, RHS);
11271 Opcode = X86ISD::FMAX;
11274 // Converting this to a max would handle both negative zeros and NaNs
11275 // incorrectly, but we can swap the operands to fix both.
11276 std::swap(LHS, RHS);
11280 Opcode = X86ISD::FMAX;
11286 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11289 // If this is a select between two integer constants, try to do some
11291 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11292 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11293 // Don't do this for crazy integer types.
11294 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11295 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11296 // so that TrueC (the true value) is larger than FalseC.
11297 bool NeedsCondInvert = false;
11299 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11300 // Efficiently invertible.
11301 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
11302 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
11303 isa<ConstantSDNode>(Cond.getOperand(1))))) {
11304 NeedsCondInvert = true;
11305 std::swap(TrueC, FalseC);
11308 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
11309 if (FalseC->getAPIntValue() == 0 &&
11310 TrueC->getAPIntValue().isPowerOf2()) {
11311 if (NeedsCondInvert) // Invert the condition if needed.
11312 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11313 DAG.getConstant(1, Cond.getValueType()));
11315 // Zero extend the condition if needed.
11316 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11318 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11319 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11320 DAG.getConstant(ShAmt, MVT::i8));
11323 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11324 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11325 if (NeedsCondInvert) // Invert the condition if needed.
11326 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11327 DAG.getConstant(1, Cond.getValueType()));
11329 // Zero extend the condition if needed.
11330 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11331 FalseC->getValueType(0), Cond);
11332 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11333 SDValue(FalseC, 0));
11336 // Optimize cases that will turn into an LEA instruction. This requires
11337 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11338 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11339 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11340 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11342 bool isFastMultiplier = false;
11344 switch ((unsigned char)Diff) {
11346 case 1: // result = add base, cond
11347 case 2: // result = lea base( , cond*2)
11348 case 3: // result = lea base(cond, cond*2)
11349 case 4: // result = lea base( , cond*4)
11350 case 5: // result = lea base(cond, cond*4)
11351 case 8: // result = lea base( , cond*8)
11352 case 9: // result = lea base(cond, cond*8)
11353 isFastMultiplier = true;
11358 if (isFastMultiplier) {
11359 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11360 if (NeedsCondInvert) // Invert the condition if needed.
11361 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11362 DAG.getConstant(1, Cond.getValueType()));
11364 // Zero extend the condition if needed.
11365 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11367 // Scale the condition by the difference.
11369 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11370 DAG.getConstant(Diff, Cond.getValueType()));
11372 // Add the base if non-zero.
11373 if (FalseC->getAPIntValue() != 0)
11374 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11375 SDValue(FalseC, 0));
11385 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11386 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11387 TargetLowering::DAGCombinerInfo &DCI) {
11388 DebugLoc DL = N->getDebugLoc();
11390 // If the flag operand isn't dead, don't touch this CMOV.
11391 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11394 SDValue FalseOp = N->getOperand(0);
11395 SDValue TrueOp = N->getOperand(1);
11396 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11397 SDValue Cond = N->getOperand(3);
11398 if (CC == X86::COND_E || CC == X86::COND_NE) {
11399 switch (Cond.getOpcode()) {
11403 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11404 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11405 return (CC == X86::COND_E) ? FalseOp : TrueOp;
11409 // If this is a select between two integer constants, try to do some
11410 // optimizations. Note that the operands are ordered the opposite of SELECT
11412 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11413 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11414 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11415 // larger than FalseC (the false value).
11416 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11417 CC = X86::GetOppositeBranchCondition(CC);
11418 std::swap(TrueC, FalseC);
11421 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
11422 // This is efficient for any integer data type (including i8/i16) and
11424 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11425 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11426 DAG.getConstant(CC, MVT::i8), Cond);
11428 // Zero extend the condition if needed.
11429 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11431 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11432 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11433 DAG.getConstant(ShAmt, MVT::i8));
11434 if (N->getNumValues() == 2) // Dead flag value?
11435 return DCI.CombineTo(N, Cond, SDValue());
11439 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
11440 // for any integer data type, including i8/i16.
11441 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11442 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11443 DAG.getConstant(CC, MVT::i8), Cond);
11445 // Zero extend the condition if needed.
11446 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11447 FalseC->getValueType(0), Cond);
11448 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11449 SDValue(FalseC, 0));
11451 if (N->getNumValues() == 2) // Dead flag value?
11452 return DCI.CombineTo(N, Cond, SDValue());
11456 // Optimize cases that will turn into an LEA instruction. This requires
11457 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11458 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11459 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11460 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11462 bool isFastMultiplier = false;
11464 switch ((unsigned char)Diff) {
11466 case 1: // result = add base, cond
11467 case 2: // result = lea base( , cond*2)
11468 case 3: // result = lea base(cond, cond*2)
11469 case 4: // result = lea base( , cond*4)
11470 case 5: // result = lea base(cond, cond*4)
11471 case 8: // result = lea base( , cond*8)
11472 case 9: // result = lea base(cond, cond*8)
11473 isFastMultiplier = true;
11478 if (isFastMultiplier) {
11479 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11480 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11481 DAG.getConstant(CC, MVT::i8), Cond);
11482 // Zero extend the condition if needed.
11483 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11485 // Scale the condition by the difference.
11487 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11488 DAG.getConstant(Diff, Cond.getValueType()));
11490 // Add the base if non-zero.
11491 if (FalseC->getAPIntValue() != 0)
11492 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11493 SDValue(FalseC, 0));
11494 if (N->getNumValues() == 2) // Dead flag value?
11495 return DCI.CombineTo(N, Cond, SDValue());
11505 /// PerformMulCombine - Optimize a single multiply with constant into two
11506 /// in order to implement it with two cheaper instructions, e.g.
11507 /// LEA + SHL, LEA + LEA.
11508 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11509 TargetLowering::DAGCombinerInfo &DCI) {
11510 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11513 EVT VT = N->getValueType(0);
11514 if (VT != MVT::i64)
11517 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11520 uint64_t MulAmt = C->getZExtValue();
11521 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11524 uint64_t MulAmt1 = 0;
11525 uint64_t MulAmt2 = 0;
11526 if ((MulAmt % 9) == 0) {
11528 MulAmt2 = MulAmt / 9;
11529 } else if ((MulAmt % 5) == 0) {
11531 MulAmt2 = MulAmt / 5;
11532 } else if ((MulAmt % 3) == 0) {
11534 MulAmt2 = MulAmt / 3;
11537 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11538 DebugLoc DL = N->getDebugLoc();
11540 if (isPowerOf2_64(MulAmt2) &&
11541 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11542 // If second multiplifer is pow2, issue it first. We want the multiply by
11543 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11545 std::swap(MulAmt1, MulAmt2);
11548 if (isPowerOf2_64(MulAmt1))
11549 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11550 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11552 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11553 DAG.getConstant(MulAmt1, VT));
11555 if (isPowerOf2_64(MulAmt2))
11556 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11557 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11559 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11560 DAG.getConstant(MulAmt2, VT));
11562 // Do not add new nodes to DAG combiner worklist.
11563 DCI.CombineTo(N, NewMul, false);
11568 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11569 SDValue N0 = N->getOperand(0);
11570 SDValue N1 = N->getOperand(1);
11571 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11572 EVT VT = N0.getValueType();
11574 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11575 // since the result of setcc_c is all zero's or all ones.
11576 if (N1C && N0.getOpcode() == ISD::AND &&
11577 N0.getOperand(1).getOpcode() == ISD::Constant) {
11578 SDValue N00 = N0.getOperand(0);
11579 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11580 ((N00.getOpcode() == ISD::ANY_EXTEND ||
11581 N00.getOpcode() == ISD::ZERO_EXTEND) &&
11582 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11583 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11584 APInt ShAmt = N1C->getAPIntValue();
11585 Mask = Mask.shl(ShAmt);
11587 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11588 N00, DAG.getConstant(Mask, VT));
11595 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11597 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11598 const X86Subtarget *Subtarget) {
11599 EVT VT = N->getValueType(0);
11600 if (!VT.isVector() && VT.isInteger() &&
11601 N->getOpcode() == ISD::SHL)
11602 return PerformSHLCombine(N, DAG);
11604 // On X86 with SSE2 support, we can transform this to a vector shift if
11605 // all elements are shifted by the same amount. We can't do this in legalize
11606 // because the a constant vector is typically transformed to a constant pool
11607 // so we have no knowledge of the shift amount.
11608 if (!Subtarget->hasSSE2())
11611 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11614 SDValue ShAmtOp = N->getOperand(1);
11615 EVT EltVT = VT.getVectorElementType();
11616 DebugLoc DL = N->getDebugLoc();
11617 SDValue BaseShAmt = SDValue();
11618 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11619 unsigned NumElts = VT.getVectorNumElements();
11621 for (; i != NumElts; ++i) {
11622 SDValue Arg = ShAmtOp.getOperand(i);
11623 if (Arg.getOpcode() == ISD::UNDEF) continue;
11627 for (; i != NumElts; ++i) {
11628 SDValue Arg = ShAmtOp.getOperand(i);
11629 if (Arg.getOpcode() == ISD::UNDEF) continue;
11630 if (Arg != BaseShAmt) {
11634 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11635 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11636 SDValue InVec = ShAmtOp.getOperand(0);
11637 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11638 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11640 for (; i != NumElts; ++i) {
11641 SDValue Arg = InVec.getOperand(i);
11642 if (Arg.getOpcode() == ISD::UNDEF) continue;
11646 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11647 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11648 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11649 if (C->getZExtValue() == SplatIdx)
11650 BaseShAmt = InVec.getOperand(1);
11653 if (BaseShAmt.getNode() == 0)
11654 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11655 DAG.getIntPtrConstant(0));
11659 // The shift amount is an i32.
11660 if (EltVT.bitsGT(MVT::i32))
11661 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11662 else if (EltVT.bitsLT(MVT::i32))
11663 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11665 // The shift amount is identical so we can do a vector shift.
11666 SDValue ValOp = N->getOperand(0);
11667 switch (N->getOpcode()) {
11669 llvm_unreachable("Unknown shift opcode!");
11672 if (VT == MVT::v2i64)
11673 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11674 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11676 if (VT == MVT::v4i32)
11677 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11678 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11680 if (VT == MVT::v8i16)
11681 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11682 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11686 if (VT == MVT::v4i32)
11687 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11688 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11690 if (VT == MVT::v8i16)
11691 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11692 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11696 if (VT == MVT::v2i64)
11697 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11698 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11700 if (VT == MVT::v4i32)
11701 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11702 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11704 if (VT == MVT::v8i16)
11705 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11706 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11714 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11715 TargetLowering::DAGCombinerInfo &DCI,
11716 const X86Subtarget *Subtarget) {
11717 if (DCI.isBeforeLegalizeOps())
11720 // Want to form PANDN nodes, in the hopes of then easily combining them with
11721 // OR and AND nodes to form PBLEND/PSIGN.
11722 EVT VT = N->getValueType(0);
11723 if (VT != MVT::v2i64)
11726 SDValue N0 = N->getOperand(0);
11727 SDValue N1 = N->getOperand(1);
11728 DebugLoc DL = N->getDebugLoc();
11730 // Check LHS for vnot
11731 if (N0.getOpcode() == ISD::XOR &&
11732 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11733 return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11735 // Check RHS for vnot
11736 if (N1.getOpcode() == ISD::XOR &&
11737 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11738 return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11743 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11744 TargetLowering::DAGCombinerInfo &DCI,
11745 const X86Subtarget *Subtarget) {
11746 if (DCI.isBeforeLegalizeOps())
11749 EVT VT = N->getValueType(0);
11750 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11753 SDValue N0 = N->getOperand(0);
11754 SDValue N1 = N->getOperand(1);
11756 // look for psign/blend
11757 if (Subtarget->hasSSSE3()) {
11758 if (VT == MVT::v2i64) {
11759 // Canonicalize pandn to RHS
11760 if (N0.getOpcode() == X86ISD::PANDN)
11762 // or (and (m, x), (pandn m, y))
11763 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11764 SDValue Mask = N1.getOperand(0);
11765 SDValue X = N1.getOperand(1);
11767 if (N0.getOperand(0) == Mask)
11768 Y = N0.getOperand(1);
11769 if (N0.getOperand(1) == Mask)
11770 Y = N0.getOperand(0);
11772 // Check to see if the mask appeared in both the AND and PANDN and
11776 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11777 if (Mask.getOpcode() != ISD::BITCAST ||
11778 X.getOpcode() != ISD::BITCAST ||
11779 Y.getOpcode() != ISD::BITCAST)
11782 // Look through mask bitcast.
11783 Mask = Mask.getOperand(0);
11784 EVT MaskVT = Mask.getValueType();
11786 // Validate that the Mask operand is a vector sra node. The sra node
11787 // will be an intrinsic.
11788 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11791 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11792 // there is no psrai.b
11793 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11794 case Intrinsic::x86_sse2_psrai_w:
11795 case Intrinsic::x86_sse2_psrai_d:
11797 default: return SDValue();
11800 // Check that the SRA is all signbits.
11801 SDValue SraC = Mask.getOperand(2);
11802 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
11803 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11804 if ((SraAmt + 1) != EltBits)
11807 DebugLoc DL = N->getDebugLoc();
11809 // Now we know we at least have a plendvb with the mask val. See if
11810 // we can form a psignb/w/d.
11811 // psign = x.type == y.type == mask.type && y = sub(0, x);
11812 X = X.getOperand(0);
11813 Y = Y.getOperand(0);
11814 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11815 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11816 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11819 case 8: Opc = X86ISD::PSIGNB; break;
11820 case 16: Opc = X86ISD::PSIGNW; break;
11821 case 32: Opc = X86ISD::PSIGND; break;
11825 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11826 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11829 // PBLENDVB only available on SSE 4.1
11830 if (!Subtarget->hasSSE41())
11833 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11834 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11835 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11836 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11837 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11842 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11843 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11845 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11847 if (!N0.hasOneUse() || !N1.hasOneUse())
11850 SDValue ShAmt0 = N0.getOperand(1);
11851 if (ShAmt0.getValueType() != MVT::i8)
11853 SDValue ShAmt1 = N1.getOperand(1);
11854 if (ShAmt1.getValueType() != MVT::i8)
11856 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11857 ShAmt0 = ShAmt0.getOperand(0);
11858 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11859 ShAmt1 = ShAmt1.getOperand(0);
11861 DebugLoc DL = N->getDebugLoc();
11862 unsigned Opc = X86ISD::SHLD;
11863 SDValue Op0 = N0.getOperand(0);
11864 SDValue Op1 = N1.getOperand(0);
11865 if (ShAmt0.getOpcode() == ISD::SUB) {
11866 Opc = X86ISD::SHRD;
11867 std::swap(Op0, Op1);
11868 std::swap(ShAmt0, ShAmt1);
11871 unsigned Bits = VT.getSizeInBits();
11872 if (ShAmt1.getOpcode() == ISD::SUB) {
11873 SDValue Sum = ShAmt1.getOperand(0);
11874 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11875 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11876 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11877 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11878 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11879 return DAG.getNode(Opc, DL, VT,
11881 DAG.getNode(ISD::TRUNCATE, DL,
11884 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11885 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11887 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11888 return DAG.getNode(Opc, DL, VT,
11889 N0.getOperand(0), N1.getOperand(0),
11890 DAG.getNode(ISD::TRUNCATE, DL,
11897 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11898 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11899 const X86Subtarget *Subtarget) {
11900 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
11901 // the FP state in cases where an emms may be missing.
11902 // A preferable solution to the general problem is to figure out the right
11903 // places to insert EMMS. This qualifies as a quick hack.
11905 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11906 StoreSDNode *St = cast<StoreSDNode>(N);
11907 EVT VT = St->getValue().getValueType();
11908 if (VT.getSizeInBits() != 64)
11911 const Function *F = DAG.getMachineFunction().getFunction();
11912 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11913 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11914 && Subtarget->hasSSE2();
11915 if ((VT.isVector() ||
11916 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11917 isa<LoadSDNode>(St->getValue()) &&
11918 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11919 St->getChain().hasOneUse() && !St->isVolatile()) {
11920 SDNode* LdVal = St->getValue().getNode();
11921 LoadSDNode *Ld = 0;
11922 int TokenFactorIndex = -1;
11923 SmallVector<SDValue, 8> Ops;
11924 SDNode* ChainVal = St->getChain().getNode();
11925 // Must be a store of a load. We currently handle two cases: the load
11926 // is a direct child, and it's under an intervening TokenFactor. It is
11927 // possible to dig deeper under nested TokenFactors.
11928 if (ChainVal == LdVal)
11929 Ld = cast<LoadSDNode>(St->getChain());
11930 else if (St->getValue().hasOneUse() &&
11931 ChainVal->getOpcode() == ISD::TokenFactor) {
11932 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11933 if (ChainVal->getOperand(i).getNode() == LdVal) {
11934 TokenFactorIndex = i;
11935 Ld = cast<LoadSDNode>(St->getValue());
11937 Ops.push_back(ChainVal->getOperand(i));
11941 if (!Ld || !ISD::isNormalLoad(Ld))
11944 // If this is not the MMX case, i.e. we are just turning i64 load/store
11945 // into f64 load/store, avoid the transformation if there are multiple
11946 // uses of the loaded value.
11947 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11950 DebugLoc LdDL = Ld->getDebugLoc();
11951 DebugLoc StDL = N->getDebugLoc();
11952 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11953 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11955 if (Subtarget->is64Bit() || F64IsLegal) {
11956 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11957 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11958 Ld->getPointerInfo(), Ld->isVolatile(),
11959 Ld->isNonTemporal(), Ld->getAlignment());
11960 SDValue NewChain = NewLd.getValue(1);
11961 if (TokenFactorIndex != -1) {
11962 Ops.push_back(NewChain);
11963 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11966 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11967 St->getPointerInfo(),
11968 St->isVolatile(), St->isNonTemporal(),
11969 St->getAlignment());
11972 // Otherwise, lower to two pairs of 32-bit loads / stores.
11973 SDValue LoAddr = Ld->getBasePtr();
11974 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11975 DAG.getConstant(4, MVT::i32));
11977 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11978 Ld->getPointerInfo(),
11979 Ld->isVolatile(), Ld->isNonTemporal(),
11980 Ld->getAlignment());
11981 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11982 Ld->getPointerInfo().getWithOffset(4),
11983 Ld->isVolatile(), Ld->isNonTemporal(),
11984 MinAlign(Ld->getAlignment(), 4));
11986 SDValue NewChain = LoLd.getValue(1);
11987 if (TokenFactorIndex != -1) {
11988 Ops.push_back(LoLd);
11989 Ops.push_back(HiLd);
11990 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11994 LoAddr = St->getBasePtr();
11995 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11996 DAG.getConstant(4, MVT::i32));
11998 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11999 St->getPointerInfo(),
12000 St->isVolatile(), St->isNonTemporal(),
12001 St->getAlignment());
12002 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12003 St->getPointerInfo().getWithOffset(4),
12005 St->isNonTemporal(),
12006 MinAlign(St->getAlignment(), 4));
12007 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12012 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12013 /// X86ISD::FXOR nodes.
12014 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12015 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12016 // F[X]OR(0.0, x) -> x
12017 // F[X]OR(x, 0.0) -> x
12018 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12019 if (C->getValueAPF().isPosZero())
12020 return N->getOperand(1);
12021 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12022 if (C->getValueAPF().isPosZero())
12023 return N->getOperand(0);
12027 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12028 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12029 // FAND(0.0, x) -> 0.0
12030 // FAND(x, 0.0) -> 0.0
12031 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12032 if (C->getValueAPF().isPosZero())
12033 return N->getOperand(0);
12034 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12035 if (C->getValueAPF().isPosZero())
12036 return N->getOperand(1);
12040 static SDValue PerformBTCombine(SDNode *N,
12042 TargetLowering::DAGCombinerInfo &DCI) {
12043 // BT ignores high bits in the bit index operand.
12044 SDValue Op1 = N->getOperand(1);
12045 if (Op1.hasOneUse()) {
12046 unsigned BitWidth = Op1.getValueSizeInBits();
12047 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12048 APInt KnownZero, KnownOne;
12049 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12050 !DCI.isBeforeLegalizeOps());
12051 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12052 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12053 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12054 DCI.CommitTargetLoweringOpt(TLO);
12059 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12060 SDValue Op = N->getOperand(0);
12061 if (Op.getOpcode() == ISD::BITCAST)
12062 Op = Op.getOperand(0);
12063 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12064 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12065 VT.getVectorElementType().getSizeInBits() ==
12066 OpVT.getVectorElementType().getSizeInBits()) {
12067 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12072 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12073 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
12074 // (and (i32 x86isd::setcc_carry), 1)
12075 // This eliminates the zext. This transformation is necessary because
12076 // ISD::SETCC is always legalized to i8.
12077 DebugLoc dl = N->getDebugLoc();
12078 SDValue N0 = N->getOperand(0);
12079 EVT VT = N->getValueType(0);
12080 if (N0.getOpcode() == ISD::AND &&
12082 N0.getOperand(0).hasOneUse()) {
12083 SDValue N00 = N0.getOperand(0);
12084 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12086 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12087 if (!C || C->getZExtValue() != 1)
12089 return DAG.getNode(ISD::AND, dl, VT,
12090 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12091 N00.getOperand(0), N00.getOperand(1)),
12092 DAG.getConstant(1, VT));
12098 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12099 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12100 unsigned X86CC = N->getConstantOperandVal(0);
12101 SDValue EFLAG = N->getOperand(1);
12102 DebugLoc DL = N->getDebugLoc();
12104 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12105 // a zext and produces an all-ones bit which is more useful than 0/1 in some
12107 if (X86CC == X86::COND_B)
12108 return DAG.getNode(ISD::AND, DL, MVT::i8,
12109 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12110 DAG.getConstant(X86CC, MVT::i8), EFLAG),
12111 DAG.getConstant(1, MVT::i8));
12116 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12117 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12118 X86TargetLowering::DAGCombinerInfo &DCI) {
12119 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12120 // the result is either zero or one (depending on the input carry bit).
12121 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12122 if (X86::isZeroNode(N->getOperand(0)) &&
12123 X86::isZeroNode(N->getOperand(1)) &&
12124 // We don't have a good way to replace an EFLAGS use, so only do this when
12126 SDValue(N, 1).use_empty()) {
12127 DebugLoc DL = N->getDebugLoc();
12128 EVT VT = N->getValueType(0);
12129 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12130 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12131 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12132 DAG.getConstant(X86::COND_B,MVT::i8),
12134 DAG.getConstant(1, VT));
12135 return DCI.CombineTo(N, Res1, CarryOut);
12141 // fold (add Y, (sete X, 0)) -> adc 0, Y
12142 // (add Y, (setne X, 0)) -> sbb -1, Y
12143 // (sub (sete X, 0), Y) -> sbb 0, Y
12144 // (sub (setne X, 0), Y) -> adc -1, Y
12145 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12146 DebugLoc DL = N->getDebugLoc();
12148 // Look through ZExts.
12149 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12150 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12153 SDValue SetCC = Ext.getOperand(0);
12154 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12157 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12158 if (CC != X86::COND_E && CC != X86::COND_NE)
12161 SDValue Cmp = SetCC.getOperand(1);
12162 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12163 !X86::isZeroNode(Cmp.getOperand(1)) ||
12164 !Cmp.getOperand(0).getValueType().isInteger())
12167 SDValue CmpOp0 = Cmp.getOperand(0);
12168 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12169 DAG.getConstant(1, CmpOp0.getValueType()));
12171 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12172 if (CC == X86::COND_NE)
12173 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12174 DL, OtherVal.getValueType(), OtherVal,
12175 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12176 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12177 DL, OtherVal.getValueType(), OtherVal,
12178 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12181 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12182 DAGCombinerInfo &DCI) const {
12183 SelectionDAG &DAG = DCI.DAG;
12184 switch (N->getOpcode()) {
12186 case ISD::EXTRACT_VECTOR_ELT:
12187 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12188 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
12189 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
12191 case ISD::SUB: return OptimizeConditonalInDecrement(N, DAG);
12192 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
12193 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
12196 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
12197 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
12198 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
12199 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
12201 case X86ISD::FOR: return PerformFORCombine(N, DAG);
12202 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
12203 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
12204 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
12205 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
12206 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
12207 case X86ISD::SHUFPS: // Handle all target specific shuffles
12208 case X86ISD::SHUFPD:
12209 case X86ISD::PALIGN:
12210 case X86ISD::PUNPCKHBW:
12211 case X86ISD::PUNPCKHWD:
12212 case X86ISD::PUNPCKHDQ:
12213 case X86ISD::PUNPCKHQDQ:
12214 case X86ISD::UNPCKHPS:
12215 case X86ISD::UNPCKHPD:
12216 case X86ISD::PUNPCKLBW:
12217 case X86ISD::PUNPCKLWD:
12218 case X86ISD::PUNPCKLDQ:
12219 case X86ISD::PUNPCKLQDQ:
12220 case X86ISD::UNPCKLPS:
12221 case X86ISD::UNPCKLPD:
12222 case X86ISD::VUNPCKLPS:
12223 case X86ISD::VUNPCKLPD:
12224 case X86ISD::VUNPCKLPSY:
12225 case X86ISD::VUNPCKLPDY:
12226 case X86ISD::MOVHLPS:
12227 case X86ISD::MOVLHPS:
12228 case X86ISD::PSHUFD:
12229 case X86ISD::PSHUFHW:
12230 case X86ISD::PSHUFLW:
12231 case X86ISD::MOVSS:
12232 case X86ISD::MOVSD:
12233 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12239 /// isTypeDesirableForOp - Return true if the target has native support for
12240 /// the specified value type and it is 'desirable' to use the type for the
12241 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12242 /// instruction encodings are longer and some i16 instructions are slow.
12243 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12244 if (!isTypeLegal(VT))
12246 if (VT != MVT::i16)
12253 case ISD::SIGN_EXTEND:
12254 case ISD::ZERO_EXTEND:
12255 case ISD::ANY_EXTEND:
12268 /// IsDesirableToPromoteOp - This method query the target whether it is
12269 /// beneficial for dag combiner to promote the specified node. If true, it
12270 /// should return the desired promotion type by reference.
12271 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12272 EVT VT = Op.getValueType();
12273 if (VT != MVT::i16)
12276 bool Promote = false;
12277 bool Commute = false;
12278 switch (Op.getOpcode()) {
12281 LoadSDNode *LD = cast<LoadSDNode>(Op);
12282 // If the non-extending load has a single use and it's not live out, then it
12283 // might be folded.
12284 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12285 Op.hasOneUse()*/) {
12286 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12287 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12288 // The only case where we'd want to promote LOAD (rather then it being
12289 // promoted as an operand is when it's only use is liveout.
12290 if (UI->getOpcode() != ISD::CopyToReg)
12297 case ISD::SIGN_EXTEND:
12298 case ISD::ZERO_EXTEND:
12299 case ISD::ANY_EXTEND:
12304 SDValue N0 = Op.getOperand(0);
12305 // Look out for (store (shl (load), x)).
12306 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12319 SDValue N0 = Op.getOperand(0);
12320 SDValue N1 = Op.getOperand(1);
12321 if (!Commute && MayFoldLoad(N1))
12323 // Avoid disabling potential load folding opportunities.
12324 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12326 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12336 //===----------------------------------------------------------------------===//
12337 // X86 Inline Assembly Support
12338 //===----------------------------------------------------------------------===//
12340 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12341 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12343 std::string AsmStr = IA->getAsmString();
12345 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12346 SmallVector<StringRef, 4> AsmPieces;
12347 SplitString(AsmStr, AsmPieces, ";\n");
12349 switch (AsmPieces.size()) {
12350 default: return false;
12352 AsmStr = AsmPieces[0];
12354 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
12356 // FIXME: this should verify that we are targeting a 486 or better. If not,
12357 // we will turn this bswap into something that will be lowered to logical ops
12358 // instead of emitting the bswap asm. For now, we don't support 486 or lower
12359 // so don't worry about this.
12361 if (AsmPieces.size() == 2 &&
12362 (AsmPieces[0] == "bswap" ||
12363 AsmPieces[0] == "bswapq" ||
12364 AsmPieces[0] == "bswapl") &&
12365 (AsmPieces[1] == "$0" ||
12366 AsmPieces[1] == "${0:q}")) {
12367 // No need to check constraints, nothing other than the equivalent of
12368 // "=r,0" would be valid here.
12369 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12370 if (!Ty || Ty->getBitWidth() % 16 != 0)
12372 return IntrinsicLowering::LowerToByteSwap(CI);
12374 // rorw $$8, ${0:w} --> llvm.bswap.i16
12375 if (CI->getType()->isIntegerTy(16) &&
12376 AsmPieces.size() == 3 &&
12377 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12378 AsmPieces[1] == "$$8," &&
12379 AsmPieces[2] == "${0:w}" &&
12380 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12382 const std::string &ConstraintsStr = IA->getConstraintString();
12383 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12384 std::sort(AsmPieces.begin(), AsmPieces.end());
12385 if (AsmPieces.size() == 4 &&
12386 AsmPieces[0] == "~{cc}" &&
12387 AsmPieces[1] == "~{dirflag}" &&
12388 AsmPieces[2] == "~{flags}" &&
12389 AsmPieces[3] == "~{fpsr}") {
12390 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12391 if (!Ty || Ty->getBitWidth() % 16 != 0)
12393 return IntrinsicLowering::LowerToByteSwap(CI);
12398 if (CI->getType()->isIntegerTy(32) &&
12399 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12400 SmallVector<StringRef, 4> Words;
12401 SplitString(AsmPieces[0], Words, " \t,");
12402 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12403 Words[2] == "${0:w}") {
12405 SplitString(AsmPieces[1], Words, " \t,");
12406 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12407 Words[2] == "$0") {
12409 SplitString(AsmPieces[2], Words, " \t,");
12410 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12411 Words[2] == "${0:w}") {
12413 const std::string &ConstraintsStr = IA->getConstraintString();
12414 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12415 std::sort(AsmPieces.begin(), AsmPieces.end());
12416 if (AsmPieces.size() == 4 &&
12417 AsmPieces[0] == "~{cc}" &&
12418 AsmPieces[1] == "~{dirflag}" &&
12419 AsmPieces[2] == "~{flags}" &&
12420 AsmPieces[3] == "~{fpsr}") {
12421 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12422 if (!Ty || Ty->getBitWidth() % 16 != 0)
12424 return IntrinsicLowering::LowerToByteSwap(CI);
12431 if (CI->getType()->isIntegerTy(64)) {
12432 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12433 if (Constraints.size() >= 2 &&
12434 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12435 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12436 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
12437 SmallVector<StringRef, 4> Words;
12438 SplitString(AsmPieces[0], Words, " \t");
12439 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12441 SplitString(AsmPieces[1], Words, " \t");
12442 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12444 SplitString(AsmPieces[2], Words, " \t,");
12445 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12446 Words[2] == "%edx") {
12447 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12448 if (!Ty || Ty->getBitWidth() % 16 != 0)
12450 return IntrinsicLowering::LowerToByteSwap(CI);
12463 /// getConstraintType - Given a constraint letter, return the type of
12464 /// constraint it is for this target.
12465 X86TargetLowering::ConstraintType
12466 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12467 if (Constraint.size() == 1) {
12468 switch (Constraint[0]) {
12478 return C_RegisterClass;
12502 return TargetLowering::getConstraintType(Constraint);
12505 /// Examine constraint type and operand type and determine a weight value.
12506 /// This object must already have been set up with the operand type
12507 /// and the current alternative constraint selected.
12508 TargetLowering::ConstraintWeight
12509 X86TargetLowering::getSingleConstraintMatchWeight(
12510 AsmOperandInfo &info, const char *constraint) const {
12511 ConstraintWeight weight = CW_Invalid;
12512 Value *CallOperandVal = info.CallOperandVal;
12513 // If we don't have a value, we can't do a match,
12514 // but allow it at the lowest weight.
12515 if (CallOperandVal == NULL)
12517 const Type *type = CallOperandVal->getType();
12518 // Look at the constraint type.
12519 switch (*constraint) {
12521 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12532 if (CallOperandVal->getType()->isIntegerTy())
12533 weight = CW_SpecificReg;
12538 if (type->isFloatingPointTy())
12539 weight = CW_SpecificReg;
12542 if (type->isX86_MMXTy() && Subtarget->hasMMX())
12543 weight = CW_SpecificReg;
12547 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12548 weight = CW_Register;
12551 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12552 if (C->getZExtValue() <= 31)
12553 weight = CW_Constant;
12557 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12558 if (C->getZExtValue() <= 63)
12559 weight = CW_Constant;
12563 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12564 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12565 weight = CW_Constant;
12569 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12570 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12571 weight = CW_Constant;
12575 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12576 if (C->getZExtValue() <= 3)
12577 weight = CW_Constant;
12581 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12582 if (C->getZExtValue() <= 0xff)
12583 weight = CW_Constant;
12588 if (dyn_cast<ConstantFP>(CallOperandVal)) {
12589 weight = CW_Constant;
12593 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12594 if ((C->getSExtValue() >= -0x80000000LL) &&
12595 (C->getSExtValue() <= 0x7fffffffLL))
12596 weight = CW_Constant;
12600 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12601 if (C->getZExtValue() <= 0xffffffff)
12602 weight = CW_Constant;
12609 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12610 /// with another that has more specific requirements based on the type of the
12611 /// corresponding operand.
12612 const char *X86TargetLowering::
12613 LowerXConstraint(EVT ConstraintVT) const {
12614 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12615 // 'f' like normal targets.
12616 if (ConstraintVT.isFloatingPoint()) {
12617 if (Subtarget->hasXMMInt())
12619 if (Subtarget->hasXMM())
12623 return TargetLowering::LowerXConstraint(ConstraintVT);
12626 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12627 /// vector. If it is invalid, don't add anything to Ops.
12628 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12630 std::vector<SDValue>&Ops,
12631 SelectionDAG &DAG) const {
12632 SDValue Result(0, 0);
12634 switch (Constraint) {
12637 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12638 if (C->getZExtValue() <= 31) {
12639 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12645 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12646 if (C->getZExtValue() <= 63) {
12647 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12653 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12654 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12655 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12661 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12662 if (C->getZExtValue() <= 255) {
12663 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12669 // 32-bit signed value
12670 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12671 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12672 C->getSExtValue())) {
12673 // Widen to 64 bits here to get it sign extended.
12674 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12677 // FIXME gcc accepts some relocatable values here too, but only in certain
12678 // memory models; it's complicated.
12683 // 32-bit unsigned value
12684 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12685 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12686 C->getZExtValue())) {
12687 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12691 // FIXME gcc accepts some relocatable values here too, but only in certain
12692 // memory models; it's complicated.
12696 // Literal immediates are always ok.
12697 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12698 // Widen to 64 bits here to get it sign extended.
12699 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12703 // In any sort of PIC mode addresses need to be computed at runtime by
12704 // adding in a register or some sort of table lookup. These can't
12705 // be used as immediates.
12706 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12709 // If we are in non-pic codegen mode, we allow the address of a global (with
12710 // an optional displacement) to be used with 'i'.
12711 GlobalAddressSDNode *GA = 0;
12712 int64_t Offset = 0;
12714 // Match either (GA), (GA+C), (GA+C1+C2), etc.
12716 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12717 Offset += GA->getOffset();
12719 } else if (Op.getOpcode() == ISD::ADD) {
12720 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12721 Offset += C->getZExtValue();
12722 Op = Op.getOperand(0);
12725 } else if (Op.getOpcode() == ISD::SUB) {
12726 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12727 Offset += -C->getZExtValue();
12728 Op = Op.getOperand(0);
12733 // Otherwise, this isn't something we can handle, reject it.
12737 const GlobalValue *GV = GA->getGlobal();
12738 // If we require an extra load to get this address, as in PIC mode, we
12739 // can't accept it.
12740 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12741 getTargetMachine())))
12744 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12745 GA->getValueType(0), Offset);
12750 if (Result.getNode()) {
12751 Ops.push_back(Result);
12754 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12757 std::vector<unsigned> X86TargetLowering::
12758 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12760 if (Constraint.size() == 1) {
12761 // FIXME: not handling fp-stack yet!
12762 switch (Constraint[0]) { // GCC X86 Constraint Letters
12763 default: break; // Unknown constraint letter
12764 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12765 if (Subtarget->is64Bit()) {
12766 if (VT == MVT::i32)
12767 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12768 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12769 X86::R10D,X86::R11D,X86::R12D,
12770 X86::R13D,X86::R14D,X86::R15D,
12771 X86::EBP, X86::ESP, 0);
12772 else if (VT == MVT::i16)
12773 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
12774 X86::SI, X86::DI, X86::R8W,X86::R9W,
12775 X86::R10W,X86::R11W,X86::R12W,
12776 X86::R13W,X86::R14W,X86::R15W,
12777 X86::BP, X86::SP, 0);
12778 else if (VT == MVT::i8)
12779 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
12780 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12781 X86::R10B,X86::R11B,X86::R12B,
12782 X86::R13B,X86::R14B,X86::R15B,
12783 X86::BPL, X86::SPL, 0);
12785 else if (VT == MVT::i64)
12786 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12787 X86::RSI, X86::RDI, X86::R8, X86::R9,
12788 X86::R10, X86::R11, X86::R12,
12789 X86::R13, X86::R14, X86::R15,
12790 X86::RBP, X86::RSP, 0);
12794 // 32-bit fallthrough
12795 case 'Q': // Q_REGS
12796 if (VT == MVT::i32)
12797 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12798 else if (VT == MVT::i16)
12799 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12800 else if (VT == MVT::i8)
12801 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12802 else if (VT == MVT::i64)
12803 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12808 return std::vector<unsigned>();
12811 std::pair<unsigned, const TargetRegisterClass*>
12812 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12814 // First, see if this is a constraint that directly corresponds to an LLVM
12816 if (Constraint.size() == 1) {
12817 // GCC Constraint Letters
12818 switch (Constraint[0]) {
12820 case 'r': // GENERAL_REGS
12821 case 'l': // INDEX_REGS
12823 return std::make_pair(0U, X86::GR8RegisterClass);
12824 if (VT == MVT::i16)
12825 return std::make_pair(0U, X86::GR16RegisterClass);
12826 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
12827 return std::make_pair(0U, X86::GR32RegisterClass);
12828 return std::make_pair(0U, X86::GR64RegisterClass);
12829 case 'R': // LEGACY_REGS
12831 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12832 if (VT == MVT::i16)
12833 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12834 if (VT == MVT::i32 || !Subtarget->is64Bit())
12835 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12836 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12837 case 'f': // FP Stack registers.
12838 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12839 // value to the correct fpstack register class.
12840 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12841 return std::make_pair(0U, X86::RFP32RegisterClass);
12842 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12843 return std::make_pair(0U, X86::RFP64RegisterClass);
12844 return std::make_pair(0U, X86::RFP80RegisterClass);
12845 case 'y': // MMX_REGS if MMX allowed.
12846 if (!Subtarget->hasMMX()) break;
12847 return std::make_pair(0U, X86::VR64RegisterClass);
12848 case 'Y': // SSE_REGS if SSE2 allowed
12849 if (!Subtarget->hasXMMInt()) break;
12851 case 'x': // SSE_REGS if SSE1 allowed
12852 if (!Subtarget->hasXMM()) break;
12854 switch (VT.getSimpleVT().SimpleTy) {
12856 // Scalar SSE types.
12859 return std::make_pair(0U, X86::FR32RegisterClass);
12862 return std::make_pair(0U, X86::FR64RegisterClass);
12870 return std::make_pair(0U, X86::VR128RegisterClass);
12876 // Use the default implementation in TargetLowering to convert the register
12877 // constraint into a member of a register class.
12878 std::pair<unsigned, const TargetRegisterClass*> Res;
12879 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12881 // Not found as a standard register?
12882 if (Res.second == 0) {
12883 // Map st(0) -> st(7) -> ST0
12884 if (Constraint.size() == 7 && Constraint[0] == '{' &&
12885 tolower(Constraint[1]) == 's' &&
12886 tolower(Constraint[2]) == 't' &&
12887 Constraint[3] == '(' &&
12888 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12889 Constraint[5] == ')' &&
12890 Constraint[6] == '}') {
12892 Res.first = X86::ST0+Constraint[4]-'0';
12893 Res.second = X86::RFP80RegisterClass;
12897 // GCC allows "st(0)" to be called just plain "st".
12898 if (StringRef("{st}").equals_lower(Constraint)) {
12899 Res.first = X86::ST0;
12900 Res.second = X86::RFP80RegisterClass;
12905 if (StringRef("{flags}").equals_lower(Constraint)) {
12906 Res.first = X86::EFLAGS;
12907 Res.second = X86::CCRRegisterClass;
12911 // 'A' means EAX + EDX.
12912 if (Constraint == "A") {
12913 Res.first = X86::EAX;
12914 Res.second = X86::GR32_ADRegisterClass;
12920 // Otherwise, check to see if this is a register class of the wrong value
12921 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12922 // turn into {ax},{dx}.
12923 if (Res.second->hasType(VT))
12924 return Res; // Correct type already, nothing to do.
12926 // All of the single-register GCC register classes map their values onto
12927 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
12928 // really want an 8-bit or 32-bit register, map to the appropriate register
12929 // class and return the appropriate register.
12930 if (Res.second == X86::GR16RegisterClass) {
12931 if (VT == MVT::i8) {
12932 unsigned DestReg = 0;
12933 switch (Res.first) {
12935 case X86::AX: DestReg = X86::AL; break;
12936 case X86::DX: DestReg = X86::DL; break;
12937 case X86::CX: DestReg = X86::CL; break;
12938 case X86::BX: DestReg = X86::BL; break;
12941 Res.first = DestReg;
12942 Res.second = X86::GR8RegisterClass;
12944 } else if (VT == MVT::i32) {
12945 unsigned DestReg = 0;
12946 switch (Res.first) {
12948 case X86::AX: DestReg = X86::EAX; break;
12949 case X86::DX: DestReg = X86::EDX; break;
12950 case X86::CX: DestReg = X86::ECX; break;
12951 case X86::BX: DestReg = X86::EBX; break;
12952 case X86::SI: DestReg = X86::ESI; break;
12953 case X86::DI: DestReg = X86::EDI; break;
12954 case X86::BP: DestReg = X86::EBP; break;
12955 case X86::SP: DestReg = X86::ESP; break;
12958 Res.first = DestReg;
12959 Res.second = X86::GR32RegisterClass;
12961 } else if (VT == MVT::i64) {
12962 unsigned DestReg = 0;
12963 switch (Res.first) {
12965 case X86::AX: DestReg = X86::RAX; break;
12966 case X86::DX: DestReg = X86::RDX; break;
12967 case X86::CX: DestReg = X86::RCX; break;
12968 case X86::BX: DestReg = X86::RBX; break;
12969 case X86::SI: DestReg = X86::RSI; break;
12970 case X86::DI: DestReg = X86::RDI; break;
12971 case X86::BP: DestReg = X86::RBP; break;
12972 case X86::SP: DestReg = X86::RSP; break;
12975 Res.first = DestReg;
12976 Res.second = X86::GR64RegisterClass;
12979 } else if (Res.second == X86::FR32RegisterClass ||
12980 Res.second == X86::FR64RegisterClass ||
12981 Res.second == X86::VR128RegisterClass) {
12982 // Handle references to XMM physical registers that got mapped into the
12983 // wrong class. This can happen with constraints like {xmm0} where the
12984 // target independent register mapper will just pick the first match it can
12985 // find, ignoring the required type.
12986 if (VT == MVT::f32)
12987 Res.second = X86::FR32RegisterClass;
12988 else if (VT == MVT::f64)
12989 Res.second = X86::FR64RegisterClass;
12990 else if (X86::VR128RegisterClass->hasType(VT))
12991 Res.second = X86::VR128RegisterClass;