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 // Lower this to FGETSIGNx86 plus an AND.
578 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
579 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
581 // We don't support sin/cos/fmod
582 setOperationAction(ISD::FSIN , MVT::f64, Expand);
583 setOperationAction(ISD::FCOS , MVT::f64, Expand);
584 setOperationAction(ISD::FSIN , MVT::f32, Expand);
585 setOperationAction(ISD::FCOS , MVT::f32, Expand);
587 // Expand FP immediates into loads from the stack, except for the special
589 addLegalFPImmediate(APFloat(+0.0)); // xorpd
590 addLegalFPImmediate(APFloat(+0.0f)); // xorps
591 } else if (!UseSoftFloat && X86ScalarSSEf32) {
592 // Use SSE for f32, x87 for f64.
593 // Set up the FP register classes.
594 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
595 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
597 // Use ANDPS to simulate FABS.
598 setOperationAction(ISD::FABS , MVT::f32, Custom);
600 // Use XORP to simulate FNEG.
601 setOperationAction(ISD::FNEG , MVT::f32, Custom);
603 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
605 // Use ANDPS and ORPS to simulate FCOPYSIGN.
606 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
607 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
609 // We don't support sin/cos/fmod
610 setOperationAction(ISD::FSIN , MVT::f32, Expand);
611 setOperationAction(ISD::FCOS , MVT::f32, Expand);
613 // Special cases we handle for FP constants.
614 addLegalFPImmediate(APFloat(+0.0f)); // xorps
615 addLegalFPImmediate(APFloat(+0.0)); // FLD0
616 addLegalFPImmediate(APFloat(+1.0)); // FLD1
617 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
618 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
621 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
622 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
624 } else if (!UseSoftFloat) {
625 // f32 and f64 in x87.
626 // Set up the FP register classes.
627 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
628 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
630 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
631 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
632 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
636 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
637 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
639 addLegalFPImmediate(APFloat(+0.0)); // FLD0
640 addLegalFPImmediate(APFloat(+1.0)); // FLD1
641 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
642 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
643 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
644 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
645 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
646 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
649 // Long double always uses X87.
651 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
652 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
653 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
655 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
656 addLegalFPImmediate(TmpFlt); // FLD0
658 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
661 APFloat TmpFlt2(+1.0);
662 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
664 addLegalFPImmediate(TmpFlt2); // FLD1
665 TmpFlt2.changeSign();
666 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
670 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
671 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
675 // Always use a library call for pow.
676 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
677 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
678 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
680 setOperationAction(ISD::FLOG, MVT::f80, Expand);
681 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
682 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
683 setOperationAction(ISD::FEXP, MVT::f80, Expand);
684 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
686 // First set operation action for all vector types to either promote
687 // (for widening) or expand (for scalarization). Then we will selectively
688 // turn on ones that can be effectively codegen'd.
689 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
690 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
691 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
692 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
693 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
694 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
695 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
696 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
698 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
699 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
700 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
701 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
702 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
703 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
704 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
705 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
706 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
708 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
709 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
741 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
745 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
746 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
747 setTruncStoreAction((MVT::SimpleValueType)VT,
748 (MVT::SimpleValueType)InnerVT, Expand);
749 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
750 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
751 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
754 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
755 // with -msoft-float, disable use of MMX as well.
756 if (!UseSoftFloat && Subtarget->hasMMX()) {
757 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
758 // No operations on x86mmx supported, everything uses intrinsics.
761 // MMX-sized vectors (other than x86mmx) are expected to be expanded
762 // into smaller operations.
763 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
764 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
765 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
766 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
767 setOperationAction(ISD::AND, MVT::v8i8, Expand);
768 setOperationAction(ISD::AND, MVT::v4i16, Expand);
769 setOperationAction(ISD::AND, MVT::v2i32, Expand);
770 setOperationAction(ISD::AND, MVT::v1i64, Expand);
771 setOperationAction(ISD::OR, MVT::v8i8, Expand);
772 setOperationAction(ISD::OR, MVT::v4i16, Expand);
773 setOperationAction(ISD::OR, MVT::v2i32, Expand);
774 setOperationAction(ISD::OR, MVT::v1i64, Expand);
775 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
776 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
777 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
778 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
779 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
780 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
781 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
782 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
783 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
784 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
785 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
786 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
787 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
788 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
789 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
790 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
791 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
793 if (!UseSoftFloat && Subtarget->hasXMM()) {
794 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
796 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
797 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
798 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
799 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
800 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
801 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
802 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
803 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
804 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
805 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
806 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
807 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
810 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
811 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
813 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
814 // registers cannot be used even for integer operations.
815 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
816 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
817 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
818 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
820 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
821 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
822 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
823 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
824 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
825 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
826 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
827 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
828 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
829 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
830 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
831 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
832 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
833 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
834 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
835 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
837 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
838 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
839 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
840 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
842 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
843 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
844 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
845 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
846 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
848 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
849 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
850 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
851 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
852 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
854 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
855 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
856 EVT VT = (MVT::SimpleValueType)i;
857 // Do not attempt to custom lower non-power-of-2 vectors
858 if (!isPowerOf2_32(VT.getVectorNumElements()))
860 // Do not attempt to custom lower non-128-bit vectors
861 if (!VT.is128BitVector())
863 setOperationAction(ISD::BUILD_VECTOR,
864 VT.getSimpleVT().SimpleTy, Custom);
865 setOperationAction(ISD::VECTOR_SHUFFLE,
866 VT.getSimpleVT().SimpleTy, Custom);
867 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
868 VT.getSimpleVT().SimpleTy, Custom);
871 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
872 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
873 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
874 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
875 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
876 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
878 if (Subtarget->is64Bit()) {
879 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
880 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
883 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
884 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
885 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
888 // Do not attempt to promote non-128-bit vectors
889 if (!VT.is128BitVector())
892 setOperationAction(ISD::AND, SVT, Promote);
893 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
894 setOperationAction(ISD::OR, SVT, Promote);
895 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
896 setOperationAction(ISD::XOR, SVT, Promote);
897 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
898 setOperationAction(ISD::LOAD, SVT, Promote);
899 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
900 setOperationAction(ISD::SELECT, SVT, Promote);
901 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
904 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
906 // Custom lower v2i64 and v2f64 selects.
907 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
908 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
909 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
910 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
912 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
913 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
916 if (Subtarget->hasSSE41()) {
917 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
918 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
919 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
920 setOperationAction(ISD::FRINT, MVT::f32, Legal);
921 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
922 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
923 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
924 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
925 setOperationAction(ISD::FRINT, MVT::f64, Legal);
926 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
928 // FIXME: Do we need to handle scalar-to-vector here?
929 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
931 // Can turn SHL into an integer multiply.
932 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
933 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
935 // i8 and i16 vectors are custom , because the source register and source
936 // source memory operand types are not the same width. f32 vectors are
937 // custom since the immediate controlling the insert encodes additional
939 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
940 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
941 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
942 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
944 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
945 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
946 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
947 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
949 if (Subtarget->is64Bit()) {
950 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
951 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
955 if (Subtarget->hasSSE2()) {
956 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
957 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
958 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
960 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
961 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
962 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
964 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
965 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
968 if (Subtarget->hasSSE42())
969 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
971 if (!UseSoftFloat && Subtarget->hasAVX()) {
972 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
973 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
974 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
975 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
976 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
978 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
979 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
980 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
981 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
983 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
984 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
985 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
986 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
987 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
988 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
990 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
991 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
992 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
993 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
994 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
995 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
997 // Custom lower build_vector, vector_shuffle, scalar_to_vector,
998 // insert_vector_elt extract_subvector and extract_vector_elt for
1000 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1001 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1003 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1004 // Do not attempt to custom lower non-256-bit vectors
1005 if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
1006 || (MVT(VT).getSizeInBits() < 256))
1008 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1009 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1010 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1011 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1012 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1014 // Custom-lower insert_subvector and extract_subvector based on
1016 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1017 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1019 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1020 // Do not attempt to custom lower non-256-bit vectors
1021 if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1024 if (MVT(VT).getSizeInBits() == 128) {
1025 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1027 else if (MVT(VT).getSizeInBits() == 256) {
1028 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1032 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1033 // Don't promote loads because we need them for VPERM vector index versions.
1035 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1036 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1038 if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1039 || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1041 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
1042 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v4i64);
1043 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
1044 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v4i64);
1045 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
1046 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v4i64);
1047 //setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
1048 //AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v4i64);
1049 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1050 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1054 // We want to custom lower some of our intrinsics.
1055 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1058 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1059 // handle type legalization for these operations here.
1061 // FIXME: We really should do custom legalization for addition and
1062 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1063 // than generic legalization for 64-bit multiplication-with-overflow, though.
1064 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1065 // Add/Sub/Mul with overflow operations are custom lowered.
1067 setOperationAction(ISD::SADDO, VT, Custom);
1068 setOperationAction(ISD::UADDO, VT, Custom);
1069 setOperationAction(ISD::SSUBO, VT, Custom);
1070 setOperationAction(ISD::USUBO, VT, Custom);
1071 setOperationAction(ISD::SMULO, VT, Custom);
1072 setOperationAction(ISD::UMULO, VT, Custom);
1075 // There are no 8-bit 3-address imul/mul instructions
1076 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1077 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1079 if (!Subtarget->is64Bit()) {
1080 // These libcalls are not available in 32-bit.
1081 setLibcallName(RTLIB::SHL_I128, 0);
1082 setLibcallName(RTLIB::SRL_I128, 0);
1083 setLibcallName(RTLIB::SRA_I128, 0);
1086 // We have target-specific dag combine patterns for the following nodes:
1087 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1088 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1089 setTargetDAGCombine(ISD::BUILD_VECTOR);
1090 setTargetDAGCombine(ISD::SELECT);
1091 setTargetDAGCombine(ISD::SHL);
1092 setTargetDAGCombine(ISD::SRA);
1093 setTargetDAGCombine(ISD::SRL);
1094 setTargetDAGCombine(ISD::OR);
1095 setTargetDAGCombine(ISD::AND);
1096 setTargetDAGCombine(ISD::ADD);
1097 setTargetDAGCombine(ISD::SUB);
1098 setTargetDAGCombine(ISD::STORE);
1099 setTargetDAGCombine(ISD::ZERO_EXTEND);
1100 setTargetDAGCombine(ISD::SINT_TO_FP);
1101 if (Subtarget->is64Bit())
1102 setTargetDAGCombine(ISD::MUL);
1104 computeRegisterProperties();
1106 // On Darwin, -Os means optimize for size without hurting performance,
1107 // do not reduce the limit.
1108 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1109 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1110 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1111 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1112 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1113 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1114 setPrefLoopAlignment(16);
1115 benefitFromCodePlacementOpt = true;
1117 setPrefFunctionAlignment(4);
1121 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1126 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1127 /// the desired ByVal argument alignment.
1128 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1131 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1132 if (VTy->getBitWidth() == 128)
1134 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1135 unsigned EltAlign = 0;
1136 getMaxByValAlign(ATy->getElementType(), EltAlign);
1137 if (EltAlign > MaxAlign)
1138 MaxAlign = EltAlign;
1139 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1140 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1141 unsigned EltAlign = 0;
1142 getMaxByValAlign(STy->getElementType(i), EltAlign);
1143 if (EltAlign > MaxAlign)
1144 MaxAlign = EltAlign;
1152 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1153 /// function arguments in the caller parameter area. For X86, aggregates
1154 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1155 /// are at 4-byte boundaries.
1156 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1157 if (Subtarget->is64Bit()) {
1158 // Max of 8 and alignment of type.
1159 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1166 if (Subtarget->hasXMM())
1167 getMaxByValAlign(Ty, Align);
1171 /// getOptimalMemOpType - Returns the target specific optimal type for load
1172 /// and store operations as a result of memset, memcpy, and memmove
1173 /// lowering. If DstAlign is zero that means it's safe to destination
1174 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1175 /// means there isn't a need to check it against alignment requirement,
1176 /// probably because the source does not need to be loaded. If
1177 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1178 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1179 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1180 /// constant so it does not need to be loaded.
1181 /// It returns EVT::Other if the type should be determined using generic
1182 /// target-independent logic.
1184 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1185 unsigned DstAlign, unsigned SrcAlign,
1186 bool NonScalarIntSafe,
1188 MachineFunction &MF) const {
1189 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1190 // linux. This is because the stack realignment code can't handle certain
1191 // cases like PR2962. This should be removed when PR2962 is fixed.
1192 const Function *F = MF.getFunction();
1193 if (NonScalarIntSafe &&
1194 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1196 (Subtarget->isUnalignedMemAccessFast() ||
1197 ((DstAlign == 0 || DstAlign >= 16) &&
1198 (SrcAlign == 0 || SrcAlign >= 16))) &&
1199 Subtarget->getStackAlignment() >= 16) {
1200 if (Subtarget->hasSSE2())
1202 if (Subtarget->hasSSE1())
1204 } else if (!MemcpyStrSrc && Size >= 8 &&
1205 !Subtarget->is64Bit() &&
1206 Subtarget->getStackAlignment() >= 8 &&
1207 Subtarget->hasXMMInt()) {
1208 // Do not use f64 to lower memcpy if source is string constant. It's
1209 // better to use i32 to avoid the loads.
1213 if (Subtarget->is64Bit() && Size >= 8)
1218 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1219 /// current function. The returned value is a member of the
1220 /// MachineJumpTableInfo::JTEntryKind enum.
1221 unsigned X86TargetLowering::getJumpTableEncoding() const {
1222 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1224 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1225 Subtarget->isPICStyleGOT())
1226 return MachineJumpTableInfo::EK_Custom32;
1228 // Otherwise, use the normal jump table encoding heuristics.
1229 return TargetLowering::getJumpTableEncoding();
1233 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1234 const MachineBasicBlock *MBB,
1235 unsigned uid,MCContext &Ctx) const{
1236 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1237 Subtarget->isPICStyleGOT());
1238 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1240 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1241 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1244 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1246 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1247 SelectionDAG &DAG) const {
1248 if (!Subtarget->is64Bit())
1249 // This doesn't have DebugLoc associated with it, but is not really the
1250 // same as a Register.
1251 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1255 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1256 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1258 const MCExpr *X86TargetLowering::
1259 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1260 MCContext &Ctx) const {
1261 // X86-64 uses RIP relative addressing based on the jump table label.
1262 if (Subtarget->isPICStyleRIPRel())
1263 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1265 // Otherwise, the reference is relative to the PIC base.
1266 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1269 // FIXME: Why this routine is here? Move to RegInfo!
1270 std::pair<const TargetRegisterClass*, uint8_t>
1271 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1272 const TargetRegisterClass *RRC = 0;
1274 switch (VT.getSimpleVT().SimpleTy) {
1276 return TargetLowering::findRepresentativeClass(VT);
1277 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1278 RRC = (Subtarget->is64Bit()
1279 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1282 RRC = X86::VR64RegisterClass;
1284 case MVT::f32: case MVT::f64:
1285 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1286 case MVT::v4f32: case MVT::v2f64:
1287 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1289 RRC = X86::VR128RegisterClass;
1292 return std::make_pair(RRC, Cost);
1295 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1296 unsigned &Offset) const {
1297 if (!Subtarget->isTargetLinux())
1300 if (Subtarget->is64Bit()) {
1301 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1303 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1316 //===----------------------------------------------------------------------===//
1317 // Return Value Calling Convention Implementation
1318 //===----------------------------------------------------------------------===//
1320 #include "X86GenCallingConv.inc"
1323 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1324 MachineFunction &MF, bool isVarArg,
1325 const SmallVectorImpl<ISD::OutputArg> &Outs,
1326 LLVMContext &Context) const {
1327 SmallVector<CCValAssign, 16> RVLocs;
1328 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1330 return CCInfo.CheckReturn(Outs, RetCC_X86);
1334 X86TargetLowering::LowerReturn(SDValue Chain,
1335 CallingConv::ID CallConv, bool isVarArg,
1336 const SmallVectorImpl<ISD::OutputArg> &Outs,
1337 const SmallVectorImpl<SDValue> &OutVals,
1338 DebugLoc dl, SelectionDAG &DAG) const {
1339 MachineFunction &MF = DAG.getMachineFunction();
1340 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1342 SmallVector<CCValAssign, 16> RVLocs;
1343 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1344 RVLocs, *DAG.getContext());
1345 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1347 // Add the regs to the liveout set for the function.
1348 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1349 for (unsigned i = 0; i != RVLocs.size(); ++i)
1350 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1351 MRI.addLiveOut(RVLocs[i].getLocReg());
1355 SmallVector<SDValue, 6> RetOps;
1356 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1357 // Operand #1 = Bytes To Pop
1358 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1361 // Copy the result values into the output registers.
1362 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1363 CCValAssign &VA = RVLocs[i];
1364 assert(VA.isRegLoc() && "Can only return in registers!");
1365 SDValue ValToCopy = OutVals[i];
1366 EVT ValVT = ValToCopy.getValueType();
1368 // If this is x86-64, and we disabled SSE, we can't return FP values,
1369 // or SSE or MMX vectors.
1370 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1371 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1372 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1373 report_fatal_error("SSE register return with SSE disabled");
1375 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1376 // llvm-gcc has never done it right and no one has noticed, so this
1377 // should be OK for now.
1378 if (ValVT == MVT::f64 &&
1379 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1380 report_fatal_error("SSE2 register return with SSE2 disabled");
1382 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1383 // the RET instruction and handled by the FP Stackifier.
1384 if (VA.getLocReg() == X86::ST0 ||
1385 VA.getLocReg() == X86::ST1) {
1386 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1387 // change the value to the FP stack register class.
1388 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1389 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1390 RetOps.push_back(ValToCopy);
1391 // Don't emit a copytoreg.
1395 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1396 // which is returned in RAX / RDX.
1397 if (Subtarget->is64Bit()) {
1398 if (ValVT == MVT::x86mmx) {
1399 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1400 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1401 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1403 // If we don't have SSE2 available, convert to v4f32 so the generated
1404 // register is legal.
1405 if (!Subtarget->hasSSE2())
1406 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1411 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1412 Flag = Chain.getValue(1);
1415 // The x86-64 ABI for returning structs by value requires that we copy
1416 // the sret argument into %rax for the return. We saved the argument into
1417 // a virtual register in the entry block, so now we copy the value out
1419 if (Subtarget->is64Bit() &&
1420 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1421 MachineFunction &MF = DAG.getMachineFunction();
1422 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1423 unsigned Reg = FuncInfo->getSRetReturnReg();
1425 "SRetReturnReg should have been set in LowerFormalArguments().");
1426 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1428 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1429 Flag = Chain.getValue(1);
1431 // RAX now acts like a return value.
1432 MRI.addLiveOut(X86::RAX);
1435 RetOps[0] = Chain; // Update chain.
1437 // Add the flag if we have it.
1439 RetOps.push_back(Flag);
1441 return DAG.getNode(X86ISD::RET_FLAG, dl,
1442 MVT::Other, &RetOps[0], RetOps.size());
1445 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1446 if (N->getNumValues() != 1)
1448 if (!N->hasNUsesOfValue(1, 0))
1451 SDNode *Copy = *N->use_begin();
1452 if (Copy->getOpcode() != ISD::CopyToReg &&
1453 Copy->getOpcode() != ISD::FP_EXTEND)
1456 bool HasRet = false;
1457 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1459 if (UI->getOpcode() != X86ISD::RET_FLAG)
1468 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1469 ISD::NodeType ExtendKind) const {
1471 // TODO: Is this also valid on 32-bit?
1472 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1473 ReturnMVT = MVT::i8;
1475 ReturnMVT = MVT::i32;
1477 EVT MinVT = getRegisterType(Context, ReturnMVT);
1478 return VT.bitsLT(MinVT) ? MinVT : VT;
1481 /// LowerCallResult - Lower the result values of a call into the
1482 /// appropriate copies out of appropriate physical registers.
1485 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1486 CallingConv::ID CallConv, bool isVarArg,
1487 const SmallVectorImpl<ISD::InputArg> &Ins,
1488 DebugLoc dl, SelectionDAG &DAG,
1489 SmallVectorImpl<SDValue> &InVals) const {
1491 // Assign locations to each value returned by this call.
1492 SmallVector<CCValAssign, 16> RVLocs;
1493 bool Is64Bit = Subtarget->is64Bit();
1494 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1495 getTargetMachine(), RVLocs, *DAG.getContext());
1496 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1498 // Copy all of the result registers out of their specified physreg.
1499 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1500 CCValAssign &VA = RVLocs[i];
1501 EVT CopyVT = VA.getValVT();
1503 // If this is x86-64, and we disabled SSE, we can't return FP values
1504 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1505 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1506 report_fatal_error("SSE register return with SSE disabled");
1511 // If this is a call to a function that returns an fp value on the floating
1512 // point stack, we must guarantee the the value is popped from the stack, so
1513 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1514 // if the return value is not used. We use the FpPOP_RETVAL instruction
1516 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1517 // If we prefer to use the value in xmm registers, copy it out as f80 and
1518 // use a truncate to move it from fp stack reg to xmm reg.
1519 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1520 SDValue Ops[] = { Chain, InFlag };
1521 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1522 MVT::Other, MVT::Glue, Ops, 2), 1);
1523 Val = Chain.getValue(0);
1525 // Round the f80 to the right size, which also moves it to the appropriate
1527 if (CopyVT != VA.getValVT())
1528 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1529 // This truncation won't change the value.
1530 DAG.getIntPtrConstant(1));
1532 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1533 CopyVT, InFlag).getValue(1);
1534 Val = Chain.getValue(0);
1536 InFlag = Chain.getValue(2);
1537 InVals.push_back(Val);
1544 //===----------------------------------------------------------------------===//
1545 // C & StdCall & Fast Calling Convention implementation
1546 //===----------------------------------------------------------------------===//
1547 // StdCall calling convention seems to be standard for many Windows' API
1548 // routines and around. It differs from C calling convention just a little:
1549 // callee should clean up the stack, not caller. Symbols should be also
1550 // decorated in some fancy way :) It doesn't support any vector arguments.
1551 // For info on fast calling convention see Fast Calling Convention (tail call)
1552 // implementation LowerX86_32FastCCCallTo.
1554 /// CallIsStructReturn - Determines whether a call uses struct return
1556 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1560 return Outs[0].Flags.isSRet();
1563 /// ArgsAreStructReturn - Determines whether a function uses struct
1564 /// return semantics.
1566 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1570 return Ins[0].Flags.isSRet();
1573 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1574 /// by "Src" to address "Dst" with size and alignment information specified by
1575 /// the specific parameter attribute. The copy will be passed as a byval
1576 /// function parameter.
1578 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1579 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1581 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1583 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1584 /*isVolatile*/false, /*AlwaysInline=*/true,
1585 MachinePointerInfo(), MachinePointerInfo());
1588 /// IsTailCallConvention - Return true if the calling convention is one that
1589 /// supports tail call optimization.
1590 static bool IsTailCallConvention(CallingConv::ID CC) {
1591 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1594 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1595 if (!CI->isTailCall())
1599 CallingConv::ID CalleeCC = CS.getCallingConv();
1600 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1606 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1607 /// a tailcall target by changing its ABI.
1608 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1609 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1613 X86TargetLowering::LowerMemArgument(SDValue Chain,
1614 CallingConv::ID CallConv,
1615 const SmallVectorImpl<ISD::InputArg> &Ins,
1616 DebugLoc dl, SelectionDAG &DAG,
1617 const CCValAssign &VA,
1618 MachineFrameInfo *MFI,
1620 // Create the nodes corresponding to a load from this parameter slot.
1621 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1622 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1623 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1626 // If value is passed by pointer we have address passed instead of the value
1628 if (VA.getLocInfo() == CCValAssign::Indirect)
1629 ValVT = VA.getLocVT();
1631 ValVT = VA.getValVT();
1633 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1634 // changed with more analysis.
1635 // In case of tail call optimization mark all arguments mutable. Since they
1636 // could be overwritten by lowering of arguments in case of a tail call.
1637 if (Flags.isByVal()) {
1638 unsigned Bytes = Flags.getByValSize();
1639 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1640 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1641 return DAG.getFrameIndex(FI, getPointerTy());
1643 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1644 VA.getLocMemOffset(), isImmutable);
1645 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1646 return DAG.getLoad(ValVT, dl, Chain, FIN,
1647 MachinePointerInfo::getFixedStack(FI),
1653 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1654 CallingConv::ID CallConv,
1656 const SmallVectorImpl<ISD::InputArg> &Ins,
1659 SmallVectorImpl<SDValue> &InVals)
1661 MachineFunction &MF = DAG.getMachineFunction();
1662 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1664 const Function* Fn = MF.getFunction();
1665 if (Fn->hasExternalLinkage() &&
1666 Subtarget->isTargetCygMing() &&
1667 Fn->getName() == "main")
1668 FuncInfo->setForceFramePointer(true);
1670 MachineFrameInfo *MFI = MF.getFrameInfo();
1671 bool Is64Bit = Subtarget->is64Bit();
1672 bool IsWin64 = Subtarget->isTargetWin64();
1674 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1675 "Var args not supported with calling convention fastcc or ghc");
1677 // Assign locations to all of the incoming arguments.
1678 SmallVector<CCValAssign, 16> ArgLocs;
1679 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1680 ArgLocs, *DAG.getContext());
1682 // Allocate shadow area for Win64
1684 CCInfo.AllocateStack(32, 8);
1687 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1689 unsigned LastVal = ~0U;
1691 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1692 CCValAssign &VA = ArgLocs[i];
1693 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1695 assert(VA.getValNo() != LastVal &&
1696 "Don't support value assigned to multiple locs yet");
1697 LastVal = VA.getValNo();
1699 if (VA.isRegLoc()) {
1700 EVT RegVT = VA.getLocVT();
1701 TargetRegisterClass *RC = NULL;
1702 if (RegVT == MVT::i32)
1703 RC = X86::GR32RegisterClass;
1704 else if (Is64Bit && RegVT == MVT::i64)
1705 RC = X86::GR64RegisterClass;
1706 else if (RegVT == MVT::f32)
1707 RC = X86::FR32RegisterClass;
1708 else if (RegVT == MVT::f64)
1709 RC = X86::FR64RegisterClass;
1710 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1711 RC = X86::VR256RegisterClass;
1712 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1713 RC = X86::VR128RegisterClass;
1714 else if (RegVT == MVT::x86mmx)
1715 RC = X86::VR64RegisterClass;
1717 llvm_unreachable("Unknown argument type!");
1719 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1720 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1722 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1723 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1725 if (VA.getLocInfo() == CCValAssign::SExt)
1726 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1727 DAG.getValueType(VA.getValVT()));
1728 else if (VA.getLocInfo() == CCValAssign::ZExt)
1729 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1730 DAG.getValueType(VA.getValVT()));
1731 else if (VA.getLocInfo() == CCValAssign::BCvt)
1732 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1734 if (VA.isExtInLoc()) {
1735 // Handle MMX values passed in XMM regs.
1736 if (RegVT.isVector()) {
1737 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1740 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1743 assert(VA.isMemLoc());
1744 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1747 // If value is passed via pointer - do a load.
1748 if (VA.getLocInfo() == CCValAssign::Indirect)
1749 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1750 MachinePointerInfo(), false, false, 0);
1752 InVals.push_back(ArgValue);
1755 // The x86-64 ABI for returning structs by value requires that we copy
1756 // the sret argument into %rax for the return. Save the argument into
1757 // a virtual register so that we can access it from the return points.
1758 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1759 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1760 unsigned Reg = FuncInfo->getSRetReturnReg();
1762 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1763 FuncInfo->setSRetReturnReg(Reg);
1765 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1766 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1769 unsigned StackSize = CCInfo.getNextStackOffset();
1770 // Align stack specially for tail calls.
1771 if (FuncIsMadeTailCallSafe(CallConv))
1772 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1774 // If the function takes variable number of arguments, make a frame index for
1775 // the start of the first vararg value... for expansion of llvm.va_start.
1777 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1778 CallConv != CallingConv::X86_ThisCall)) {
1779 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1782 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1784 // FIXME: We should really autogenerate these arrays
1785 static const unsigned GPR64ArgRegsWin64[] = {
1786 X86::RCX, X86::RDX, X86::R8, X86::R9
1788 static const unsigned GPR64ArgRegs64Bit[] = {
1789 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1791 static const unsigned XMMArgRegs64Bit[] = {
1792 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1793 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1795 const unsigned *GPR64ArgRegs;
1796 unsigned NumXMMRegs = 0;
1799 // The XMM registers which might contain var arg parameters are shadowed
1800 // in their paired GPR. So we only need to save the GPR to their home
1802 TotalNumIntRegs = 4;
1803 GPR64ArgRegs = GPR64ArgRegsWin64;
1805 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1806 GPR64ArgRegs = GPR64ArgRegs64Bit;
1808 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1810 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1813 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1814 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1815 "SSE register cannot be used when SSE is disabled!");
1816 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1817 "SSE register cannot be used when SSE is disabled!");
1818 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1819 // Kernel mode asks for SSE to be disabled, so don't push them
1821 TotalNumXMMRegs = 0;
1824 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1825 // Get to the caller-allocated home save location. Add 8 to account
1826 // for the return address.
1827 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1828 FuncInfo->setRegSaveFrameIndex(
1829 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1830 // Fixup to set vararg frame on shadow area (4 x i64).
1832 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1834 // For X86-64, if there are vararg parameters that are passed via
1835 // registers, then we must store them to their spots on the stack so they
1836 // may be loaded by deferencing the result of va_next.
1837 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1838 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1839 FuncInfo->setRegSaveFrameIndex(
1840 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1844 // Store the integer parameter registers.
1845 SmallVector<SDValue, 8> MemOps;
1846 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1848 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1849 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1850 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1851 DAG.getIntPtrConstant(Offset));
1852 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1853 X86::GR64RegisterClass);
1854 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1856 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1857 MachinePointerInfo::getFixedStack(
1858 FuncInfo->getRegSaveFrameIndex(), Offset),
1860 MemOps.push_back(Store);
1864 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1865 // Now store the XMM (fp + vector) parameter registers.
1866 SmallVector<SDValue, 11> SaveXMMOps;
1867 SaveXMMOps.push_back(Chain);
1869 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1870 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1871 SaveXMMOps.push_back(ALVal);
1873 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1874 FuncInfo->getRegSaveFrameIndex()));
1875 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1876 FuncInfo->getVarArgsFPOffset()));
1878 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1879 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1880 X86::VR128RegisterClass);
1881 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1882 SaveXMMOps.push_back(Val);
1884 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1886 &SaveXMMOps[0], SaveXMMOps.size()));
1889 if (!MemOps.empty())
1890 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1891 &MemOps[0], MemOps.size());
1895 // Some CCs need callee pop.
1896 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1897 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1899 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1900 // If this is an sret function, the return should pop the hidden pointer.
1901 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1902 FuncInfo->setBytesToPopOnReturn(4);
1906 // RegSaveFrameIndex is X86-64 only.
1907 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1908 if (CallConv == CallingConv::X86_FastCall ||
1909 CallConv == CallingConv::X86_ThisCall)
1910 // fastcc functions can't have varargs.
1911 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1918 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1919 SDValue StackPtr, SDValue Arg,
1920 DebugLoc dl, SelectionDAG &DAG,
1921 const CCValAssign &VA,
1922 ISD::ArgFlagsTy Flags) const {
1923 unsigned LocMemOffset = VA.getLocMemOffset();
1924 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1925 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1926 if (Flags.isByVal())
1927 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1929 return DAG.getStore(Chain, dl, Arg, PtrOff,
1930 MachinePointerInfo::getStack(LocMemOffset),
1934 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1935 /// optimization is performed and it is required.
1937 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1938 SDValue &OutRetAddr, SDValue Chain,
1939 bool IsTailCall, bool Is64Bit,
1940 int FPDiff, DebugLoc dl) const {
1941 // Adjust the Return address stack slot.
1942 EVT VT = getPointerTy();
1943 OutRetAddr = getReturnAddressFrameIndex(DAG);
1945 // Load the "old" Return address.
1946 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1948 return SDValue(OutRetAddr.getNode(), 1);
1951 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1952 /// optimization is performed and it is required (FPDiff!=0).
1954 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1955 SDValue Chain, SDValue RetAddrFrIdx,
1956 bool Is64Bit, int FPDiff, DebugLoc dl) {
1957 // Store the return address to the appropriate stack slot.
1958 if (!FPDiff) return Chain;
1959 // Calculate the new stack slot for the return address.
1960 int SlotSize = Is64Bit ? 8 : 4;
1961 int NewReturnAddrFI =
1962 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1963 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1964 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1965 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1966 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1972 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1973 CallingConv::ID CallConv, bool isVarArg,
1975 const SmallVectorImpl<ISD::OutputArg> &Outs,
1976 const SmallVectorImpl<SDValue> &OutVals,
1977 const SmallVectorImpl<ISD::InputArg> &Ins,
1978 DebugLoc dl, SelectionDAG &DAG,
1979 SmallVectorImpl<SDValue> &InVals) const {
1980 MachineFunction &MF = DAG.getMachineFunction();
1981 bool Is64Bit = Subtarget->is64Bit();
1982 bool IsWin64 = Subtarget->isTargetWin64();
1983 bool IsStructRet = CallIsStructReturn(Outs);
1984 bool IsSibcall = false;
1987 // Check if it's really possible to do a tail call.
1988 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1989 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1990 Outs, OutVals, Ins, DAG);
1992 // Sibcalls are automatically detected tailcalls which do not require
1994 if (!GuaranteedTailCallOpt && isTailCall)
2001 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2002 "Var args not supported with calling convention fastcc or ghc");
2004 // Analyze operands of the call, assigning locations to each operand.
2005 SmallVector<CCValAssign, 16> ArgLocs;
2006 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2007 ArgLocs, *DAG.getContext());
2009 // Allocate shadow area for Win64
2011 CCInfo.AllocateStack(32, 8);
2014 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2016 // Get a count of how many bytes are to be pushed on the stack.
2017 unsigned NumBytes = CCInfo.getNextStackOffset();
2019 // This is a sibcall. The memory operands are available in caller's
2020 // own caller's stack.
2022 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2023 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2026 if (isTailCall && !IsSibcall) {
2027 // Lower arguments at fp - stackoffset + fpdiff.
2028 unsigned NumBytesCallerPushed =
2029 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2030 FPDiff = NumBytesCallerPushed - NumBytes;
2032 // Set the delta of movement of the returnaddr stackslot.
2033 // But only set if delta is greater than previous delta.
2034 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2035 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2039 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2041 SDValue RetAddrFrIdx;
2042 // Load return address for tail calls.
2043 if (isTailCall && FPDiff)
2044 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2045 Is64Bit, FPDiff, dl);
2047 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2048 SmallVector<SDValue, 8> MemOpChains;
2051 // Walk the register/memloc assignments, inserting copies/loads. In the case
2052 // of tail call optimization arguments are handle later.
2053 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2054 CCValAssign &VA = ArgLocs[i];
2055 EVT RegVT = VA.getLocVT();
2056 SDValue Arg = OutVals[i];
2057 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2058 bool isByVal = Flags.isByVal();
2060 // Promote the value if needed.
2061 switch (VA.getLocInfo()) {
2062 default: llvm_unreachable("Unknown loc info!");
2063 case CCValAssign::Full: break;
2064 case CCValAssign::SExt:
2065 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2067 case CCValAssign::ZExt:
2068 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2070 case CCValAssign::AExt:
2071 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2072 // Special case: passing MMX values in XMM registers.
2073 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2074 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2075 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2077 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2079 case CCValAssign::BCvt:
2080 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2082 case CCValAssign::Indirect: {
2083 // Store the argument.
2084 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2085 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2086 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2087 MachinePointerInfo::getFixedStack(FI),
2094 if (VA.isRegLoc()) {
2095 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2096 if (isVarArg && IsWin64) {
2097 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2098 // shadow reg if callee is a varargs function.
2099 unsigned ShadowReg = 0;
2100 switch (VA.getLocReg()) {
2101 case X86::XMM0: ShadowReg = X86::RCX; break;
2102 case X86::XMM1: ShadowReg = X86::RDX; break;
2103 case X86::XMM2: ShadowReg = X86::R8; break;
2104 case X86::XMM3: ShadowReg = X86::R9; break;
2107 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2109 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2110 assert(VA.isMemLoc());
2111 if (StackPtr.getNode() == 0)
2112 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2113 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2114 dl, DAG, VA, Flags));
2118 if (!MemOpChains.empty())
2119 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2120 &MemOpChains[0], MemOpChains.size());
2122 // Build a sequence of copy-to-reg nodes chained together with token chain
2123 // and flag operands which copy the outgoing args into registers.
2125 // Tail call byval lowering might overwrite argument registers so in case of
2126 // tail call optimization the copies to registers are lowered later.
2128 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2129 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2130 RegsToPass[i].second, InFlag);
2131 InFlag = Chain.getValue(1);
2134 if (Subtarget->isPICStyleGOT()) {
2135 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2138 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2139 DAG.getNode(X86ISD::GlobalBaseReg,
2140 DebugLoc(), getPointerTy()),
2142 InFlag = Chain.getValue(1);
2144 // If we are tail calling and generating PIC/GOT style code load the
2145 // address of the callee into ECX. The value in ecx is used as target of
2146 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2147 // for tail calls on PIC/GOT architectures. Normally we would just put the
2148 // address of GOT into ebx and then call target@PLT. But for tail calls
2149 // ebx would be restored (since ebx is callee saved) before jumping to the
2152 // Note: The actual moving to ECX is done further down.
2153 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2154 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2155 !G->getGlobal()->hasProtectedVisibility())
2156 Callee = LowerGlobalAddress(Callee, DAG);
2157 else if (isa<ExternalSymbolSDNode>(Callee))
2158 Callee = LowerExternalSymbol(Callee, DAG);
2162 if (Is64Bit && isVarArg && !IsWin64) {
2163 // From AMD64 ABI document:
2164 // For calls that may call functions that use varargs or stdargs
2165 // (prototype-less calls or calls to functions containing ellipsis (...) in
2166 // the declaration) %al is used as hidden argument to specify the number
2167 // of SSE registers used. The contents of %al do not need to match exactly
2168 // the number of registers, but must be an ubound on the number of SSE
2169 // registers used and is in the range 0 - 8 inclusive.
2171 // Count the number of XMM registers allocated.
2172 static const unsigned XMMArgRegs[] = {
2173 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2174 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2176 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2177 assert((Subtarget->hasXMM() || !NumXMMRegs)
2178 && "SSE registers cannot be used when SSE is disabled");
2180 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2181 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2182 InFlag = Chain.getValue(1);
2186 // For tail calls lower the arguments to the 'real' stack slot.
2188 // Force all the incoming stack arguments to be loaded from the stack
2189 // before any new outgoing arguments are stored to the stack, because the
2190 // outgoing stack slots may alias the incoming argument stack slots, and
2191 // the alias isn't otherwise explicit. This is slightly more conservative
2192 // than necessary, because it means that each store effectively depends
2193 // on every argument instead of just those arguments it would clobber.
2194 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2196 SmallVector<SDValue, 8> MemOpChains2;
2199 // Do not flag preceding copytoreg stuff together with the following stuff.
2201 if (GuaranteedTailCallOpt) {
2202 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2203 CCValAssign &VA = ArgLocs[i];
2206 assert(VA.isMemLoc());
2207 SDValue Arg = OutVals[i];
2208 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2209 // Create frame index.
2210 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2211 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2212 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2213 FIN = DAG.getFrameIndex(FI, getPointerTy());
2215 if (Flags.isByVal()) {
2216 // Copy relative to framepointer.
2217 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2218 if (StackPtr.getNode() == 0)
2219 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2221 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2223 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2227 // Store relative to framepointer.
2228 MemOpChains2.push_back(
2229 DAG.getStore(ArgChain, dl, Arg, FIN,
2230 MachinePointerInfo::getFixedStack(FI),
2236 if (!MemOpChains2.empty())
2237 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2238 &MemOpChains2[0], MemOpChains2.size());
2240 // Copy arguments to their registers.
2241 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2242 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2243 RegsToPass[i].second, InFlag);
2244 InFlag = Chain.getValue(1);
2248 // Store the return address to the appropriate stack slot.
2249 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2253 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2254 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2255 // In the 64-bit large code model, we have to make all calls
2256 // through a register, since the call instruction's 32-bit
2257 // pc-relative offset may not be large enough to hold the whole
2259 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2260 // If the callee is a GlobalAddress node (quite common, every direct call
2261 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2264 // We should use extra load for direct calls to dllimported functions in
2266 const GlobalValue *GV = G->getGlobal();
2267 if (!GV->hasDLLImportLinkage()) {
2268 unsigned char OpFlags = 0;
2269 bool ExtraLoad = false;
2270 unsigned WrapperKind = ISD::DELETED_NODE;
2272 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2273 // external symbols most go through the PLT in PIC mode. If the symbol
2274 // has hidden or protected visibility, or if it is static or local, then
2275 // we don't need to use the PLT - we can directly call it.
2276 if (Subtarget->isTargetELF() &&
2277 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2278 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2279 OpFlags = X86II::MO_PLT;
2280 } else if (Subtarget->isPICStyleStubAny() &&
2281 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2282 (!Subtarget->getTargetTriple().isMacOSX() ||
2283 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2284 // PC-relative references to external symbols should go through $stub,
2285 // unless we're building with the leopard linker or later, which
2286 // automatically synthesizes these stubs.
2287 OpFlags = X86II::MO_DARWIN_STUB;
2288 } else if (Subtarget->isPICStyleRIPRel() &&
2289 isa<Function>(GV) &&
2290 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2291 // If the function is marked as non-lazy, generate an indirect call
2292 // which loads from the GOT directly. This avoids runtime overhead
2293 // at the cost of eager binding (and one extra byte of encoding).
2294 OpFlags = X86II::MO_GOTPCREL;
2295 WrapperKind = X86ISD::WrapperRIP;
2299 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2300 G->getOffset(), OpFlags);
2302 // Add a wrapper if needed.
2303 if (WrapperKind != ISD::DELETED_NODE)
2304 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2305 // Add extra indirection if needed.
2307 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2308 MachinePointerInfo::getGOT(),
2311 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2312 unsigned char OpFlags = 0;
2314 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2315 // external symbols should go through the PLT.
2316 if (Subtarget->isTargetELF() &&
2317 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2318 OpFlags = X86II::MO_PLT;
2319 } else if (Subtarget->isPICStyleStubAny() &&
2320 (!Subtarget->getTargetTriple().isMacOSX() ||
2321 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2322 // PC-relative references to external symbols should go through $stub,
2323 // unless we're building with the leopard linker or later, which
2324 // automatically synthesizes these stubs.
2325 OpFlags = X86II::MO_DARWIN_STUB;
2328 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2332 // Returns a chain & a flag for retval copy to use.
2333 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2334 SmallVector<SDValue, 8> Ops;
2336 if (!IsSibcall && isTailCall) {
2337 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2338 DAG.getIntPtrConstant(0, true), InFlag);
2339 InFlag = Chain.getValue(1);
2342 Ops.push_back(Chain);
2343 Ops.push_back(Callee);
2346 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2348 // Add argument registers to the end of the list so that they are known live
2350 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2351 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2352 RegsToPass[i].second.getValueType()));
2354 // Add an implicit use GOT pointer in EBX.
2355 if (!isTailCall && Subtarget->isPICStyleGOT())
2356 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2358 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2359 if (Is64Bit && isVarArg && !IsWin64)
2360 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2362 if (InFlag.getNode())
2363 Ops.push_back(InFlag);
2367 //// If this is the first return lowered for this function, add the regs
2368 //// to the liveout set for the function.
2369 // This isn't right, although it's probably harmless on x86; liveouts
2370 // should be computed from returns not tail calls. Consider a void
2371 // function making a tail call to a function returning int.
2372 return DAG.getNode(X86ISD::TC_RETURN, dl,
2373 NodeTys, &Ops[0], Ops.size());
2376 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2377 InFlag = Chain.getValue(1);
2379 // Create the CALLSEQ_END node.
2380 unsigned NumBytesForCalleeToPush;
2381 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2382 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2383 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2384 // If this is a call to a struct-return function, the callee
2385 // pops the hidden struct pointer, so we have to push it back.
2386 // This is common for Darwin/X86, Linux & Mingw32 targets.
2387 NumBytesForCalleeToPush = 4;
2389 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2391 // Returns a flag for retval copy to use.
2393 Chain = DAG.getCALLSEQ_END(Chain,
2394 DAG.getIntPtrConstant(NumBytes, true),
2395 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2398 InFlag = Chain.getValue(1);
2401 // Handle result values, copying them out of physregs into vregs that we
2403 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2404 Ins, dl, DAG, InVals);
2408 //===----------------------------------------------------------------------===//
2409 // Fast Calling Convention (tail call) implementation
2410 //===----------------------------------------------------------------------===//
2412 // Like std call, callee cleans arguments, convention except that ECX is
2413 // reserved for storing the tail called function address. Only 2 registers are
2414 // free for argument passing (inreg). Tail call optimization is performed
2416 // * tailcallopt is enabled
2417 // * caller/callee are fastcc
2418 // On X86_64 architecture with GOT-style position independent code only local
2419 // (within module) calls are supported at the moment.
2420 // To keep the stack aligned according to platform abi the function
2421 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2422 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2423 // If a tail called function callee has more arguments than the caller the
2424 // caller needs to make sure that there is room to move the RETADDR to. This is
2425 // achieved by reserving an area the size of the argument delta right after the
2426 // original REtADDR, but before the saved framepointer or the spilled registers
2427 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2439 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2440 /// for a 16 byte align requirement.
2442 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2443 SelectionDAG& DAG) const {
2444 MachineFunction &MF = DAG.getMachineFunction();
2445 const TargetMachine &TM = MF.getTarget();
2446 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2447 unsigned StackAlignment = TFI.getStackAlignment();
2448 uint64_t AlignMask = StackAlignment - 1;
2449 int64_t Offset = StackSize;
2450 uint64_t SlotSize = TD->getPointerSize();
2451 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2452 // Number smaller than 12 so just add the difference.
2453 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2455 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2456 Offset = ((~AlignMask) & Offset) + StackAlignment +
2457 (StackAlignment-SlotSize);
2462 /// MatchingStackOffset - Return true if the given stack call argument is
2463 /// already available in the same position (relatively) of the caller's
2464 /// incoming argument stack.
2466 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2467 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2468 const X86InstrInfo *TII) {
2469 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2471 if (Arg.getOpcode() == ISD::CopyFromReg) {
2472 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2473 if (!TargetRegisterInfo::isVirtualRegister(VR))
2475 MachineInstr *Def = MRI->getVRegDef(VR);
2478 if (!Flags.isByVal()) {
2479 if (!TII->isLoadFromStackSlot(Def, FI))
2482 unsigned Opcode = Def->getOpcode();
2483 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2484 Def->getOperand(1).isFI()) {
2485 FI = Def->getOperand(1).getIndex();
2486 Bytes = Flags.getByValSize();
2490 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2491 if (Flags.isByVal())
2492 // ByVal argument is passed in as a pointer but it's now being
2493 // dereferenced. e.g.
2494 // define @foo(%struct.X* %A) {
2495 // tail call @bar(%struct.X* byval %A)
2498 SDValue Ptr = Ld->getBasePtr();
2499 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2502 FI = FINode->getIndex();
2503 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2504 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2505 FI = FINode->getIndex();
2506 Bytes = Flags.getByValSize();
2510 assert(FI != INT_MAX);
2511 if (!MFI->isFixedObjectIndex(FI))
2513 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2516 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2517 /// for tail call optimization. Targets which want to do tail call
2518 /// optimization should implement this function.
2520 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2521 CallingConv::ID CalleeCC,
2523 bool isCalleeStructRet,
2524 bool isCallerStructRet,
2525 const SmallVectorImpl<ISD::OutputArg> &Outs,
2526 const SmallVectorImpl<SDValue> &OutVals,
2527 const SmallVectorImpl<ISD::InputArg> &Ins,
2528 SelectionDAG& DAG) const {
2529 if (!IsTailCallConvention(CalleeCC) &&
2530 CalleeCC != CallingConv::C)
2533 // If -tailcallopt is specified, make fastcc functions tail-callable.
2534 const MachineFunction &MF = DAG.getMachineFunction();
2535 const Function *CallerF = DAG.getMachineFunction().getFunction();
2536 CallingConv::ID CallerCC = CallerF->getCallingConv();
2537 bool CCMatch = CallerCC == CalleeCC;
2539 if (GuaranteedTailCallOpt) {
2540 if (IsTailCallConvention(CalleeCC) && CCMatch)
2545 // Look for obvious safe cases to perform tail call optimization that do not
2546 // require ABI changes. This is what gcc calls sibcall.
2548 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2549 // emit a special epilogue.
2550 if (RegInfo->needsStackRealignment(MF))
2553 // Also avoid sibcall optimization if either caller or callee uses struct
2554 // return semantics.
2555 if (isCalleeStructRet || isCallerStructRet)
2558 // An stdcall caller is expected to clean up its arguments; the callee
2559 // isn't going to do that.
2560 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2563 // Do not sibcall optimize vararg calls unless all arguments are passed via
2565 if (isVarArg && !Outs.empty()) {
2567 // Optimizing for varargs on Win64 is unlikely to be safe without
2568 // additional testing.
2569 if (Subtarget->isTargetWin64())
2572 SmallVector<CCValAssign, 16> ArgLocs;
2573 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2574 getTargetMachine(), ArgLocs, *DAG.getContext());
2576 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2577 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2578 if (!ArgLocs[i].isRegLoc())
2582 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2583 // Therefore if it's not used by the call it is not safe to optimize this into
2585 bool Unused = false;
2586 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2593 SmallVector<CCValAssign, 16> RVLocs;
2594 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2595 getTargetMachine(), RVLocs, *DAG.getContext());
2596 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2597 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2598 CCValAssign &VA = RVLocs[i];
2599 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2604 // If the calling conventions do not match, then we'd better make sure the
2605 // results are returned in the same way as what the caller expects.
2607 SmallVector<CCValAssign, 16> RVLocs1;
2608 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2609 getTargetMachine(), RVLocs1, *DAG.getContext());
2610 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2612 SmallVector<CCValAssign, 16> RVLocs2;
2613 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2614 getTargetMachine(), RVLocs2, *DAG.getContext());
2615 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2617 if (RVLocs1.size() != RVLocs2.size())
2619 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2620 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2622 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2624 if (RVLocs1[i].isRegLoc()) {
2625 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2628 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2634 // If the callee takes no arguments then go on to check the results of the
2636 if (!Outs.empty()) {
2637 // Check if stack adjustment is needed. For now, do not do this if any
2638 // argument is passed on the stack.
2639 SmallVector<CCValAssign, 16> ArgLocs;
2640 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2641 getTargetMachine(), ArgLocs, *DAG.getContext());
2643 // Allocate shadow area for Win64
2644 if (Subtarget->isTargetWin64()) {
2645 CCInfo.AllocateStack(32, 8);
2648 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2649 if (CCInfo.getNextStackOffset()) {
2650 MachineFunction &MF = DAG.getMachineFunction();
2651 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2654 // Check if the arguments are already laid out in the right way as
2655 // the caller's fixed stack objects.
2656 MachineFrameInfo *MFI = MF.getFrameInfo();
2657 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2658 const X86InstrInfo *TII =
2659 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2660 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2661 CCValAssign &VA = ArgLocs[i];
2662 SDValue Arg = OutVals[i];
2663 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2664 if (VA.getLocInfo() == CCValAssign::Indirect)
2666 if (!VA.isRegLoc()) {
2667 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2674 // If the tailcall address may be in a register, then make sure it's
2675 // possible to register allocate for it. In 32-bit, the call address can
2676 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2677 // callee-saved registers are restored. These happen to be the same
2678 // registers used to pass 'inreg' arguments so watch out for those.
2679 if (!Subtarget->is64Bit() &&
2680 !isa<GlobalAddressSDNode>(Callee) &&
2681 !isa<ExternalSymbolSDNode>(Callee)) {
2682 unsigned NumInRegs = 0;
2683 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2684 CCValAssign &VA = ArgLocs[i];
2687 unsigned Reg = VA.getLocReg();
2690 case X86::EAX: case X86::EDX: case X86::ECX:
2691 if (++NumInRegs == 3)
2703 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2704 return X86::createFastISel(funcInfo);
2708 //===----------------------------------------------------------------------===//
2709 // Other Lowering Hooks
2710 //===----------------------------------------------------------------------===//
2712 static bool MayFoldLoad(SDValue Op) {
2713 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2716 static bool MayFoldIntoStore(SDValue Op) {
2717 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2720 static bool isTargetShuffle(unsigned Opcode) {
2722 default: return false;
2723 case X86ISD::PSHUFD:
2724 case X86ISD::PSHUFHW:
2725 case X86ISD::PSHUFLW:
2726 case X86ISD::SHUFPD:
2727 case X86ISD::PALIGN:
2728 case X86ISD::SHUFPS:
2729 case X86ISD::MOVLHPS:
2730 case X86ISD::MOVLHPD:
2731 case X86ISD::MOVHLPS:
2732 case X86ISD::MOVLPS:
2733 case X86ISD::MOVLPD:
2734 case X86ISD::MOVSHDUP:
2735 case X86ISD::MOVSLDUP:
2736 case X86ISD::MOVDDUP:
2739 case X86ISD::UNPCKLPS:
2740 case X86ISD::UNPCKLPD:
2741 case X86ISD::VUNPCKLPS:
2742 case X86ISD::VUNPCKLPD:
2743 case X86ISD::VUNPCKLPSY:
2744 case X86ISD::VUNPCKLPDY:
2745 case X86ISD::PUNPCKLWD:
2746 case X86ISD::PUNPCKLBW:
2747 case X86ISD::PUNPCKLDQ:
2748 case X86ISD::PUNPCKLQDQ:
2749 case X86ISD::UNPCKHPS:
2750 case X86ISD::UNPCKHPD:
2751 case X86ISD::PUNPCKHWD:
2752 case X86ISD::PUNPCKHBW:
2753 case X86ISD::PUNPCKHDQ:
2754 case X86ISD::PUNPCKHQDQ:
2760 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2761 SDValue V1, SelectionDAG &DAG) {
2763 default: llvm_unreachable("Unknown x86 shuffle node");
2764 case X86ISD::MOVSHDUP:
2765 case X86ISD::MOVSLDUP:
2766 case X86ISD::MOVDDUP:
2767 return DAG.getNode(Opc, dl, VT, V1);
2773 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2774 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2776 default: llvm_unreachable("Unknown x86 shuffle node");
2777 case X86ISD::PSHUFD:
2778 case X86ISD::PSHUFHW:
2779 case X86ISD::PSHUFLW:
2780 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2786 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2787 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2789 default: llvm_unreachable("Unknown x86 shuffle node");
2790 case X86ISD::PALIGN:
2791 case X86ISD::SHUFPD:
2792 case X86ISD::SHUFPS:
2793 return DAG.getNode(Opc, dl, VT, V1, V2,
2794 DAG.getConstant(TargetMask, MVT::i8));
2799 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2800 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2802 default: llvm_unreachable("Unknown x86 shuffle node");
2803 case X86ISD::MOVLHPS:
2804 case X86ISD::MOVLHPD:
2805 case X86ISD::MOVHLPS:
2806 case X86ISD::MOVLPS:
2807 case X86ISD::MOVLPD:
2810 case X86ISD::UNPCKLPS:
2811 case X86ISD::UNPCKLPD:
2812 case X86ISD::VUNPCKLPS:
2813 case X86ISD::VUNPCKLPD:
2814 case X86ISD::VUNPCKLPSY:
2815 case X86ISD::VUNPCKLPDY:
2816 case X86ISD::PUNPCKLWD:
2817 case X86ISD::PUNPCKLBW:
2818 case X86ISD::PUNPCKLDQ:
2819 case X86ISD::PUNPCKLQDQ:
2820 case X86ISD::UNPCKHPS:
2821 case X86ISD::UNPCKHPD:
2822 case X86ISD::PUNPCKHWD:
2823 case X86ISD::PUNPCKHBW:
2824 case X86ISD::PUNPCKHDQ:
2825 case X86ISD::PUNPCKHQDQ:
2826 return DAG.getNode(Opc, dl, VT, V1, V2);
2831 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2832 MachineFunction &MF = DAG.getMachineFunction();
2833 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2834 int ReturnAddrIndex = FuncInfo->getRAIndex();
2836 if (ReturnAddrIndex == 0) {
2837 // Set up a frame object for the return address.
2838 uint64_t SlotSize = TD->getPointerSize();
2839 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2841 FuncInfo->setRAIndex(ReturnAddrIndex);
2844 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2848 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2849 bool hasSymbolicDisplacement) {
2850 // Offset should fit into 32 bit immediate field.
2851 if (!isInt<32>(Offset))
2854 // If we don't have a symbolic displacement - we don't have any extra
2856 if (!hasSymbolicDisplacement)
2859 // FIXME: Some tweaks might be needed for medium code model.
2860 if (M != CodeModel::Small && M != CodeModel::Kernel)
2863 // For small code model we assume that latest object is 16MB before end of 31
2864 // bits boundary. We may also accept pretty large negative constants knowing
2865 // that all objects are in the positive half of address space.
2866 if (M == CodeModel::Small && Offset < 16*1024*1024)
2869 // For kernel code model we know that all object resist in the negative half
2870 // of 32bits address space. We may not accept negative offsets, since they may
2871 // be just off and we may accept pretty large positive ones.
2872 if (M == CodeModel::Kernel && Offset > 0)
2878 /// isCalleePop - Determines whether the callee is required to pop its
2879 /// own arguments. Callee pop is necessary to support tail calls.
2880 bool X86::isCalleePop(CallingConv::ID CallingConv,
2881 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2885 switch (CallingConv) {
2888 case CallingConv::X86_StdCall:
2890 case CallingConv::X86_FastCall:
2892 case CallingConv::X86_ThisCall:
2894 case CallingConv::Fast:
2896 case CallingConv::GHC:
2901 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2902 /// specific condition code, returning the condition code and the LHS/RHS of the
2903 /// comparison to make.
2904 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2905 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2907 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2908 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2909 // X > -1 -> X == 0, jump !sign.
2910 RHS = DAG.getConstant(0, RHS.getValueType());
2911 return X86::COND_NS;
2912 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2913 // X < 0 -> X == 0, jump on sign.
2915 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2917 RHS = DAG.getConstant(0, RHS.getValueType());
2918 return X86::COND_LE;
2922 switch (SetCCOpcode) {
2923 default: llvm_unreachable("Invalid integer condition!");
2924 case ISD::SETEQ: return X86::COND_E;
2925 case ISD::SETGT: return X86::COND_G;
2926 case ISD::SETGE: return X86::COND_GE;
2927 case ISD::SETLT: return X86::COND_L;
2928 case ISD::SETLE: return X86::COND_LE;
2929 case ISD::SETNE: return X86::COND_NE;
2930 case ISD::SETULT: return X86::COND_B;
2931 case ISD::SETUGT: return X86::COND_A;
2932 case ISD::SETULE: return X86::COND_BE;
2933 case ISD::SETUGE: return X86::COND_AE;
2937 // First determine if it is required or is profitable to flip the operands.
2939 // If LHS is a foldable load, but RHS is not, flip the condition.
2940 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2941 !ISD::isNON_EXTLoad(RHS.getNode())) {
2942 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2943 std::swap(LHS, RHS);
2946 switch (SetCCOpcode) {
2952 std::swap(LHS, RHS);
2956 // On a floating point condition, the flags are set as follows:
2958 // 0 | 0 | 0 | X > Y
2959 // 0 | 0 | 1 | X < Y
2960 // 1 | 0 | 0 | X == Y
2961 // 1 | 1 | 1 | unordered
2962 switch (SetCCOpcode) {
2963 default: llvm_unreachable("Condcode should be pre-legalized away");
2965 case ISD::SETEQ: return X86::COND_E;
2966 case ISD::SETOLT: // flipped
2968 case ISD::SETGT: return X86::COND_A;
2969 case ISD::SETOLE: // flipped
2971 case ISD::SETGE: return X86::COND_AE;
2972 case ISD::SETUGT: // flipped
2974 case ISD::SETLT: return X86::COND_B;
2975 case ISD::SETUGE: // flipped
2977 case ISD::SETLE: return X86::COND_BE;
2979 case ISD::SETNE: return X86::COND_NE;
2980 case ISD::SETUO: return X86::COND_P;
2981 case ISD::SETO: return X86::COND_NP;
2983 case ISD::SETUNE: return X86::COND_INVALID;
2987 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2988 /// code. Current x86 isa includes the following FP cmov instructions:
2989 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2990 static bool hasFPCMov(unsigned X86CC) {
3006 /// isFPImmLegal - Returns true if the target can instruction select the
3007 /// specified FP immediate natively. If false, the legalizer will
3008 /// materialize the FP immediate as a load from a constant pool.
3009 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3010 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3011 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3017 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3018 /// the specified range (L, H].
3019 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3020 return (Val < 0) || (Val >= Low && Val < Hi);
3023 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3024 /// specified value.
3025 static bool isUndefOrEqual(int Val, int CmpVal) {
3026 if (Val < 0 || Val == CmpVal)
3031 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3032 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3033 /// the second operand.
3034 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3035 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3036 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3037 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3038 return (Mask[0] < 2 && Mask[1] < 2);
3042 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3043 SmallVector<int, 8> M;
3045 return ::isPSHUFDMask(M, N->getValueType(0));
3048 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3049 /// is suitable for input to PSHUFHW.
3050 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3051 if (VT != MVT::v8i16)
3054 // Lower quadword copied in order or undef.
3055 for (int i = 0; i != 4; ++i)
3056 if (Mask[i] >= 0 && Mask[i] != i)
3059 // Upper quadword shuffled.
3060 for (int i = 4; i != 8; ++i)
3061 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3067 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3068 SmallVector<int, 8> M;
3070 return ::isPSHUFHWMask(M, N->getValueType(0));
3073 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3074 /// is suitable for input to PSHUFLW.
3075 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3076 if (VT != MVT::v8i16)
3079 // Upper quadword copied in order.
3080 for (int i = 4; i != 8; ++i)
3081 if (Mask[i] >= 0 && Mask[i] != i)
3084 // Lower quadword shuffled.
3085 for (int i = 0; i != 4; ++i)
3092 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3093 SmallVector<int, 8> M;
3095 return ::isPSHUFLWMask(M, N->getValueType(0));
3098 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3099 /// is suitable for input to PALIGNR.
3100 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3102 int i, e = VT.getVectorNumElements();
3104 // Do not handle v2i64 / v2f64 shuffles with palignr.
3105 if (e < 4 || !hasSSSE3)
3108 for (i = 0; i != e; ++i)
3112 // All undef, not a palignr.
3116 // Determine if it's ok to perform a palignr with only the LHS, since we
3117 // don't have access to the actual shuffle elements to see if RHS is undef.
3118 bool Unary = Mask[i] < (int)e;
3119 bool NeedsUnary = false;
3121 int s = Mask[i] - i;
3123 // Check the rest of the elements to see if they are consecutive.
3124 for (++i; i != e; ++i) {
3129 Unary = Unary && (m < (int)e);
3130 NeedsUnary = NeedsUnary || (m < s);
3132 if (NeedsUnary && !Unary)
3134 if (Unary && m != ((s+i) & (e-1)))
3136 if (!Unary && m != (s+i))
3142 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3143 SmallVector<int, 8> M;
3145 return ::isPALIGNRMask(M, N->getValueType(0), true);
3148 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3149 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3150 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3151 int NumElems = VT.getVectorNumElements();
3152 if (NumElems != 2 && NumElems != 4)
3155 int Half = NumElems / 2;
3156 for (int i = 0; i < Half; ++i)
3157 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3159 for (int i = Half; i < NumElems; ++i)
3160 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3166 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3167 SmallVector<int, 8> M;
3169 return ::isSHUFPMask(M, N->getValueType(0));
3172 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3173 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3174 /// half elements to come from vector 1 (which would equal the dest.) and
3175 /// the upper half to come from vector 2.
3176 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3177 int NumElems = VT.getVectorNumElements();
3179 if (NumElems != 2 && NumElems != 4)
3182 int Half = NumElems / 2;
3183 for (int i = 0; i < Half; ++i)
3184 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3186 for (int i = Half; i < NumElems; ++i)
3187 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3192 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3193 SmallVector<int, 8> M;
3195 return isCommutedSHUFPMask(M, N->getValueType(0));
3198 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3199 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3200 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3201 if (N->getValueType(0).getVectorNumElements() != 4)
3204 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3205 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3206 isUndefOrEqual(N->getMaskElt(1), 7) &&
3207 isUndefOrEqual(N->getMaskElt(2), 2) &&
3208 isUndefOrEqual(N->getMaskElt(3), 3);
3211 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3212 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3214 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3215 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3220 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3221 isUndefOrEqual(N->getMaskElt(1), 3) &&
3222 isUndefOrEqual(N->getMaskElt(2), 2) &&
3223 isUndefOrEqual(N->getMaskElt(3), 3);
3226 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3227 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3228 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3229 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3231 if (NumElems != 2 && NumElems != 4)
3234 for (unsigned i = 0; i < NumElems/2; ++i)
3235 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3238 for (unsigned i = NumElems/2; i < NumElems; ++i)
3239 if (!isUndefOrEqual(N->getMaskElt(i), i))
3245 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3246 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3247 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3248 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3250 if ((NumElems != 2 && NumElems != 4)
3251 || N->getValueType(0).getSizeInBits() > 128)
3254 for (unsigned i = 0; i < NumElems/2; ++i)
3255 if (!isUndefOrEqual(N->getMaskElt(i), i))
3258 for (unsigned i = 0; i < NumElems/2; ++i)
3259 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3265 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3266 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3267 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3268 bool V2IsSplat = false) {
3269 int NumElts = VT.getVectorNumElements();
3270 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3273 // Handle vector lengths > 128 bits. Define a "section" as a set of
3274 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3276 unsigned NumSections = VT.getSizeInBits() / 128;
3277 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3278 unsigned NumSectionElts = NumElts / NumSections;
3281 unsigned End = NumSectionElts;
3282 for (unsigned s = 0; s < NumSections; ++s) {
3283 for (unsigned i = Start, j = s * NumSectionElts;
3287 int BitI1 = Mask[i+1];
3288 if (!isUndefOrEqual(BitI, j))
3291 if (!isUndefOrEqual(BitI1, NumElts))
3294 if (!isUndefOrEqual(BitI1, j + NumElts))
3298 // Process the next 128 bits.
3299 Start += NumSectionElts;
3300 End += NumSectionElts;
3306 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3307 SmallVector<int, 8> M;
3309 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3312 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3313 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3314 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3315 bool V2IsSplat = false) {
3316 int NumElts = VT.getVectorNumElements();
3317 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3320 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3322 int BitI1 = Mask[i+1];
3323 if (!isUndefOrEqual(BitI, j + NumElts/2))
3326 if (isUndefOrEqual(BitI1, NumElts))
3329 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3336 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3337 SmallVector<int, 8> M;
3339 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3342 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3343 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3345 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3346 int NumElems = VT.getVectorNumElements();
3347 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3350 // Handle vector lengths > 128 bits. Define a "section" as a set of
3351 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3353 unsigned NumSections = VT.getSizeInBits() / 128;
3354 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3355 unsigned NumSectionElts = NumElems / NumSections;
3357 for (unsigned s = 0; s < NumSections; ++s) {
3358 for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3359 i != NumSectionElts * (s + 1);
3362 int BitI1 = Mask[i+1];
3364 if (!isUndefOrEqual(BitI, j))
3366 if (!isUndefOrEqual(BitI1, j))
3374 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3375 SmallVector<int, 8> M;
3377 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3380 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3381 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3383 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3384 int NumElems = VT.getVectorNumElements();
3385 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3388 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3390 int BitI1 = Mask[i+1];
3391 if (!isUndefOrEqual(BitI, j))
3393 if (!isUndefOrEqual(BitI1, j))
3399 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3400 SmallVector<int, 8> M;
3402 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3405 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3406 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3407 /// MOVSD, and MOVD, i.e. setting the lowest element.
3408 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3409 if (VT.getVectorElementType().getSizeInBits() < 32)
3412 int NumElts = VT.getVectorNumElements();
3414 if (!isUndefOrEqual(Mask[0], NumElts))
3417 for (int i = 1; i < NumElts; ++i)
3418 if (!isUndefOrEqual(Mask[i], i))
3424 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3425 SmallVector<int, 8> M;
3427 return ::isMOVLMask(M, N->getValueType(0));
3430 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3431 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3432 /// element of vector 2 and the other elements to come from vector 1 in order.
3433 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3434 bool V2IsSplat = false, bool V2IsUndef = false) {
3435 int NumOps = VT.getVectorNumElements();
3436 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3439 if (!isUndefOrEqual(Mask[0], 0))
3442 for (int i = 1; i < NumOps; ++i)
3443 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3444 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3445 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3451 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3452 bool V2IsUndef = false) {
3453 SmallVector<int, 8> M;
3455 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3458 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3459 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3460 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3461 if (N->getValueType(0).getVectorNumElements() != 4)
3464 // Expect 1, 1, 3, 3
3465 for (unsigned i = 0; i < 2; ++i) {
3466 int Elt = N->getMaskElt(i);
3467 if (Elt >= 0 && Elt != 1)
3472 for (unsigned i = 2; i < 4; ++i) {
3473 int Elt = N->getMaskElt(i);
3474 if (Elt >= 0 && Elt != 3)
3479 // Don't use movshdup if it can be done with a shufps.
3480 // FIXME: verify that matching u, u, 3, 3 is what we want.
3484 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3485 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3486 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3487 if (N->getValueType(0).getVectorNumElements() != 4)
3490 // Expect 0, 0, 2, 2
3491 for (unsigned i = 0; i < 2; ++i)
3492 if (N->getMaskElt(i) > 0)
3496 for (unsigned i = 2; i < 4; ++i) {
3497 int Elt = N->getMaskElt(i);
3498 if (Elt >= 0 && Elt != 2)
3503 // Don't use movsldup if it can be done with a shufps.
3507 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3508 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3509 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3510 int e = N->getValueType(0).getVectorNumElements() / 2;
3512 for (int i = 0; i < e; ++i)
3513 if (!isUndefOrEqual(N->getMaskElt(i), i))
3515 for (int i = 0; i < e; ++i)
3516 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3521 /// isVEXTRACTF128Index - Return true if the specified
3522 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3523 /// suitable for input to VEXTRACTF128.
3524 bool X86::isVEXTRACTF128Index(SDNode *N) {
3525 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3528 // The index should be aligned on a 128-bit boundary.
3530 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3532 unsigned VL = N->getValueType(0).getVectorNumElements();
3533 unsigned VBits = N->getValueType(0).getSizeInBits();
3534 unsigned ElSize = VBits / VL;
3535 bool Result = (Index * ElSize) % 128 == 0;
3540 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3541 /// operand specifies a subvector insert that is suitable for input to
3543 bool X86::isVINSERTF128Index(SDNode *N) {
3544 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3547 // The index should be aligned on a 128-bit boundary.
3549 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3551 unsigned VL = N->getValueType(0).getVectorNumElements();
3552 unsigned VBits = N->getValueType(0).getSizeInBits();
3553 unsigned ElSize = VBits / VL;
3554 bool Result = (Index * ElSize) % 128 == 0;
3559 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3560 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3561 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3562 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3563 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3565 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3567 for (int i = 0; i < NumOperands; ++i) {
3568 int Val = SVOp->getMaskElt(NumOperands-i-1);
3569 if (Val < 0) Val = 0;
3570 if (Val >= NumOperands) Val -= NumOperands;
3572 if (i != NumOperands - 1)
3578 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3579 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3580 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3581 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3583 // 8 nodes, but we only care about the last 4.
3584 for (unsigned i = 7; i >= 4; --i) {
3585 int Val = SVOp->getMaskElt(i);
3594 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3595 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3596 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3597 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3599 // 8 nodes, but we only care about the first 4.
3600 for (int i = 3; i >= 0; --i) {
3601 int Val = SVOp->getMaskElt(i);
3610 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3611 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3612 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3613 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3614 EVT VVT = N->getValueType(0);
3615 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3619 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3620 Val = SVOp->getMaskElt(i);
3624 return (Val - i) * EltSize;
3627 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3628 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3630 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3631 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3632 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3635 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3637 EVT VecVT = N->getOperand(0).getValueType();
3638 EVT ElVT = VecVT.getVectorElementType();
3640 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3642 return Index / NumElemsPerChunk;
3645 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3646 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3648 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3649 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3650 llvm_unreachable("Illegal insert subvector for VINSERTF128");
3653 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3655 EVT VecVT = N->getValueType(0);
3656 EVT ElVT = VecVT.getVectorElementType();
3658 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3660 return Index / NumElemsPerChunk;
3663 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3665 bool X86::isZeroNode(SDValue Elt) {
3666 return ((isa<ConstantSDNode>(Elt) &&
3667 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3668 (isa<ConstantFPSDNode>(Elt) &&
3669 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3672 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3673 /// their permute mask.
3674 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3675 SelectionDAG &DAG) {
3676 EVT VT = SVOp->getValueType(0);
3677 unsigned NumElems = VT.getVectorNumElements();
3678 SmallVector<int, 8> MaskVec;
3680 for (unsigned i = 0; i != NumElems; ++i) {
3681 int idx = SVOp->getMaskElt(i);
3683 MaskVec.push_back(idx);
3684 else if (idx < (int)NumElems)
3685 MaskVec.push_back(idx + NumElems);
3687 MaskVec.push_back(idx - NumElems);
3689 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3690 SVOp->getOperand(0), &MaskVec[0]);
3693 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3694 /// the two vector operands have swapped position.
3695 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3696 unsigned NumElems = VT.getVectorNumElements();
3697 for (unsigned i = 0; i != NumElems; ++i) {
3701 else if (idx < (int)NumElems)
3702 Mask[i] = idx + NumElems;
3704 Mask[i] = idx - NumElems;
3708 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3709 /// match movhlps. The lower half elements should come from upper half of
3710 /// V1 (and in order), and the upper half elements should come from the upper
3711 /// half of V2 (and in order).
3712 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3713 if (Op->getValueType(0).getVectorNumElements() != 4)
3715 for (unsigned i = 0, e = 2; i != e; ++i)
3716 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3718 for (unsigned i = 2; i != 4; ++i)
3719 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3724 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3725 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3727 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3728 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3730 N = N->getOperand(0).getNode();
3731 if (!ISD::isNON_EXTLoad(N))
3734 *LD = cast<LoadSDNode>(N);
3738 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3739 /// match movlp{s|d}. The lower half elements should come from lower half of
3740 /// V1 (and in order), and the upper half elements should come from the upper
3741 /// half of V2 (and in order). And since V1 will become the source of the
3742 /// MOVLP, it must be either a vector load or a scalar load to vector.
3743 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3744 ShuffleVectorSDNode *Op) {
3745 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3747 // Is V2 is a vector load, don't do this transformation. We will try to use
3748 // load folding shufps op.
3749 if (ISD::isNON_EXTLoad(V2))
3752 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3754 if (NumElems != 2 && NumElems != 4)
3756 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3757 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3759 for (unsigned i = NumElems/2; i != NumElems; ++i)
3760 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3765 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3767 static bool isSplatVector(SDNode *N) {
3768 if (N->getOpcode() != ISD::BUILD_VECTOR)
3771 SDValue SplatValue = N->getOperand(0);
3772 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3773 if (N->getOperand(i) != SplatValue)
3778 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3779 /// to an zero vector.
3780 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3781 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3782 SDValue V1 = N->getOperand(0);
3783 SDValue V2 = N->getOperand(1);
3784 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3785 for (unsigned i = 0; i != NumElems; ++i) {
3786 int Idx = N->getMaskElt(i);
3787 if (Idx >= (int)NumElems) {
3788 unsigned Opc = V2.getOpcode();
3789 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3791 if (Opc != ISD::BUILD_VECTOR ||
3792 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3794 } else if (Idx >= 0) {
3795 unsigned Opc = V1.getOpcode();
3796 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3798 if (Opc != ISD::BUILD_VECTOR ||
3799 !X86::isZeroNode(V1.getOperand(Idx)))
3806 /// getZeroVector - Returns a vector of specified type with all zero elements.
3808 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3810 assert(VT.isVector() && "Expected a vector type");
3812 // Always build SSE zero vectors as <4 x i32> bitcasted
3813 // to their dest type. This ensures they get CSE'd.
3815 if (VT.getSizeInBits() == 128) { // SSE
3816 if (HasSSE2) { // SSE2
3817 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3818 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3820 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3821 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3823 } else if (VT.getSizeInBits() == 256) { // AVX
3824 // 256-bit logic and arithmetic instructions in AVX are
3825 // all floating-point, no support for integer ops. Default
3826 // to emitting fp zeroed vectors then.
3827 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3828 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3829 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3831 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3834 /// getOnesVector - Returns a vector of specified type with all bits set.
3836 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3837 assert(VT.isVector() && "Expected a vector type");
3839 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3840 // type. This ensures they get CSE'd.
3841 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3843 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3844 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3848 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3849 /// that point to V2 points to its first element.
3850 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3851 EVT VT = SVOp->getValueType(0);
3852 unsigned NumElems = VT.getVectorNumElements();
3854 bool Changed = false;
3855 SmallVector<int, 8> MaskVec;
3856 SVOp->getMask(MaskVec);
3858 for (unsigned i = 0; i != NumElems; ++i) {
3859 if (MaskVec[i] > (int)NumElems) {
3860 MaskVec[i] = NumElems;
3865 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3866 SVOp->getOperand(1), &MaskVec[0]);
3867 return SDValue(SVOp, 0);
3870 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3871 /// operation of specified width.
3872 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3874 unsigned NumElems = VT.getVectorNumElements();
3875 SmallVector<int, 8> Mask;
3876 Mask.push_back(NumElems);
3877 for (unsigned i = 1; i != NumElems; ++i)
3879 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3882 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3883 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3885 unsigned NumElems = VT.getVectorNumElements();
3886 SmallVector<int, 8> Mask;
3887 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3889 Mask.push_back(i + NumElems);
3891 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3894 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3895 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3897 unsigned NumElems = VT.getVectorNumElements();
3898 unsigned Half = NumElems/2;
3899 SmallVector<int, 8> Mask;
3900 for (unsigned i = 0; i != Half; ++i) {
3901 Mask.push_back(i + Half);
3902 Mask.push_back(i + NumElems + Half);
3904 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3907 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3908 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3909 EVT PVT = MVT::v4f32;
3910 EVT VT = SV->getValueType(0);
3911 DebugLoc dl = SV->getDebugLoc();
3912 SDValue V1 = SV->getOperand(0);
3913 int NumElems = VT.getVectorNumElements();
3914 int EltNo = SV->getSplatIndex();
3916 // unpack elements to the correct location
3917 while (NumElems > 4) {
3918 if (EltNo < NumElems/2) {
3919 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3921 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3922 EltNo -= NumElems/2;
3927 // Perform the splat.
3928 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3929 V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3930 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3931 return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3934 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3935 /// vector of zero or undef vector. This produces a shuffle where the low
3936 /// element of V2 is swizzled into the zero/undef vector, landing at element
3937 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3938 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3939 bool isZero, bool HasSSE2,
3940 SelectionDAG &DAG) {
3941 EVT VT = V2.getValueType();
3943 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3944 unsigned NumElems = VT.getVectorNumElements();
3945 SmallVector<int, 16> MaskVec;
3946 for (unsigned i = 0; i != NumElems; ++i)
3947 // If this is the insertion idx, put the low elt of V2 here.
3948 MaskVec.push_back(i == Idx ? NumElems : i);
3949 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3952 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3953 /// element of the result of the vector shuffle.
3954 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3957 return SDValue(); // Limit search depth.
3959 SDValue V = SDValue(N, 0);
3960 EVT VT = V.getValueType();
3961 unsigned Opcode = V.getOpcode();
3963 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3964 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3965 Index = SV->getMaskElt(Index);
3968 return DAG.getUNDEF(VT.getVectorElementType());
3970 int NumElems = VT.getVectorNumElements();
3971 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3972 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3975 // Recurse into target specific vector shuffles to find scalars.
3976 if (isTargetShuffle(Opcode)) {
3977 int NumElems = VT.getVectorNumElements();
3978 SmallVector<unsigned, 16> ShuffleMask;
3982 case X86ISD::SHUFPS:
3983 case X86ISD::SHUFPD:
3984 ImmN = N->getOperand(N->getNumOperands()-1);
3985 DecodeSHUFPSMask(NumElems,
3986 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3989 case X86ISD::PUNPCKHBW:
3990 case X86ISD::PUNPCKHWD:
3991 case X86ISD::PUNPCKHDQ:
3992 case X86ISD::PUNPCKHQDQ:
3993 DecodePUNPCKHMask(NumElems, ShuffleMask);
3995 case X86ISD::UNPCKHPS:
3996 case X86ISD::UNPCKHPD:
3997 DecodeUNPCKHPMask(NumElems, ShuffleMask);
3999 case X86ISD::PUNPCKLBW:
4000 case X86ISD::PUNPCKLWD:
4001 case X86ISD::PUNPCKLDQ:
4002 case X86ISD::PUNPCKLQDQ:
4003 DecodePUNPCKLMask(VT, ShuffleMask);
4005 case X86ISD::UNPCKLPS:
4006 case X86ISD::UNPCKLPD:
4007 case X86ISD::VUNPCKLPS:
4008 case X86ISD::VUNPCKLPD:
4009 case X86ISD::VUNPCKLPSY:
4010 case X86ISD::VUNPCKLPDY:
4011 DecodeUNPCKLPMask(VT, ShuffleMask);
4013 case X86ISD::MOVHLPS:
4014 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4016 case X86ISD::MOVLHPS:
4017 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4019 case X86ISD::PSHUFD:
4020 ImmN = N->getOperand(N->getNumOperands()-1);
4021 DecodePSHUFMask(NumElems,
4022 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4025 case X86ISD::PSHUFHW:
4026 ImmN = N->getOperand(N->getNumOperands()-1);
4027 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4030 case X86ISD::PSHUFLW:
4031 ImmN = N->getOperand(N->getNumOperands()-1);
4032 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4036 case X86ISD::MOVSD: {
4037 // The index 0 always comes from the first element of the second source,
4038 // this is why MOVSS and MOVSD are used in the first place. The other
4039 // elements come from the other positions of the first source vector.
4040 unsigned OpNum = (Index == 0) ? 1 : 0;
4041 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4045 assert("not implemented for target shuffle node");
4049 Index = ShuffleMask[Index];
4051 return DAG.getUNDEF(VT.getVectorElementType());
4053 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4054 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4058 // Actual nodes that may contain scalar elements
4059 if (Opcode == ISD::BITCAST) {
4060 V = V.getOperand(0);
4061 EVT SrcVT = V.getValueType();
4062 unsigned NumElems = VT.getVectorNumElements();
4064 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4068 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4069 return (Index == 0) ? V.getOperand(0)
4070 : DAG.getUNDEF(VT.getVectorElementType());
4072 if (V.getOpcode() == ISD::BUILD_VECTOR)
4073 return V.getOperand(Index);
4078 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4079 /// shuffle operation which come from a consecutively from a zero. The
4080 /// search can start in two different directions, from left or right.
4082 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4083 bool ZerosFromLeft, SelectionDAG &DAG) {
4086 while (i < NumElems) {
4087 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4088 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4089 if (!(Elt.getNode() &&
4090 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4098 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4099 /// MaskE correspond consecutively to elements from one of the vector operands,
4100 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4102 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4103 int OpIdx, int NumElems, unsigned &OpNum) {
4104 bool SeenV1 = false;
4105 bool SeenV2 = false;
4107 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4108 int Idx = SVOp->getMaskElt(i);
4109 // Ignore undef indicies
4118 // Only accept consecutive elements from the same vector
4119 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4123 OpNum = SeenV1 ? 0 : 1;
4127 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4128 /// logical left shift of a vector.
4129 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4130 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4131 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4132 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4133 false /* check zeros from right */, DAG);
4139 // Considering the elements in the mask that are not consecutive zeros,
4140 // check if they consecutively come from only one of the source vectors.
4142 // V1 = {X, A, B, C} 0
4144 // vector_shuffle V1, V2 <1, 2, 3, X>
4146 if (!isShuffleMaskConsecutive(SVOp,
4147 0, // Mask Start Index
4148 NumElems-NumZeros-1, // Mask End Index
4149 NumZeros, // Where to start looking in the src vector
4150 NumElems, // Number of elements in vector
4151 OpSrc)) // Which source operand ?
4156 ShVal = SVOp->getOperand(OpSrc);
4160 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4161 /// logical left shift of a vector.
4162 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4163 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4164 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4165 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4166 true /* check zeros from left */, DAG);
4172 // Considering the elements in the mask that are not consecutive zeros,
4173 // check if they consecutively come from only one of the source vectors.
4175 // 0 { A, B, X, X } = V2
4177 // vector_shuffle V1, V2 <X, X, 4, 5>
4179 if (!isShuffleMaskConsecutive(SVOp,
4180 NumZeros, // Mask Start Index
4181 NumElems-1, // Mask End Index
4182 0, // Where to start looking in the src vector
4183 NumElems, // Number of elements in vector
4184 OpSrc)) // Which source operand ?
4189 ShVal = SVOp->getOperand(OpSrc);
4193 /// isVectorShift - Returns true if the shuffle can be implemented as a
4194 /// logical left or right shift of a vector.
4195 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4196 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4197 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4198 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4204 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4206 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4207 unsigned NumNonZero, unsigned NumZero,
4209 const TargetLowering &TLI) {
4213 DebugLoc dl = Op.getDebugLoc();
4216 for (unsigned i = 0; i < 16; ++i) {
4217 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4218 if (ThisIsNonZero && First) {
4220 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4222 V = DAG.getUNDEF(MVT::v8i16);
4227 SDValue ThisElt(0, 0), LastElt(0, 0);
4228 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4229 if (LastIsNonZero) {
4230 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4231 MVT::i16, Op.getOperand(i-1));
4233 if (ThisIsNonZero) {
4234 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4235 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4236 ThisElt, DAG.getConstant(8, MVT::i8));
4238 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4242 if (ThisElt.getNode())
4243 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4244 DAG.getIntPtrConstant(i/2));
4248 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4251 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4253 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4254 unsigned NumNonZero, unsigned NumZero,
4256 const TargetLowering &TLI) {
4260 DebugLoc dl = Op.getDebugLoc();
4263 for (unsigned i = 0; i < 8; ++i) {
4264 bool isNonZero = (NonZeros & (1 << i)) != 0;
4268 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4270 V = DAG.getUNDEF(MVT::v8i16);
4273 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4274 MVT::v8i16, V, Op.getOperand(i),
4275 DAG.getIntPtrConstant(i));
4282 /// getVShift - Return a vector logical shift node.
4284 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4285 unsigned NumBits, SelectionDAG &DAG,
4286 const TargetLowering &TLI, DebugLoc dl) {
4287 EVT ShVT = MVT::v2i64;
4288 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4289 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4290 return DAG.getNode(ISD::BITCAST, dl, VT,
4291 DAG.getNode(Opc, dl, ShVT, SrcOp,
4292 DAG.getConstant(NumBits,
4293 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4297 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4298 SelectionDAG &DAG) const {
4300 // Check if the scalar load can be widened into a vector load. And if
4301 // the address is "base + cst" see if the cst can be "absorbed" into
4302 // the shuffle mask.
4303 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4304 SDValue Ptr = LD->getBasePtr();
4305 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4307 EVT PVT = LD->getValueType(0);
4308 if (PVT != MVT::i32 && PVT != MVT::f32)
4313 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4314 FI = FINode->getIndex();
4316 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4317 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4318 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4319 Offset = Ptr.getConstantOperandVal(1);
4320 Ptr = Ptr.getOperand(0);
4325 SDValue Chain = LD->getChain();
4326 // Make sure the stack object alignment is at least 16.
4327 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4328 if (DAG.InferPtrAlignment(Ptr) < 16) {
4329 if (MFI->isFixedObjectIndex(FI)) {
4330 // Can't change the alignment. FIXME: It's possible to compute
4331 // the exact stack offset and reference FI + adjust offset instead.
4332 // If someone *really* cares about this. That's the way to implement it.
4335 MFI->setObjectAlignment(FI, 16);
4339 // (Offset % 16) must be multiple of 4. Then address is then
4340 // Ptr + (Offset & ~15).
4343 if ((Offset % 16) & 3)
4345 int64_t StartOffset = Offset & ~15;
4347 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4348 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4350 int EltNo = (Offset - StartOffset) >> 2;
4351 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4352 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4353 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4354 LD->getPointerInfo().getWithOffset(StartOffset),
4356 // Canonicalize it to a v4i32 shuffle.
4357 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4358 return DAG.getNode(ISD::BITCAST, dl, VT,
4359 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4360 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4366 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4367 /// vector of type 'VT', see if the elements can be replaced by a single large
4368 /// load which has the same value as a build_vector whose operands are 'elts'.
4370 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4372 /// FIXME: we'd also like to handle the case where the last elements are zero
4373 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4374 /// There's even a handy isZeroNode for that purpose.
4375 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4376 DebugLoc &DL, SelectionDAG &DAG) {
4377 EVT EltVT = VT.getVectorElementType();
4378 unsigned NumElems = Elts.size();
4380 LoadSDNode *LDBase = NULL;
4381 unsigned LastLoadedElt = -1U;
4383 // For each element in the initializer, see if we've found a load or an undef.
4384 // If we don't find an initial load element, or later load elements are
4385 // non-consecutive, bail out.
4386 for (unsigned i = 0; i < NumElems; ++i) {
4387 SDValue Elt = Elts[i];
4389 if (!Elt.getNode() ||
4390 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4393 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4395 LDBase = cast<LoadSDNode>(Elt.getNode());
4399 if (Elt.getOpcode() == ISD::UNDEF)
4402 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4403 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4408 // If we have found an entire vector of loads and undefs, then return a large
4409 // load of the entire vector width starting at the base pointer. If we found
4410 // consecutive loads for the low half, generate a vzext_load node.
4411 if (LastLoadedElt == NumElems - 1) {
4412 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4413 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4414 LDBase->getPointerInfo(),
4415 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4416 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4417 LDBase->getPointerInfo(),
4418 LDBase->isVolatile(), LDBase->isNonTemporal(),
4419 LDBase->getAlignment());
4420 } else if (NumElems == 4 && LastLoadedElt == 1) {
4421 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4422 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4423 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4425 LDBase->getMemOperand());
4426 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4432 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4433 DebugLoc dl = Op.getDebugLoc();
4435 EVT VT = Op.getValueType();
4436 EVT ExtVT = VT.getVectorElementType();
4438 unsigned NumElems = Op.getNumOperands();
4440 // For AVX-length vectors, build the individual 128-bit pieces and
4441 // use shuffles to put them in place.
4442 if (VT.getSizeInBits() > 256 &&
4443 Subtarget->hasAVX() &&
4444 !ISD::isBuildVectorAllZeros(Op.getNode())) {
4445 SmallVector<SDValue, 8> V;
4447 for (unsigned i = 0; i < NumElems; ++i) {
4448 V[i] = Op.getOperand(i);
4451 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4453 // Build the lower subvector.
4454 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4455 // Build the upper subvector.
4456 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4459 return ConcatVectors(Lower, Upper, DAG);
4462 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4463 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4464 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4465 // is present, so AllOnes is ignored.
4466 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4467 (Op.getValueType().getSizeInBits() != 256 &&
4468 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4469 // Canonicalize this to <4 x i32> (SSE) to
4470 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4471 // eliminated on x86-32 hosts.
4472 if (Op.getValueType() == MVT::v4i32)
4475 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4476 return getOnesVector(Op.getValueType(), DAG, dl);
4477 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4480 unsigned EVTBits = ExtVT.getSizeInBits();
4482 unsigned NumZero = 0;
4483 unsigned NumNonZero = 0;
4484 unsigned NonZeros = 0;
4485 bool IsAllConstants = true;
4486 SmallSet<SDValue, 8> Values;
4487 for (unsigned i = 0; i < NumElems; ++i) {
4488 SDValue Elt = Op.getOperand(i);
4489 if (Elt.getOpcode() == ISD::UNDEF)
4492 if (Elt.getOpcode() != ISD::Constant &&
4493 Elt.getOpcode() != ISD::ConstantFP)
4494 IsAllConstants = false;
4495 if (X86::isZeroNode(Elt))
4498 NonZeros |= (1 << i);
4503 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4504 if (NumNonZero == 0)
4505 return DAG.getUNDEF(VT);
4507 // Special case for single non-zero, non-undef, element.
4508 if (NumNonZero == 1) {
4509 unsigned Idx = CountTrailingZeros_32(NonZeros);
4510 SDValue Item = Op.getOperand(Idx);
4512 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4513 // the value are obviously zero, truncate the value to i32 and do the
4514 // insertion that way. Only do this if the value is non-constant or if the
4515 // value is a constant being inserted into element 0. It is cheaper to do
4516 // a constant pool load than it is to do a movd + shuffle.
4517 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4518 (!IsAllConstants || Idx == 0)) {
4519 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4521 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4522 EVT VecVT = MVT::v4i32;
4523 unsigned VecElts = 4;
4525 // Truncate the value (which may itself be a constant) to i32, and
4526 // convert it to a vector with movd (S2V+shuffle to zero extend).
4527 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4528 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4529 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4530 Subtarget->hasSSE2(), DAG);
4532 // Now we have our 32-bit value zero extended in the low element of
4533 // a vector. If Idx != 0, swizzle it into place.
4535 SmallVector<int, 4> Mask;
4536 Mask.push_back(Idx);
4537 for (unsigned i = 1; i != VecElts; ++i)
4539 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4540 DAG.getUNDEF(Item.getValueType()),
4543 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4547 // If we have a constant or non-constant insertion into the low element of
4548 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4549 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4550 // depending on what the source datatype is.
4553 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4554 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4555 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4556 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4557 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4558 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4560 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4561 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4562 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4563 EVT MiddleVT = MVT::v4i32;
4564 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4565 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4566 Subtarget->hasSSE2(), DAG);
4567 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4571 // Is it a vector logical left shift?
4572 if (NumElems == 2 && Idx == 1 &&
4573 X86::isZeroNode(Op.getOperand(0)) &&
4574 !X86::isZeroNode(Op.getOperand(1))) {
4575 unsigned NumBits = VT.getSizeInBits();
4576 return getVShift(true, VT,
4577 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4578 VT, Op.getOperand(1)),
4579 NumBits/2, DAG, *this, dl);
4582 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4585 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4586 // is a non-constant being inserted into an element other than the low one,
4587 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4588 // movd/movss) to move this into the low element, then shuffle it into
4590 if (EVTBits == 32) {
4591 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4593 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4594 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4595 Subtarget->hasSSE2(), DAG);
4596 SmallVector<int, 8> MaskVec;
4597 for (unsigned i = 0; i < NumElems; i++)
4598 MaskVec.push_back(i == Idx ? 0 : 1);
4599 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4603 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4604 if (Values.size() == 1) {
4605 if (EVTBits == 32) {
4606 // Instead of a shuffle like this:
4607 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4608 // Check if it's possible to issue this instead.
4609 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4610 unsigned Idx = CountTrailingZeros_32(NonZeros);
4611 SDValue Item = Op.getOperand(Idx);
4612 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4613 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4618 // A vector full of immediates; various special cases are already
4619 // handled, so this is best done with a single constant-pool load.
4623 // Let legalizer expand 2-wide build_vectors.
4624 if (EVTBits == 64) {
4625 if (NumNonZero == 1) {
4626 // One half is zero or undef.
4627 unsigned Idx = CountTrailingZeros_32(NonZeros);
4628 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4629 Op.getOperand(Idx));
4630 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4631 Subtarget->hasSSE2(), DAG);
4636 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4637 if (EVTBits == 8 && NumElems == 16) {
4638 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4640 if (V.getNode()) return V;
4643 if (EVTBits == 16 && NumElems == 8) {
4644 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4646 if (V.getNode()) return V;
4649 // If element VT is == 32 bits, turn it into a number of shuffles.
4650 SmallVector<SDValue, 8> V;
4652 if (NumElems == 4 && NumZero > 0) {
4653 for (unsigned i = 0; i < 4; ++i) {
4654 bool isZero = !(NonZeros & (1 << i));
4656 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4658 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4661 for (unsigned i = 0; i < 2; ++i) {
4662 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4665 V[i] = V[i*2]; // Must be a zero vector.
4668 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4671 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4674 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4679 SmallVector<int, 8> MaskVec;
4680 bool Reverse = (NonZeros & 0x3) == 2;
4681 for (unsigned i = 0; i < 2; ++i)
4682 MaskVec.push_back(Reverse ? 1-i : i);
4683 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4684 for (unsigned i = 0; i < 2; ++i)
4685 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4686 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4689 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4690 // Check for a build vector of consecutive loads.
4691 for (unsigned i = 0; i < NumElems; ++i)
4692 V[i] = Op.getOperand(i);
4694 // Check for elements which are consecutive loads.
4695 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4699 // For SSE 4.1, use insertps to put the high elements into the low element.
4700 if (getSubtarget()->hasSSE41()) {
4702 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4703 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4705 Result = DAG.getUNDEF(VT);
4707 for (unsigned i = 1; i < NumElems; ++i) {
4708 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4709 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4710 Op.getOperand(i), DAG.getIntPtrConstant(i));
4715 // Otherwise, expand into a number of unpckl*, start by extending each of
4716 // our (non-undef) elements to the full vector width with the element in the
4717 // bottom slot of the vector (which generates no code for SSE).
4718 for (unsigned i = 0; i < NumElems; ++i) {
4719 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4720 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4722 V[i] = DAG.getUNDEF(VT);
4725 // Next, we iteratively mix elements, e.g. for v4f32:
4726 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4727 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4728 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4729 unsigned EltStride = NumElems >> 1;
4730 while (EltStride != 0) {
4731 for (unsigned i = 0; i < EltStride; ++i) {
4732 // If V[i+EltStride] is undef and this is the first round of mixing,
4733 // then it is safe to just drop this shuffle: V[i] is already in the
4734 // right place, the one element (since it's the first round) being
4735 // inserted as undef can be dropped. This isn't safe for successive
4736 // rounds because they will permute elements within both vectors.
4737 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4738 EltStride == NumElems/2)
4741 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4751 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4752 // We support concatenate two MMX registers and place them in a MMX
4753 // register. This is better than doing a stack convert.
4754 DebugLoc dl = Op.getDebugLoc();
4755 EVT ResVT = Op.getValueType();
4756 assert(Op.getNumOperands() == 2);
4757 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4758 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4760 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4761 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4762 InVec = Op.getOperand(1);
4763 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4764 unsigned NumElts = ResVT.getVectorNumElements();
4765 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4766 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4767 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4769 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4770 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4771 Mask[0] = 0; Mask[1] = 2;
4772 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4774 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4777 // v8i16 shuffles - Prefer shuffles in the following order:
4778 // 1. [all] pshuflw, pshufhw, optional move
4779 // 2. [ssse3] 1 x pshufb
4780 // 3. [ssse3] 2 x pshufb + 1 x por
4781 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4783 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4784 SelectionDAG &DAG) const {
4785 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4786 SDValue V1 = SVOp->getOperand(0);
4787 SDValue V2 = SVOp->getOperand(1);
4788 DebugLoc dl = SVOp->getDebugLoc();
4789 SmallVector<int, 8> MaskVals;
4791 // Determine if more than 1 of the words in each of the low and high quadwords
4792 // of the result come from the same quadword of one of the two inputs. Undef
4793 // mask values count as coming from any quadword, for better codegen.
4794 SmallVector<unsigned, 4> LoQuad(4);
4795 SmallVector<unsigned, 4> HiQuad(4);
4796 BitVector InputQuads(4);
4797 for (unsigned i = 0; i < 8; ++i) {
4798 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4799 int EltIdx = SVOp->getMaskElt(i);
4800 MaskVals.push_back(EltIdx);
4809 InputQuads.set(EltIdx / 4);
4812 int BestLoQuad = -1;
4813 unsigned MaxQuad = 1;
4814 for (unsigned i = 0; i < 4; ++i) {
4815 if (LoQuad[i] > MaxQuad) {
4817 MaxQuad = LoQuad[i];
4821 int BestHiQuad = -1;
4823 for (unsigned i = 0; i < 4; ++i) {
4824 if (HiQuad[i] > MaxQuad) {
4826 MaxQuad = HiQuad[i];
4830 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4831 // of the two input vectors, shuffle them into one input vector so only a
4832 // single pshufb instruction is necessary. If There are more than 2 input
4833 // quads, disable the next transformation since it does not help SSSE3.
4834 bool V1Used = InputQuads[0] || InputQuads[1];
4835 bool V2Used = InputQuads[2] || InputQuads[3];
4836 if (Subtarget->hasSSSE3()) {
4837 if (InputQuads.count() == 2 && V1Used && V2Used) {
4838 BestLoQuad = InputQuads.find_first();
4839 BestHiQuad = InputQuads.find_next(BestLoQuad);
4841 if (InputQuads.count() > 2) {
4847 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4848 // the shuffle mask. If a quad is scored as -1, that means that it contains
4849 // words from all 4 input quadwords.
4851 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4852 SmallVector<int, 8> MaskV;
4853 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4854 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4855 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4856 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4857 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4858 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4860 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4861 // source words for the shuffle, to aid later transformations.
4862 bool AllWordsInNewV = true;
4863 bool InOrder[2] = { true, true };
4864 for (unsigned i = 0; i != 8; ++i) {
4865 int idx = MaskVals[i];
4867 InOrder[i/4] = false;
4868 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4870 AllWordsInNewV = false;
4874 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4875 if (AllWordsInNewV) {
4876 for (int i = 0; i != 8; ++i) {
4877 int idx = MaskVals[i];
4880 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4881 if ((idx != i) && idx < 4)
4883 if ((idx != i) && idx > 3)
4892 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4893 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4894 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4895 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4896 unsigned TargetMask = 0;
4897 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4898 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4899 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4900 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4901 V1 = NewV.getOperand(0);
4902 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4906 // If we have SSSE3, and all words of the result are from 1 input vector,
4907 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4908 // is present, fall back to case 4.
4909 if (Subtarget->hasSSSE3()) {
4910 SmallVector<SDValue,16> pshufbMask;
4912 // If we have elements from both input vectors, set the high bit of the
4913 // shuffle mask element to zero out elements that come from V2 in the V1
4914 // mask, and elements that come from V1 in the V2 mask, so that the two
4915 // results can be OR'd together.
4916 bool TwoInputs = V1Used && V2Used;
4917 for (unsigned i = 0; i != 8; ++i) {
4918 int EltIdx = MaskVals[i] * 2;
4919 if (TwoInputs && (EltIdx >= 16)) {
4920 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4921 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4924 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4925 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4927 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4928 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4929 DAG.getNode(ISD::BUILD_VECTOR, dl,
4930 MVT::v16i8, &pshufbMask[0], 16));
4932 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4934 // Calculate the shuffle mask for the second input, shuffle it, and
4935 // OR it with the first shuffled input.
4937 for (unsigned i = 0; i != 8; ++i) {
4938 int EltIdx = MaskVals[i] * 2;
4940 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4941 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4944 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4945 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4947 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4948 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4949 DAG.getNode(ISD::BUILD_VECTOR, dl,
4950 MVT::v16i8, &pshufbMask[0], 16));
4951 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4952 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4955 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4956 // and update MaskVals with new element order.
4957 BitVector InOrder(8);
4958 if (BestLoQuad >= 0) {
4959 SmallVector<int, 8> MaskV;
4960 for (int i = 0; i != 4; ++i) {
4961 int idx = MaskVals[i];
4963 MaskV.push_back(-1);
4965 } else if ((idx / 4) == BestLoQuad) {
4966 MaskV.push_back(idx & 3);
4969 MaskV.push_back(-1);
4972 for (unsigned i = 4; i != 8; ++i)
4974 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4977 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4978 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4980 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4984 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4985 // and update MaskVals with the new element order.
4986 if (BestHiQuad >= 0) {
4987 SmallVector<int, 8> MaskV;
4988 for (unsigned i = 0; i != 4; ++i)
4990 for (unsigned i = 4; i != 8; ++i) {
4991 int idx = MaskVals[i];
4993 MaskV.push_back(-1);
4995 } else if ((idx / 4) == BestHiQuad) {
4996 MaskV.push_back((idx & 3) + 4);
4999 MaskV.push_back(-1);
5002 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5005 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5006 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5008 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5012 // In case BestHi & BestLo were both -1, which means each quadword has a word
5013 // from each of the four input quadwords, calculate the InOrder bitvector now
5014 // before falling through to the insert/extract cleanup.
5015 if (BestLoQuad == -1 && BestHiQuad == -1) {
5017 for (int i = 0; i != 8; ++i)
5018 if (MaskVals[i] < 0 || MaskVals[i] == i)
5022 // The other elements are put in the right place using pextrw and pinsrw.
5023 for (unsigned i = 0; i != 8; ++i) {
5026 int EltIdx = MaskVals[i];
5029 SDValue ExtOp = (EltIdx < 8)
5030 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5031 DAG.getIntPtrConstant(EltIdx))
5032 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5033 DAG.getIntPtrConstant(EltIdx - 8));
5034 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5035 DAG.getIntPtrConstant(i));
5040 // v16i8 shuffles - Prefer shuffles in the following order:
5041 // 1. [ssse3] 1 x pshufb
5042 // 2. [ssse3] 2 x pshufb + 1 x por
5043 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5045 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5047 const X86TargetLowering &TLI) {
5048 SDValue V1 = SVOp->getOperand(0);
5049 SDValue V2 = SVOp->getOperand(1);
5050 DebugLoc dl = SVOp->getDebugLoc();
5051 SmallVector<int, 16> MaskVals;
5052 SVOp->getMask(MaskVals);
5054 // If we have SSSE3, case 1 is generated when all result bytes come from
5055 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5056 // present, fall back to case 3.
5057 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5060 for (unsigned i = 0; i < 16; ++i) {
5061 int EltIdx = MaskVals[i];
5070 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5071 if (TLI.getSubtarget()->hasSSSE3()) {
5072 SmallVector<SDValue,16> pshufbMask;
5074 // If all result elements are from one input vector, then only translate
5075 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5077 // Otherwise, we have elements from both input vectors, and must zero out
5078 // elements that come from V2 in the first mask, and V1 in the second mask
5079 // so that we can OR them together.
5080 bool TwoInputs = !(V1Only || V2Only);
5081 for (unsigned i = 0; i != 16; ++i) {
5082 int EltIdx = MaskVals[i];
5083 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5084 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5087 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5089 // If all the elements are from V2, assign it to V1 and return after
5090 // building the first pshufb.
5093 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5094 DAG.getNode(ISD::BUILD_VECTOR, dl,
5095 MVT::v16i8, &pshufbMask[0], 16));
5099 // Calculate the shuffle mask for the second input, shuffle it, and
5100 // OR it with the first shuffled input.
5102 for (unsigned i = 0; i != 16; ++i) {
5103 int EltIdx = MaskVals[i];
5105 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5108 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5110 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5111 DAG.getNode(ISD::BUILD_VECTOR, dl,
5112 MVT::v16i8, &pshufbMask[0], 16));
5113 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5116 // No SSSE3 - Calculate in place words and then fix all out of place words
5117 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5118 // the 16 different words that comprise the two doublequadword input vectors.
5119 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5120 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5121 SDValue NewV = V2Only ? V2 : V1;
5122 for (int i = 0; i != 8; ++i) {
5123 int Elt0 = MaskVals[i*2];
5124 int Elt1 = MaskVals[i*2+1];
5126 // This word of the result is all undef, skip it.
5127 if (Elt0 < 0 && Elt1 < 0)
5130 // This word of the result is already in the correct place, skip it.
5131 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5133 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5136 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5137 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5140 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5141 // using a single extract together, load it and store it.
5142 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5143 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5144 DAG.getIntPtrConstant(Elt1 / 2));
5145 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5146 DAG.getIntPtrConstant(i));
5150 // If Elt1 is defined, extract it from the appropriate source. If the
5151 // source byte is not also odd, shift the extracted word left 8 bits
5152 // otherwise clear the bottom 8 bits if we need to do an or.
5154 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5155 DAG.getIntPtrConstant(Elt1 / 2));
5156 if ((Elt1 & 1) == 0)
5157 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5159 TLI.getShiftAmountTy(InsElt.getValueType())));
5161 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5162 DAG.getConstant(0xFF00, MVT::i16));
5164 // If Elt0 is defined, extract it from the appropriate source. If the
5165 // source byte is not also even, shift the extracted word right 8 bits. If
5166 // Elt1 was also defined, OR the extracted values together before
5167 // inserting them in the result.
5169 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5170 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5171 if ((Elt0 & 1) != 0)
5172 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5174 TLI.getShiftAmountTy(InsElt0.getValueType())));
5176 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5177 DAG.getConstant(0x00FF, MVT::i16));
5178 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5181 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5182 DAG.getIntPtrConstant(i));
5184 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5187 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5188 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5189 /// done when every pair / quad of shuffle mask elements point to elements in
5190 /// the right sequence. e.g.
5191 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5193 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5194 SelectionDAG &DAG, DebugLoc dl) {
5195 EVT VT = SVOp->getValueType(0);
5196 SDValue V1 = SVOp->getOperand(0);
5197 SDValue V2 = SVOp->getOperand(1);
5198 unsigned NumElems = VT.getVectorNumElements();
5199 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5201 switch (VT.getSimpleVT().SimpleTy) {
5202 default: assert(false && "Unexpected!");
5203 case MVT::v4f32: NewVT = MVT::v2f64; break;
5204 case MVT::v4i32: NewVT = MVT::v2i64; break;
5205 case MVT::v8i16: NewVT = MVT::v4i32; break;
5206 case MVT::v16i8: NewVT = MVT::v4i32; break;
5209 int Scale = NumElems / NewWidth;
5210 SmallVector<int, 8> MaskVec;
5211 for (unsigned i = 0; i < NumElems; i += Scale) {
5213 for (int j = 0; j < Scale; ++j) {
5214 int EltIdx = SVOp->getMaskElt(i+j);
5218 StartIdx = EltIdx - (EltIdx % Scale);
5219 if (EltIdx != StartIdx + j)
5223 MaskVec.push_back(-1);
5225 MaskVec.push_back(StartIdx / Scale);
5228 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5229 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5230 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5233 /// getVZextMovL - Return a zero-extending vector move low node.
5235 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5236 SDValue SrcOp, SelectionDAG &DAG,
5237 const X86Subtarget *Subtarget, DebugLoc dl) {
5238 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5239 LoadSDNode *LD = NULL;
5240 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5241 LD = dyn_cast<LoadSDNode>(SrcOp);
5243 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5245 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5246 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5247 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5248 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5249 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5251 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5252 return DAG.getNode(ISD::BITCAST, dl, VT,
5253 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5254 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5262 return DAG.getNode(ISD::BITCAST, dl, VT,
5263 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5264 DAG.getNode(ISD::BITCAST, dl,
5268 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5271 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5272 SDValue V1 = SVOp->getOperand(0);
5273 SDValue V2 = SVOp->getOperand(1);
5274 DebugLoc dl = SVOp->getDebugLoc();
5275 EVT VT = SVOp->getValueType(0);
5277 SmallVector<std::pair<int, int>, 8> Locs;
5279 SmallVector<int, 8> Mask1(4U, -1);
5280 SmallVector<int, 8> PermMask;
5281 SVOp->getMask(PermMask);
5285 for (unsigned i = 0; i != 4; ++i) {
5286 int Idx = PermMask[i];
5288 Locs[i] = std::make_pair(-1, -1);
5290 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5292 Locs[i] = std::make_pair(0, NumLo);
5296 Locs[i] = std::make_pair(1, NumHi);
5298 Mask1[2+NumHi] = Idx;
5304 if (NumLo <= 2 && NumHi <= 2) {
5305 // If no more than two elements come from either vector. This can be
5306 // implemented with two shuffles. First shuffle gather the elements.
5307 // The second shuffle, which takes the first shuffle as both of its
5308 // vector operands, put the elements into the right order.
5309 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5311 SmallVector<int, 8> Mask2(4U, -1);
5313 for (unsigned i = 0; i != 4; ++i) {
5314 if (Locs[i].first == -1)
5317 unsigned Idx = (i < 2) ? 0 : 4;
5318 Idx += Locs[i].first * 2 + Locs[i].second;
5323 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5324 } else if (NumLo == 3 || NumHi == 3) {
5325 // Otherwise, we must have three elements from one vector, call it X, and
5326 // one element from the other, call it Y. First, use a shufps to build an
5327 // intermediate vector with the one element from Y and the element from X
5328 // that will be in the same half in the final destination (the indexes don't
5329 // matter). Then, use a shufps to build the final vector, taking the half
5330 // containing the element from Y from the intermediate, and the other half
5333 // Normalize it so the 3 elements come from V1.
5334 CommuteVectorShuffleMask(PermMask, VT);
5338 // Find the element from V2.
5340 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5341 int Val = PermMask[HiIndex];
5348 Mask1[0] = PermMask[HiIndex];
5350 Mask1[2] = PermMask[HiIndex^1];
5352 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5355 Mask1[0] = PermMask[0];
5356 Mask1[1] = PermMask[1];
5357 Mask1[2] = HiIndex & 1 ? 6 : 4;
5358 Mask1[3] = HiIndex & 1 ? 4 : 6;
5359 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5361 Mask1[0] = HiIndex & 1 ? 2 : 0;
5362 Mask1[1] = HiIndex & 1 ? 0 : 2;
5363 Mask1[2] = PermMask[2];
5364 Mask1[3] = PermMask[3];
5369 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5373 // Break it into (shuffle shuffle_hi, shuffle_lo).
5376 SmallVector<int,8> LoMask(4U, -1);
5377 SmallVector<int,8> HiMask(4U, -1);
5379 SmallVector<int,8> *MaskPtr = &LoMask;
5380 unsigned MaskIdx = 0;
5383 for (unsigned i = 0; i != 4; ++i) {
5390 int Idx = PermMask[i];
5392 Locs[i] = std::make_pair(-1, -1);
5393 } else if (Idx < 4) {
5394 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5395 (*MaskPtr)[LoIdx] = Idx;
5398 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5399 (*MaskPtr)[HiIdx] = Idx;
5404 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5405 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5406 SmallVector<int, 8> MaskOps;
5407 for (unsigned i = 0; i != 4; ++i) {
5408 if (Locs[i].first == -1) {
5409 MaskOps.push_back(-1);
5411 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5412 MaskOps.push_back(Idx);
5415 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5418 static bool MayFoldVectorLoad(SDValue V) {
5419 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5420 V = V.getOperand(0);
5421 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5422 V = V.getOperand(0);
5428 // FIXME: the version above should always be used. Since there's
5429 // a bug where several vector shuffles can't be folded because the
5430 // DAG is not updated during lowering and a node claims to have two
5431 // uses while it only has one, use this version, and let isel match
5432 // another instruction if the load really happens to have more than
5433 // one use. Remove this version after this bug get fixed.
5434 // rdar://8434668, PR8156
5435 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5436 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5437 V = V.getOperand(0);
5438 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5439 V = V.getOperand(0);
5440 if (ISD::isNormalLoad(V.getNode()))
5445 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5446 /// a vector extract, and if both can be later optimized into a single load.
5447 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5448 /// here because otherwise a target specific shuffle node is going to be
5449 /// emitted for this shuffle, and the optimization not done.
5450 /// FIXME: This is probably not the best approach, but fix the problem
5451 /// until the right path is decided.
5453 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5454 const TargetLowering &TLI) {
5455 EVT VT = V.getValueType();
5456 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5458 // Be sure that the vector shuffle is present in a pattern like this:
5459 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5463 SDNode *N = *V.getNode()->use_begin();
5464 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5467 SDValue EltNo = N->getOperand(1);
5468 if (!isa<ConstantSDNode>(EltNo))
5471 // If the bit convert changed the number of elements, it is unsafe
5472 // to examine the mask.
5473 bool HasShuffleIntoBitcast = false;
5474 if (V.getOpcode() == ISD::BITCAST) {
5475 EVT SrcVT = V.getOperand(0).getValueType();
5476 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5478 V = V.getOperand(0);
5479 HasShuffleIntoBitcast = true;
5482 // Select the input vector, guarding against out of range extract vector.
5483 unsigned NumElems = VT.getVectorNumElements();
5484 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5485 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5486 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5488 // Skip one more bit_convert if necessary
5489 if (V.getOpcode() == ISD::BITCAST)
5490 V = V.getOperand(0);
5492 if (ISD::isNormalLoad(V.getNode())) {
5493 // Is the original load suitable?
5494 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5496 // FIXME: avoid the multi-use bug that is preventing lots of
5497 // of foldings to be detected, this is still wrong of course, but
5498 // give the temporary desired behavior, and if it happens that
5499 // the load has real more uses, during isel it will not fold, and
5500 // will generate poor code.
5501 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5504 if (!HasShuffleIntoBitcast)
5507 // If there's a bitcast before the shuffle, check if the load type and
5508 // alignment is valid.
5509 unsigned Align = LN0->getAlignment();
5511 TLI.getTargetData()->getABITypeAlignment(
5512 VT.getTypeForEVT(*DAG.getContext()));
5514 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5522 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5523 EVT VT = Op.getValueType();
5525 // Canonizalize to v2f64.
5526 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5527 return DAG.getNode(ISD::BITCAST, dl, VT,
5528 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5533 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5535 SDValue V1 = Op.getOperand(0);
5536 SDValue V2 = Op.getOperand(1);
5537 EVT VT = Op.getValueType();
5539 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5541 if (HasSSE2 && VT == MVT::v2f64)
5542 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5545 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5549 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5550 SDValue V1 = Op.getOperand(0);
5551 SDValue V2 = Op.getOperand(1);
5552 EVT VT = Op.getValueType();
5554 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5555 "unsupported shuffle type");
5557 if (V2.getOpcode() == ISD::UNDEF)
5561 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5565 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5566 SDValue V1 = Op.getOperand(0);
5567 SDValue V2 = Op.getOperand(1);
5568 EVT VT = Op.getValueType();
5569 unsigned NumElems = VT.getVectorNumElements();
5571 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5572 // operand of these instructions is only memory, so check if there's a
5573 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5575 bool CanFoldLoad = false;
5577 // Trivial case, when V2 comes from a load.
5578 if (MayFoldVectorLoad(V2))
5581 // When V1 is a load, it can be folded later into a store in isel, example:
5582 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5584 // (MOVLPSmr addr:$src1, VR128:$src2)
5585 // So, recognize this potential and also use MOVLPS or MOVLPD
5586 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5589 // Both of them can't be memory operations though.
5590 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5591 CanFoldLoad = false;
5594 if (HasSSE2 && NumElems == 2)
5595 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5598 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5601 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5602 // movl and movlp will both match v2i64, but v2i64 is never matched by
5603 // movl earlier because we make it strict to avoid messing with the movlp load
5604 // folding logic (see the code above getMOVLP call). Match it here then,
5605 // this is horrible, but will stay like this until we move all shuffle
5606 // matching to x86 specific nodes. Note that for the 1st condition all
5607 // types are matched with movsd.
5608 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5609 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5611 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5614 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5616 // Invert the operand order and use SHUFPS to match it.
5617 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5618 X86::getShuffleSHUFImmediate(SVOp), DAG);
5621 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5622 switch(VT.getSimpleVT().SimpleTy) {
5623 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5624 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5626 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5628 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5629 case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5630 case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5631 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5632 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5634 llvm_unreachable("Unknown type for unpckl");
5639 static inline unsigned getUNPCKHOpcode(EVT VT) {
5640 switch(VT.getSimpleVT().SimpleTy) {
5641 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5642 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5643 case MVT::v4f32: return X86ISD::UNPCKHPS;
5644 case MVT::v2f64: return X86ISD::UNPCKHPD;
5645 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5646 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5648 llvm_unreachable("Unknown type for unpckh");
5654 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5655 const TargetLowering &TLI,
5656 const X86Subtarget *Subtarget) {
5657 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5658 EVT VT = Op.getValueType();
5659 DebugLoc dl = Op.getDebugLoc();
5660 SDValue V1 = Op.getOperand(0);
5661 SDValue V2 = Op.getOperand(1);
5663 if (isZeroShuffle(SVOp))
5664 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5666 // Handle splat operations
5667 if (SVOp->isSplat()) {
5668 // Special case, this is the only place now where it's
5669 // allowed to return a vector_shuffle operation without
5670 // using a target specific node, because *hopefully* it
5671 // will be optimized away by the dag combiner.
5672 if (VT.getVectorNumElements() <= 4 &&
5673 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5676 // Handle splats by matching through known masks
5677 if (VT.getVectorNumElements() <= 4)
5680 // Canonicalize all of the remaining to v4f32.
5681 return PromoteSplat(SVOp, DAG);
5684 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5686 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5687 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5688 if (NewOp.getNode())
5689 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5690 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5691 // FIXME: Figure out a cleaner way to do this.
5692 // Try to make use of movq to zero out the top part.
5693 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5694 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5695 if (NewOp.getNode()) {
5696 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5697 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5698 DAG, Subtarget, dl);
5700 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5701 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5702 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5703 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5704 DAG, Subtarget, dl);
5711 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5712 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5713 SDValue V1 = Op.getOperand(0);
5714 SDValue V2 = Op.getOperand(1);
5715 EVT VT = Op.getValueType();
5716 DebugLoc dl = Op.getDebugLoc();
5717 unsigned NumElems = VT.getVectorNumElements();
5718 bool isMMX = VT.getSizeInBits() == 64;
5719 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5720 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5721 bool V1IsSplat = false;
5722 bool V2IsSplat = false;
5723 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5724 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5725 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5726 MachineFunction &MF = DAG.getMachineFunction();
5727 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5729 // Shuffle operations on MMX not supported.
5733 // Vector shuffle lowering takes 3 steps:
5735 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5736 // narrowing and commutation of operands should be handled.
5737 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5739 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5740 // so the shuffle can be broken into other shuffles and the legalizer can
5741 // try the lowering again.
5743 // The general ideia is that no vector_shuffle operation should be left to
5744 // be matched during isel, all of them must be converted to a target specific
5747 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5748 // narrowing and commutation of operands should be handled. The actual code
5749 // doesn't include all of those, work in progress...
5750 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5751 if (NewOp.getNode())
5754 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5755 // unpckh_undef). Only use pshufd if speed is more important than size.
5756 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5757 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5758 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5759 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5760 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5761 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5763 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5764 RelaxedMayFoldVectorLoad(V1))
5765 return getMOVDDup(Op, dl, V1, DAG);
5767 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5768 return getMOVHighToLow(Op, dl, DAG);
5770 // Use to match splats
5771 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5772 (VT == MVT::v2f64 || VT == MVT::v2i64))
5773 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5775 if (X86::isPSHUFDMask(SVOp)) {
5776 // The actual implementation will match the mask in the if above and then
5777 // during isel it can match several different instructions, not only pshufd
5778 // as its name says, sad but true, emulate the behavior for now...
5779 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5780 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5782 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5784 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5785 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5787 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5788 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5791 if (VT == MVT::v4f32)
5792 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5796 // Check if this can be converted into a logical shift.
5797 bool isLeft = false;
5800 bool isShift = getSubtarget()->hasSSE2() &&
5801 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5802 if (isShift && ShVal.hasOneUse()) {
5803 // If the shifted value has multiple uses, it may be cheaper to use
5804 // v_set0 + movlhps or movhlps, etc.
5805 EVT EltVT = VT.getVectorElementType();
5806 ShAmt *= EltVT.getSizeInBits();
5807 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5810 if (X86::isMOVLMask(SVOp)) {
5813 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5814 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5815 if (!X86::isMOVLPMask(SVOp)) {
5816 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5817 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5819 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5820 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5824 // FIXME: fold these into legal mask.
5825 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5826 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5828 if (X86::isMOVHLPSMask(SVOp))
5829 return getMOVHighToLow(Op, dl, DAG);
5831 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5832 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5834 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5835 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5837 if (X86::isMOVLPMask(SVOp))
5838 return getMOVLP(Op, dl, DAG, HasSSE2);
5840 if (ShouldXformToMOVHLPS(SVOp) ||
5841 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5842 return CommuteVectorShuffle(SVOp, DAG);
5845 // No better options. Use a vshl / vsrl.
5846 EVT EltVT = VT.getVectorElementType();
5847 ShAmt *= EltVT.getSizeInBits();
5848 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5851 bool Commuted = false;
5852 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5853 // 1,1,1,1 -> v8i16 though.
5854 V1IsSplat = isSplatVector(V1.getNode());
5855 V2IsSplat = isSplatVector(V2.getNode());
5857 // Canonicalize the splat or undef, if present, to be on the RHS.
5858 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5859 Op = CommuteVectorShuffle(SVOp, DAG);
5860 SVOp = cast<ShuffleVectorSDNode>(Op);
5861 V1 = SVOp->getOperand(0);
5862 V2 = SVOp->getOperand(1);
5863 std::swap(V1IsSplat, V2IsSplat);
5864 std::swap(V1IsUndef, V2IsUndef);
5868 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5869 // Shuffling low element of v1 into undef, just return v1.
5872 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5873 // the instruction selector will not match, so get a canonical MOVL with
5874 // swapped operands to undo the commute.
5875 return getMOVL(DAG, dl, VT, V2, V1);
5878 if (X86::isUNPCKLMask(SVOp))
5879 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5880 dl, VT, V1, V2, DAG);
5882 if (X86::isUNPCKHMask(SVOp))
5883 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5886 // Normalize mask so all entries that point to V2 points to its first
5887 // element then try to match unpck{h|l} again. If match, return a
5888 // new vector_shuffle with the corrected mask.
5889 SDValue NewMask = NormalizeMask(SVOp, DAG);
5890 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5891 if (NSVOp != SVOp) {
5892 if (X86::isUNPCKLMask(NSVOp, true)) {
5894 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5901 // Commute is back and try unpck* again.
5902 // FIXME: this seems wrong.
5903 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5904 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5906 if (X86::isUNPCKLMask(NewSVOp))
5907 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5908 dl, VT, V2, V1, DAG);
5910 if (X86::isUNPCKHMask(NewSVOp))
5911 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5914 // Normalize the node to match x86 shuffle ops if needed
5915 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5916 return CommuteVectorShuffle(SVOp, DAG);
5918 // The checks below are all present in isShuffleMaskLegal, but they are
5919 // inlined here right now to enable us to directly emit target specific
5920 // nodes, and remove one by one until they don't return Op anymore.
5921 SmallVector<int, 16> M;
5924 if (isPALIGNRMask(M, VT, HasSSSE3))
5925 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5926 X86::getShufflePALIGNRImmediate(SVOp),
5929 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5930 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5931 if (VT == MVT::v2f64) {
5932 X86ISD::NodeType Opcode =
5933 getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5934 return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5936 if (VT == MVT::v2i64)
5937 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5940 if (isPSHUFHWMask(M, VT))
5941 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5942 X86::getShufflePSHUFHWImmediate(SVOp),
5945 if (isPSHUFLWMask(M, VT))
5946 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5947 X86::getShufflePSHUFLWImmediate(SVOp),
5950 if (isSHUFPMask(M, VT)) {
5951 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5952 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5953 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5955 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5956 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5960 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5961 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5962 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5963 dl, VT, V1, V1, DAG);
5964 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5965 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5966 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5968 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5969 if (VT == MVT::v8i16) {
5970 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5971 if (NewOp.getNode())
5975 if (VT == MVT::v16i8) {
5976 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5977 if (NewOp.getNode())
5981 // Handle all 4 wide cases with a number of shuffles.
5983 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5989 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5990 SelectionDAG &DAG) const {
5991 EVT VT = Op.getValueType();
5992 DebugLoc dl = Op.getDebugLoc();
5993 if (VT.getSizeInBits() == 8) {
5994 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5995 Op.getOperand(0), Op.getOperand(1));
5996 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5997 DAG.getValueType(VT));
5998 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5999 } else if (VT.getSizeInBits() == 16) {
6000 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6001 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6003 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6004 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6005 DAG.getNode(ISD::BITCAST, dl,
6009 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6010 Op.getOperand(0), Op.getOperand(1));
6011 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6012 DAG.getValueType(VT));
6013 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6014 } else if (VT == MVT::f32) {
6015 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6016 // the result back to FR32 register. It's only worth matching if the
6017 // result has a single use which is a store or a bitcast to i32. And in
6018 // the case of a store, it's not worth it if the index is a constant 0,
6019 // because a MOVSSmr can be used instead, which is smaller and faster.
6020 if (!Op.hasOneUse())
6022 SDNode *User = *Op.getNode()->use_begin();
6023 if ((User->getOpcode() != ISD::STORE ||
6024 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6025 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6026 (User->getOpcode() != ISD::BITCAST ||
6027 User->getValueType(0) != MVT::i32))
6029 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6030 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6033 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6034 } else if (VT == MVT::i32) {
6035 // ExtractPS works with constant index.
6036 if (isa<ConstantSDNode>(Op.getOperand(1)))
6044 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6045 SelectionDAG &DAG) const {
6046 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6049 SDValue Vec = Op.getOperand(0);
6050 EVT VecVT = Vec.getValueType();
6052 // If this is a 256-bit vector result, first extract the 128-bit
6053 // vector and then extract from the 128-bit vector.
6054 if (VecVT.getSizeInBits() > 128) {
6055 DebugLoc dl = Op.getNode()->getDebugLoc();
6056 unsigned NumElems = VecVT.getVectorNumElements();
6057 SDValue Idx = Op.getOperand(1);
6059 if (!isa<ConstantSDNode>(Idx))
6062 unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6063 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6065 // Get the 128-bit vector.
6066 bool Upper = IdxVal >= ExtractNumElems;
6067 Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6070 SDValue ScaledIdx = Idx;
6072 ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6073 DAG.getConstant(ExtractNumElems,
6074 Idx.getValueType()));
6075 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6079 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6081 if (Subtarget->hasSSE41()) {
6082 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6087 EVT VT = Op.getValueType();
6088 DebugLoc dl = Op.getDebugLoc();
6089 // TODO: handle v16i8.
6090 if (VT.getSizeInBits() == 16) {
6091 SDValue Vec = Op.getOperand(0);
6092 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6094 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6095 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6096 DAG.getNode(ISD::BITCAST, dl,
6099 // Transform it so it match pextrw which produces a 32-bit result.
6100 EVT EltVT = MVT::i32;
6101 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6102 Op.getOperand(0), Op.getOperand(1));
6103 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6104 DAG.getValueType(VT));
6105 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6106 } else if (VT.getSizeInBits() == 32) {
6107 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6111 // SHUFPS the element to the lowest double word, then movss.
6112 int Mask[4] = { Idx, -1, -1, -1 };
6113 EVT VVT = Op.getOperand(0).getValueType();
6114 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6115 DAG.getUNDEF(VVT), Mask);
6116 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6117 DAG.getIntPtrConstant(0));
6118 } else if (VT.getSizeInBits() == 64) {
6119 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6120 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6121 // to match extract_elt for f64.
6122 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6126 // UNPCKHPD the element to the lowest double word, then movsd.
6127 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6128 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6129 int Mask[2] = { 1, -1 };
6130 EVT VVT = Op.getOperand(0).getValueType();
6131 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6132 DAG.getUNDEF(VVT), Mask);
6133 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6134 DAG.getIntPtrConstant(0));
6141 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6142 SelectionDAG &DAG) const {
6143 EVT VT = Op.getValueType();
6144 EVT EltVT = VT.getVectorElementType();
6145 DebugLoc dl = Op.getDebugLoc();
6147 SDValue N0 = Op.getOperand(0);
6148 SDValue N1 = Op.getOperand(1);
6149 SDValue N2 = Op.getOperand(2);
6151 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6152 isa<ConstantSDNode>(N2)) {
6154 if (VT == MVT::v8i16)
6155 Opc = X86ISD::PINSRW;
6156 else if (VT == MVT::v16i8)
6157 Opc = X86ISD::PINSRB;
6159 Opc = X86ISD::PINSRB;
6161 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6163 if (N1.getValueType() != MVT::i32)
6164 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6165 if (N2.getValueType() != MVT::i32)
6166 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6167 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6168 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6169 // Bits [7:6] of the constant are the source select. This will always be
6170 // zero here. The DAG Combiner may combine an extract_elt index into these
6171 // bits. For example (insert (extract, 3), 2) could be matched by putting
6172 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6173 // Bits [5:4] of the constant are the destination select. This is the
6174 // value of the incoming immediate.
6175 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6176 // combine either bitwise AND or insert of float 0.0 to set these bits.
6177 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6178 // Create this as a scalar to vector..
6179 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6180 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6181 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6182 // PINSR* works with constant index.
6189 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6190 EVT VT = Op.getValueType();
6191 EVT EltVT = VT.getVectorElementType();
6193 DebugLoc dl = Op.getDebugLoc();
6194 SDValue N0 = Op.getOperand(0);
6195 SDValue N1 = Op.getOperand(1);
6196 SDValue N2 = Op.getOperand(2);
6198 // If this is a 256-bit vector result, first insert into a 128-bit
6199 // vector and then insert into the 256-bit vector.
6200 if (VT.getSizeInBits() > 128) {
6201 if (!isa<ConstantSDNode>(N2))
6204 // Get the 128-bit vector.
6205 unsigned NumElems = VT.getVectorNumElements();
6206 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6207 bool Upper = IdxVal >= NumElems / 2;
6209 SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6212 SDValue ScaledN2 = N2;
6214 ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6215 DAG.getConstant(NumElems /
6216 (VT.getSizeInBits() / 128),
6217 N2.getValueType()));
6218 Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6221 // Insert the 128-bit vector
6222 // FIXME: Why UNDEF?
6223 return Insert128BitVector(N0, Op, N2, DAG, dl);
6226 if (Subtarget->hasSSE41())
6227 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6229 if (EltVT == MVT::i8)
6232 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6233 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6234 // as its second argument.
6235 if (N1.getValueType() != MVT::i32)
6236 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6237 if (N2.getValueType() != MVT::i32)
6238 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6239 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6245 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6246 LLVMContext *Context = DAG.getContext();
6247 DebugLoc dl = Op.getDebugLoc();
6248 EVT OpVT = Op.getValueType();
6250 // If this is a 256-bit vector result, first insert into a 128-bit
6251 // vector and then insert into the 256-bit vector.
6252 if (OpVT.getSizeInBits() > 128) {
6253 // Insert into a 128-bit vector.
6254 EVT VT128 = EVT::getVectorVT(*Context,
6255 OpVT.getVectorElementType(),
6256 OpVT.getVectorNumElements() / 2);
6258 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6260 // Insert the 128-bit vector.
6261 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6262 DAG.getConstant(0, MVT::i32),
6266 if (Op.getValueType() == MVT::v1i64 &&
6267 Op.getOperand(0).getValueType() == MVT::i64)
6268 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6270 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6271 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6272 "Expected an SSE type!");
6273 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6274 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6277 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
6278 // a simple subregister reference or explicit instructions to grab
6279 // upper bits of a vector.
6281 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6282 if (Subtarget->hasAVX()) {
6283 DebugLoc dl = Op.getNode()->getDebugLoc();
6284 SDValue Vec = Op.getNode()->getOperand(0);
6285 SDValue Idx = Op.getNode()->getOperand(1);
6287 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6288 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6289 return Extract128BitVector(Vec, Idx, DAG, dl);
6295 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
6296 // simple superregister reference or explicit instructions to insert
6297 // the upper bits of a vector.
6299 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6300 if (Subtarget->hasAVX()) {
6301 DebugLoc dl = Op.getNode()->getDebugLoc();
6302 SDValue Vec = Op.getNode()->getOperand(0);
6303 SDValue SubVec = Op.getNode()->getOperand(1);
6304 SDValue Idx = Op.getNode()->getOperand(2);
6306 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6307 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6308 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6314 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6315 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6316 // one of the above mentioned nodes. It has to be wrapped because otherwise
6317 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6318 // be used to form addressing mode. These wrapped nodes will be selected
6321 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6322 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6324 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6326 unsigned char OpFlag = 0;
6327 unsigned WrapperKind = X86ISD::Wrapper;
6328 CodeModel::Model M = getTargetMachine().getCodeModel();
6330 if (Subtarget->isPICStyleRIPRel() &&
6331 (M == CodeModel::Small || M == CodeModel::Kernel))
6332 WrapperKind = X86ISD::WrapperRIP;
6333 else if (Subtarget->isPICStyleGOT())
6334 OpFlag = X86II::MO_GOTOFF;
6335 else if (Subtarget->isPICStyleStubPIC())
6336 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6338 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6340 CP->getOffset(), OpFlag);
6341 DebugLoc DL = CP->getDebugLoc();
6342 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6343 // With PIC, the address is actually $g + Offset.
6345 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6346 DAG.getNode(X86ISD::GlobalBaseReg,
6347 DebugLoc(), getPointerTy()),
6354 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6355 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6357 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6359 unsigned char OpFlag = 0;
6360 unsigned WrapperKind = X86ISD::Wrapper;
6361 CodeModel::Model M = getTargetMachine().getCodeModel();
6363 if (Subtarget->isPICStyleRIPRel() &&
6364 (M == CodeModel::Small || M == CodeModel::Kernel))
6365 WrapperKind = X86ISD::WrapperRIP;
6366 else if (Subtarget->isPICStyleGOT())
6367 OpFlag = X86II::MO_GOTOFF;
6368 else if (Subtarget->isPICStyleStubPIC())
6369 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6371 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6373 DebugLoc DL = JT->getDebugLoc();
6374 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6376 // With PIC, the address is actually $g + Offset.
6378 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6379 DAG.getNode(X86ISD::GlobalBaseReg,
6380 DebugLoc(), getPointerTy()),
6387 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6388 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6390 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6392 unsigned char OpFlag = 0;
6393 unsigned WrapperKind = X86ISD::Wrapper;
6394 CodeModel::Model M = getTargetMachine().getCodeModel();
6396 if (Subtarget->isPICStyleRIPRel() &&
6397 (M == CodeModel::Small || M == CodeModel::Kernel))
6398 WrapperKind = X86ISD::WrapperRIP;
6399 else if (Subtarget->isPICStyleGOT())
6400 OpFlag = X86II::MO_GOTOFF;
6401 else if (Subtarget->isPICStyleStubPIC())
6402 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6404 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6406 DebugLoc DL = Op.getDebugLoc();
6407 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6410 // With PIC, the address is actually $g + Offset.
6411 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6412 !Subtarget->is64Bit()) {
6413 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6414 DAG.getNode(X86ISD::GlobalBaseReg,
6415 DebugLoc(), getPointerTy()),
6423 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6424 // Create the TargetBlockAddressAddress node.
6425 unsigned char OpFlags =
6426 Subtarget->ClassifyBlockAddressReference();
6427 CodeModel::Model M = getTargetMachine().getCodeModel();
6428 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6429 DebugLoc dl = Op.getDebugLoc();
6430 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6431 /*isTarget=*/true, OpFlags);
6433 if (Subtarget->isPICStyleRIPRel() &&
6434 (M == CodeModel::Small || M == CodeModel::Kernel))
6435 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6437 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6439 // With PIC, the address is actually $g + Offset.
6440 if (isGlobalRelativeToPICBase(OpFlags)) {
6441 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6442 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6450 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6452 SelectionDAG &DAG) const {
6453 // Create the TargetGlobalAddress node, folding in the constant
6454 // offset if it is legal.
6455 unsigned char OpFlags =
6456 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6457 CodeModel::Model M = getTargetMachine().getCodeModel();
6459 if (OpFlags == X86II::MO_NO_FLAG &&
6460 X86::isOffsetSuitableForCodeModel(Offset, M)) {
6461 // A direct static reference to a global.
6462 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6465 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6468 if (Subtarget->isPICStyleRIPRel() &&
6469 (M == CodeModel::Small || M == CodeModel::Kernel))
6470 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6472 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6474 // With PIC, the address is actually $g + Offset.
6475 if (isGlobalRelativeToPICBase(OpFlags)) {
6476 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6477 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6481 // For globals that require a load from a stub to get the address, emit the
6483 if (isGlobalStubReference(OpFlags))
6484 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6485 MachinePointerInfo::getGOT(), false, false, 0);
6487 // If there was a non-zero offset that we didn't fold, create an explicit
6490 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6491 DAG.getConstant(Offset, getPointerTy()));
6497 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6498 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6499 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6500 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6504 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6505 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6506 unsigned char OperandFlags) {
6507 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6508 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6509 DebugLoc dl = GA->getDebugLoc();
6510 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6511 GA->getValueType(0),
6515 SDValue Ops[] = { Chain, TGA, *InFlag };
6516 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6518 SDValue Ops[] = { Chain, TGA };
6519 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6522 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6523 MFI->setAdjustsStack(true);
6525 SDValue Flag = Chain.getValue(1);
6526 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6529 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6531 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6534 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6535 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6536 DAG.getNode(X86ISD::GlobalBaseReg,
6537 DebugLoc(), PtrVT), InFlag);
6538 InFlag = Chain.getValue(1);
6540 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6543 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6545 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6547 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6548 X86::RAX, X86II::MO_TLSGD);
6551 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6552 // "local exec" model.
6553 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6554 const EVT PtrVT, TLSModel::Model model,
6556 DebugLoc dl = GA->getDebugLoc();
6558 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6559 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6560 is64Bit ? 257 : 256));
6562 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6563 DAG.getIntPtrConstant(0),
6564 MachinePointerInfo(Ptr), false, false, 0);
6566 unsigned char OperandFlags = 0;
6567 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6569 unsigned WrapperKind = X86ISD::Wrapper;
6570 if (model == TLSModel::LocalExec) {
6571 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6572 } else if (is64Bit) {
6573 assert(model == TLSModel::InitialExec);
6574 OperandFlags = X86II::MO_GOTTPOFF;
6575 WrapperKind = X86ISD::WrapperRIP;
6577 assert(model == TLSModel::InitialExec);
6578 OperandFlags = X86II::MO_INDNTPOFF;
6581 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6583 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6584 GA->getValueType(0),
6585 GA->getOffset(), OperandFlags);
6586 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6588 if (model == TLSModel::InitialExec)
6589 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6590 MachinePointerInfo::getGOT(), false, false, 0);
6592 // The address of the thread local variable is the add of the thread
6593 // pointer with the offset of the variable.
6594 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6598 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6600 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6601 const GlobalValue *GV = GA->getGlobal();
6603 if (Subtarget->isTargetELF()) {
6604 // TODO: implement the "local dynamic" model
6605 // TODO: implement the "initial exec"model for pic executables
6607 // If GV is an alias then use the aliasee for determining
6608 // thread-localness.
6609 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6610 GV = GA->resolveAliasedGlobal(false);
6612 TLSModel::Model model
6613 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6616 case TLSModel::GeneralDynamic:
6617 case TLSModel::LocalDynamic: // not implemented
6618 if (Subtarget->is64Bit())
6619 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6620 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6622 case TLSModel::InitialExec:
6623 case TLSModel::LocalExec:
6624 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6625 Subtarget->is64Bit());
6627 } else if (Subtarget->isTargetDarwin()) {
6628 // Darwin only has one model of TLS. Lower to that.
6629 unsigned char OpFlag = 0;
6630 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6631 X86ISD::WrapperRIP : X86ISD::Wrapper;
6633 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6635 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6636 !Subtarget->is64Bit();
6638 OpFlag = X86II::MO_TLVP_PIC_BASE;
6640 OpFlag = X86II::MO_TLVP;
6641 DebugLoc DL = Op.getDebugLoc();
6642 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6643 GA->getValueType(0),
6644 GA->getOffset(), OpFlag);
6645 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6647 // With PIC32, the address is actually $g + Offset.
6649 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6650 DAG.getNode(X86ISD::GlobalBaseReg,
6651 DebugLoc(), getPointerTy()),
6654 // Lowering the machine isd will make sure everything is in the right
6656 SDValue Chain = DAG.getEntryNode();
6657 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6658 SDValue Args[] = { Chain, Offset };
6659 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6661 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6662 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6663 MFI->setAdjustsStack(true);
6665 // And our return value (tls address) is in the standard call return value
6667 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6668 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6672 "TLS not implemented for this target.");
6674 llvm_unreachable("Unreachable");
6679 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6680 /// take a 2 x i32 value to shift plus a shift amount.
6681 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6682 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6683 EVT VT = Op.getValueType();
6684 unsigned VTBits = VT.getSizeInBits();
6685 DebugLoc dl = Op.getDebugLoc();
6686 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6687 SDValue ShOpLo = Op.getOperand(0);
6688 SDValue ShOpHi = Op.getOperand(1);
6689 SDValue ShAmt = Op.getOperand(2);
6690 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6691 DAG.getConstant(VTBits - 1, MVT::i8))
6692 : DAG.getConstant(0, VT);
6695 if (Op.getOpcode() == ISD::SHL_PARTS) {
6696 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6697 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6699 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6700 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6703 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6704 DAG.getConstant(VTBits, MVT::i8));
6705 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6706 AndNode, DAG.getConstant(0, MVT::i8));
6709 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6710 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6711 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6713 if (Op.getOpcode() == ISD::SHL_PARTS) {
6714 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6715 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6717 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6718 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6721 SDValue Ops[2] = { Lo, Hi };
6722 return DAG.getMergeValues(Ops, 2, dl);
6725 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6726 SelectionDAG &DAG) const {
6727 EVT SrcVT = Op.getOperand(0).getValueType();
6729 if (SrcVT.isVector())
6732 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6733 "Unknown SINT_TO_FP to lower!");
6735 // These are really Legal; return the operand so the caller accepts it as
6737 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6739 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6740 Subtarget->is64Bit()) {
6744 DebugLoc dl = Op.getDebugLoc();
6745 unsigned Size = SrcVT.getSizeInBits()/8;
6746 MachineFunction &MF = DAG.getMachineFunction();
6747 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6748 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6749 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6751 MachinePointerInfo::getFixedStack(SSFI),
6753 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6756 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6758 SelectionDAG &DAG) const {
6760 DebugLoc DL = Op.getDebugLoc();
6762 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6764 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6766 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6768 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6770 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
6771 MachineMemOperand *MMO;
6773 int SSFI = FI->getIndex();
6775 DAG.getMachineFunction()
6776 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6777 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6779 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
6780 StackSlot = StackSlot.getOperand(1);
6782 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6783 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6785 Tys, Ops, array_lengthof(Ops),
6789 Chain = Result.getValue(1);
6790 SDValue InFlag = Result.getValue(2);
6792 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6793 // shouldn't be necessary except that RFP cannot be live across
6794 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6795 MachineFunction &MF = DAG.getMachineFunction();
6796 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6797 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6798 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6799 Tys = DAG.getVTList(MVT::Other);
6801 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6803 MachineMemOperand *MMO =
6804 DAG.getMachineFunction()
6805 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6806 MachineMemOperand::MOStore, SSFISize, SSFISize);
6808 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6809 Ops, array_lengthof(Ops),
6810 Op.getValueType(), MMO);
6811 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6812 MachinePointerInfo::getFixedStack(SSFI),
6819 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6820 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6821 SelectionDAG &DAG) const {
6822 // This algorithm is not obvious. Here it is in C code, more or less:
6824 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6825 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6826 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6828 // Copy ints to xmm registers.
6829 __m128i xh = _mm_cvtsi32_si128( hi );
6830 __m128i xl = _mm_cvtsi32_si128( lo );
6832 // Combine into low half of a single xmm register.
6833 __m128i x = _mm_unpacklo_epi32( xh, xl );
6837 // Merge in appropriate exponents to give the integer bits the right
6839 x = _mm_unpacklo_epi32( x, exp );
6841 // Subtract away the biases to deal with the IEEE-754 double precision
6843 d = _mm_sub_pd( (__m128d) x, bias );
6845 // All conversions up to here are exact. The correctly rounded result is
6846 // calculated using the current rounding mode using the following
6848 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6849 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6850 // store doesn't really need to be here (except
6851 // maybe to zero the other double)
6856 DebugLoc dl = Op.getDebugLoc();
6857 LLVMContext *Context = DAG.getContext();
6859 // Build some magic constants.
6860 std::vector<Constant*> CV0;
6861 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6862 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6863 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6864 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6865 Constant *C0 = ConstantVector::get(CV0);
6866 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6868 std::vector<Constant*> CV1;
6870 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6872 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6873 Constant *C1 = ConstantVector::get(CV1);
6874 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6876 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6877 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6879 DAG.getIntPtrConstant(1)));
6880 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6881 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6883 DAG.getIntPtrConstant(0)));
6884 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6885 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6886 MachinePointerInfo::getConstantPool(),
6888 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6889 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6890 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6891 MachinePointerInfo::getConstantPool(),
6893 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6895 // Add the halves; easiest way is to swap them into another reg first.
6896 int ShufMask[2] = { 1, -1 };
6897 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6898 DAG.getUNDEF(MVT::v2f64), ShufMask);
6899 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6900 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6901 DAG.getIntPtrConstant(0));
6904 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6905 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6906 SelectionDAG &DAG) const {
6907 DebugLoc dl = Op.getDebugLoc();
6908 // FP constant to bias correct the final result.
6909 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6912 // Load the 32-bit value into an XMM register.
6913 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6914 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6916 DAG.getIntPtrConstant(0)));
6918 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6919 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6920 DAG.getIntPtrConstant(0));
6922 // Or the load with the bias.
6923 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6924 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6925 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6927 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6928 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6929 MVT::v2f64, Bias)));
6930 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6931 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6932 DAG.getIntPtrConstant(0));
6934 // Subtract the bias.
6935 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6937 // Handle final rounding.
6938 EVT DestVT = Op.getValueType();
6940 if (DestVT.bitsLT(MVT::f64)) {
6941 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6942 DAG.getIntPtrConstant(0));
6943 } else if (DestVT.bitsGT(MVT::f64)) {
6944 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6947 // Handle final rounding.
6951 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6952 SelectionDAG &DAG) const {
6953 SDValue N0 = Op.getOperand(0);
6954 DebugLoc dl = Op.getDebugLoc();
6956 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6957 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6958 // the optimization here.
6959 if (DAG.SignBitIsZero(N0))
6960 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6962 EVT SrcVT = N0.getValueType();
6963 EVT DstVT = Op.getValueType();
6964 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6965 return LowerUINT_TO_FP_i64(Op, DAG);
6966 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6967 return LowerUINT_TO_FP_i32(Op, DAG);
6969 // Make a 64-bit buffer, and use it to build an FILD.
6970 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6971 if (SrcVT == MVT::i32) {
6972 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6973 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6974 getPointerTy(), StackSlot, WordOff);
6975 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6976 StackSlot, MachinePointerInfo(),
6978 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6979 OffsetSlot, MachinePointerInfo(),
6981 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6985 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6986 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6987 StackSlot, MachinePointerInfo(),
6989 // For i64 source, we need to add the appropriate power of 2 if the input
6990 // was negative. This is the same as the optimization in
6991 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6992 // we must be careful to do the computation in x87 extended precision, not
6993 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6994 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6995 MachineMemOperand *MMO =
6996 DAG.getMachineFunction()
6997 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6998 MachineMemOperand::MOLoad, 8, 8);
7000 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7001 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7002 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7005 APInt FF(32, 0x5F800000ULL);
7007 // Check whether the sign bit is set.
7008 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7009 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7012 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7013 SDValue FudgePtr = DAG.getConstantPool(
7014 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7017 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7018 SDValue Zero = DAG.getIntPtrConstant(0);
7019 SDValue Four = DAG.getIntPtrConstant(4);
7020 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7022 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7024 // Load the value out, extending it from f32 to f80.
7025 // FIXME: Avoid the extend by constructing the right constant pool?
7026 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7027 FudgePtr, MachinePointerInfo::getConstantPool(),
7028 MVT::f32, false, false, 4);
7029 // Extend everything to 80 bits to force it to be done on x87.
7030 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7031 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7034 std::pair<SDValue,SDValue> X86TargetLowering::
7035 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7036 DebugLoc DL = Op.getDebugLoc();
7038 EVT DstTy = Op.getValueType();
7041 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7045 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7046 DstTy.getSimpleVT() >= MVT::i16 &&
7047 "Unknown FP_TO_SINT to lower!");
7049 // These are really Legal.
7050 if (DstTy == MVT::i32 &&
7051 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7052 return std::make_pair(SDValue(), SDValue());
7053 if (Subtarget->is64Bit() &&
7054 DstTy == MVT::i64 &&
7055 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7056 return std::make_pair(SDValue(), SDValue());
7058 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7060 MachineFunction &MF = DAG.getMachineFunction();
7061 unsigned MemSize = DstTy.getSizeInBits()/8;
7062 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7063 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7068 switch (DstTy.getSimpleVT().SimpleTy) {
7069 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7070 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7071 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7072 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7075 SDValue Chain = DAG.getEntryNode();
7076 SDValue Value = Op.getOperand(0);
7077 EVT TheVT = Op.getOperand(0).getValueType();
7078 if (isScalarFPTypeInSSEReg(TheVT)) {
7079 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7080 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7081 MachinePointerInfo::getFixedStack(SSFI),
7083 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7085 Chain, StackSlot, DAG.getValueType(TheVT)
7088 MachineMemOperand *MMO =
7089 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7090 MachineMemOperand::MOLoad, MemSize, MemSize);
7091 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7093 Chain = Value.getValue(1);
7094 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7095 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7098 MachineMemOperand *MMO =
7099 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7100 MachineMemOperand::MOStore, MemSize, MemSize);
7102 // Build the FP_TO_INT*_IN_MEM
7103 SDValue Ops[] = { Chain, Value, StackSlot };
7104 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7105 Ops, 3, DstTy, MMO);
7107 return std::make_pair(FIST, StackSlot);
7110 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7111 SelectionDAG &DAG) const {
7112 if (Op.getValueType().isVector())
7115 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7116 SDValue FIST = Vals.first, StackSlot = Vals.second;
7117 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7118 if (FIST.getNode() == 0) return Op;
7121 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7122 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7125 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7126 SelectionDAG &DAG) const {
7127 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7128 SDValue FIST = Vals.first, StackSlot = Vals.second;
7129 assert(FIST.getNode() && "Unexpected failure");
7132 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7133 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7136 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7137 SelectionDAG &DAG) const {
7138 LLVMContext *Context = DAG.getContext();
7139 DebugLoc dl = Op.getDebugLoc();
7140 EVT VT = Op.getValueType();
7143 EltVT = VT.getVectorElementType();
7144 std::vector<Constant*> CV;
7145 if (EltVT == MVT::f64) {
7146 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7150 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7156 Constant *C = ConstantVector::get(CV);
7157 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7158 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7159 MachinePointerInfo::getConstantPool(),
7161 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7164 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7165 LLVMContext *Context = DAG.getContext();
7166 DebugLoc dl = Op.getDebugLoc();
7167 EVT VT = Op.getValueType();
7170 EltVT = VT.getVectorElementType();
7171 std::vector<Constant*> CV;
7172 if (EltVT == MVT::f64) {
7173 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7177 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7183 Constant *C = ConstantVector::get(CV);
7184 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7185 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7186 MachinePointerInfo::getConstantPool(),
7188 if (VT.isVector()) {
7189 return DAG.getNode(ISD::BITCAST, dl, VT,
7190 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7191 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7193 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7195 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7199 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7200 LLVMContext *Context = DAG.getContext();
7201 SDValue Op0 = Op.getOperand(0);
7202 SDValue Op1 = Op.getOperand(1);
7203 DebugLoc dl = Op.getDebugLoc();
7204 EVT VT = Op.getValueType();
7205 EVT SrcVT = Op1.getValueType();
7207 // If second operand is smaller, extend it first.
7208 if (SrcVT.bitsLT(VT)) {
7209 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7212 // And if it is bigger, shrink it first.
7213 if (SrcVT.bitsGT(VT)) {
7214 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7218 // At this point the operands and the result should have the same
7219 // type, and that won't be f80 since that is not custom lowered.
7221 // First get the sign bit of second operand.
7222 std::vector<Constant*> CV;
7223 if (SrcVT == MVT::f64) {
7224 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7225 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7227 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7228 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7229 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7230 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7232 Constant *C = ConstantVector::get(CV);
7233 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7234 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7235 MachinePointerInfo::getConstantPool(),
7237 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7239 // Shift sign bit right or left if the two operands have different types.
7240 if (SrcVT.bitsGT(VT)) {
7241 // Op0 is MVT::f32, Op1 is MVT::f64.
7242 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7243 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7244 DAG.getConstant(32, MVT::i32));
7245 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7246 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7247 DAG.getIntPtrConstant(0));
7250 // Clear first operand sign bit.
7252 if (VT == MVT::f64) {
7253 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7254 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7256 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7257 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7258 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7259 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7261 C = ConstantVector::get(CV);
7262 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7263 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7264 MachinePointerInfo::getConstantPool(),
7266 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7268 // Or the value with the sign bit.
7269 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7272 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7273 SDValue N0 = Op.getOperand(0);
7274 DebugLoc dl = Op.getDebugLoc();
7275 EVT VT = Op.getValueType();
7277 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7278 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7279 DAG.getConstant(1, VT));
7280 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7283 /// Emit nodes that will be selected as "test Op0,Op0", or something
7285 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7286 SelectionDAG &DAG) const {
7287 DebugLoc dl = Op.getDebugLoc();
7289 // CF and OF aren't always set the way we want. Determine which
7290 // of these we need.
7291 bool NeedCF = false;
7292 bool NeedOF = false;
7295 case X86::COND_A: case X86::COND_AE:
7296 case X86::COND_B: case X86::COND_BE:
7299 case X86::COND_G: case X86::COND_GE:
7300 case X86::COND_L: case X86::COND_LE:
7301 case X86::COND_O: case X86::COND_NO:
7306 // See if we can use the EFLAGS value from the operand instead of
7307 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7308 // we prove that the arithmetic won't overflow, we can't use OF or CF.
7309 if (Op.getResNo() != 0 || NeedOF || NeedCF)
7310 // Emit a CMP with 0, which is the TEST pattern.
7311 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7312 DAG.getConstant(0, Op.getValueType()));
7314 unsigned Opcode = 0;
7315 unsigned NumOperands = 0;
7316 switch (Op.getNode()->getOpcode()) {
7318 // Due to an isel shortcoming, be conservative if this add is likely to be
7319 // selected as part of a load-modify-store instruction. When the root node
7320 // in a match is a store, isel doesn't know how to remap non-chain non-flag
7321 // uses of other nodes in the match, such as the ADD in this case. This
7322 // leads to the ADD being left around and reselected, with the result being
7323 // two adds in the output. Alas, even if none our users are stores, that
7324 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
7325 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
7326 // climbing the DAG back to the root, and it doesn't seem to be worth the
7328 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7329 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7330 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7333 if (ConstantSDNode *C =
7334 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7335 // An add of one will be selected as an INC.
7336 if (C->getAPIntValue() == 1) {
7337 Opcode = X86ISD::INC;
7342 // An add of negative one (subtract of one) will be selected as a DEC.
7343 if (C->getAPIntValue().isAllOnesValue()) {
7344 Opcode = X86ISD::DEC;
7350 // Otherwise use a regular EFLAGS-setting add.
7351 Opcode = X86ISD::ADD;
7355 // If the primary and result isn't used, don't bother using X86ISD::AND,
7356 // because a TEST instruction will be better.
7357 bool NonFlagUse = false;
7358 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7359 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7361 unsigned UOpNo = UI.getOperandNo();
7362 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7363 // Look pass truncate.
7364 UOpNo = User->use_begin().getOperandNo();
7365 User = *User->use_begin();
7368 if (User->getOpcode() != ISD::BRCOND &&
7369 User->getOpcode() != ISD::SETCC &&
7370 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7383 // Due to the ISEL shortcoming noted above, be conservative if this op is
7384 // likely to be selected as part of a load-modify-store instruction.
7385 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7386 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7387 if (UI->getOpcode() == ISD::STORE)
7390 // Otherwise use a regular EFLAGS-setting instruction.
7391 switch (Op.getNode()->getOpcode()) {
7392 default: llvm_unreachable("unexpected operator!");
7393 case ISD::SUB: Opcode = X86ISD::SUB; break;
7394 case ISD::OR: Opcode = X86ISD::OR; break;
7395 case ISD::XOR: Opcode = X86ISD::XOR; break;
7396 case ISD::AND: Opcode = X86ISD::AND; break;
7408 return SDValue(Op.getNode(), 1);
7415 // Emit a CMP with 0, which is the TEST pattern.
7416 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7417 DAG.getConstant(0, Op.getValueType()));
7419 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7420 SmallVector<SDValue, 4> Ops;
7421 for (unsigned i = 0; i != NumOperands; ++i)
7422 Ops.push_back(Op.getOperand(i));
7424 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7425 DAG.ReplaceAllUsesWith(Op, New);
7426 return SDValue(New.getNode(), 1);
7429 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7431 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7432 SelectionDAG &DAG) const {
7433 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7434 if (C->getAPIntValue() == 0)
7435 return EmitTest(Op0, X86CC, DAG);
7437 DebugLoc dl = Op0.getDebugLoc();
7438 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7441 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7442 /// if it's possible.
7443 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7444 DebugLoc dl, SelectionDAG &DAG) const {
7445 SDValue Op0 = And.getOperand(0);
7446 SDValue Op1 = And.getOperand(1);
7447 if (Op0.getOpcode() == ISD::TRUNCATE)
7448 Op0 = Op0.getOperand(0);
7449 if (Op1.getOpcode() == ISD::TRUNCATE)
7450 Op1 = Op1.getOperand(0);
7453 if (Op1.getOpcode() == ISD::SHL)
7454 std::swap(Op0, Op1);
7455 if (Op0.getOpcode() == ISD::SHL) {
7456 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7457 if (And00C->getZExtValue() == 1) {
7458 // If we looked past a truncate, check that it's only truncating away
7460 unsigned BitWidth = Op0.getValueSizeInBits();
7461 unsigned AndBitWidth = And.getValueSizeInBits();
7462 if (BitWidth > AndBitWidth) {
7463 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7464 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7465 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7469 RHS = Op0.getOperand(1);
7471 } else if (Op1.getOpcode() == ISD::Constant) {
7472 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7473 SDValue AndLHS = Op0;
7474 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7475 LHS = AndLHS.getOperand(0);
7476 RHS = AndLHS.getOperand(1);
7480 if (LHS.getNode()) {
7481 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
7482 // instruction. Since the shift amount is in-range-or-undefined, we know
7483 // that doing a bittest on the i32 value is ok. We extend to i32 because
7484 // the encoding for the i16 version is larger than the i32 version.
7485 // Also promote i16 to i32 for performance / code size reason.
7486 if (LHS.getValueType() == MVT::i8 ||
7487 LHS.getValueType() == MVT::i16)
7488 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7490 // If the operand types disagree, extend the shift amount to match. Since
7491 // BT ignores high bits (like shifts) we can use anyextend.
7492 if (LHS.getValueType() != RHS.getValueType())
7493 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7495 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7496 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7497 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7498 DAG.getConstant(Cond, MVT::i8), BT);
7504 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7505 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7506 SDValue Op0 = Op.getOperand(0);
7507 SDValue Op1 = Op.getOperand(1);
7508 DebugLoc dl = Op.getDebugLoc();
7509 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7511 // Optimize to BT if possible.
7512 // Lower (X & (1 << N)) == 0 to BT(X, N).
7513 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7514 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7515 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7516 Op1.getOpcode() == ISD::Constant &&
7517 cast<ConstantSDNode>(Op1)->isNullValue() &&
7518 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7519 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7520 if (NewSetCC.getNode())
7524 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
7526 if (Op1.getOpcode() == ISD::Constant &&
7527 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7528 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7529 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7531 // If the input is a setcc, then reuse the input setcc or use a new one with
7532 // the inverted condition.
7533 if (Op0.getOpcode() == X86ISD::SETCC) {
7534 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7535 bool Invert = (CC == ISD::SETNE) ^
7536 cast<ConstantSDNode>(Op1)->isNullValue();
7537 if (!Invert) return Op0;
7539 CCode = X86::GetOppositeBranchCondition(CCode);
7540 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7541 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7545 bool isFP = Op1.getValueType().isFloatingPoint();
7546 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7547 if (X86CC == X86::COND_INVALID)
7550 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7551 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7552 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7555 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7557 SDValue Op0 = Op.getOperand(0);
7558 SDValue Op1 = Op.getOperand(1);
7559 SDValue CC = Op.getOperand(2);
7560 EVT VT = Op.getValueType();
7561 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7562 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7563 DebugLoc dl = Op.getDebugLoc();
7567 EVT VT0 = Op0.getValueType();
7568 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7569 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7572 switch (SetCCOpcode) {
7575 case ISD::SETEQ: SSECC = 0; break;
7577 case ISD::SETGT: Swap = true; // Fallthrough
7579 case ISD::SETOLT: SSECC = 1; break;
7581 case ISD::SETGE: Swap = true; // Fallthrough
7583 case ISD::SETOLE: SSECC = 2; break;
7584 case ISD::SETUO: SSECC = 3; break;
7586 case ISD::SETNE: SSECC = 4; break;
7587 case ISD::SETULE: Swap = true;
7588 case ISD::SETUGE: SSECC = 5; break;
7589 case ISD::SETULT: Swap = true;
7590 case ISD::SETUGT: SSECC = 6; break;
7591 case ISD::SETO: SSECC = 7; break;
7594 std::swap(Op0, Op1);
7596 // In the two special cases we can't handle, emit two comparisons.
7598 if (SetCCOpcode == ISD::SETUEQ) {
7600 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7601 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7602 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7604 else if (SetCCOpcode == ISD::SETONE) {
7606 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7607 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7608 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7610 llvm_unreachable("Illegal FP comparison");
7612 // Handle all other FP comparisons here.
7613 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7616 // We are handling one of the integer comparisons here. Since SSE only has
7617 // GT and EQ comparisons for integer, swapping operands and multiple
7618 // operations may be required for some comparisons.
7619 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7620 bool Swap = false, Invert = false, FlipSigns = false;
7622 switch (VT.getSimpleVT().SimpleTy) {
7624 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7625 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7626 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7627 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7630 switch (SetCCOpcode) {
7632 case ISD::SETNE: Invert = true;
7633 case ISD::SETEQ: Opc = EQOpc; break;
7634 case ISD::SETLT: Swap = true;
7635 case ISD::SETGT: Opc = GTOpc; break;
7636 case ISD::SETGE: Swap = true;
7637 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7638 case ISD::SETULT: Swap = true;
7639 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7640 case ISD::SETUGE: Swap = true;
7641 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7644 std::swap(Op0, Op1);
7646 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7647 // bits of the inputs before performing those operations.
7649 EVT EltVT = VT.getVectorElementType();
7650 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7652 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7653 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7655 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7656 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7659 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7661 // If the logical-not of the result is required, perform that now.
7663 Result = DAG.getNOT(dl, Result, VT);
7668 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7669 static bool isX86LogicalCmp(SDValue Op) {
7670 unsigned Opc = Op.getNode()->getOpcode();
7671 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7673 if (Op.getResNo() == 1 &&
7674 (Opc == X86ISD::ADD ||
7675 Opc == X86ISD::SUB ||
7676 Opc == X86ISD::ADC ||
7677 Opc == X86ISD::SBB ||
7678 Opc == X86ISD::SMUL ||
7679 Opc == X86ISD::UMUL ||
7680 Opc == X86ISD::INC ||
7681 Opc == X86ISD::DEC ||
7682 Opc == X86ISD::OR ||
7683 Opc == X86ISD::XOR ||
7684 Opc == X86ISD::AND))
7687 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7693 static bool isZero(SDValue V) {
7694 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7695 return C && C->isNullValue();
7698 static bool isAllOnes(SDValue V) {
7699 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7700 return C && C->isAllOnesValue();
7703 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7704 bool addTest = true;
7705 SDValue Cond = Op.getOperand(0);
7706 SDValue Op1 = Op.getOperand(1);
7707 SDValue Op2 = Op.getOperand(2);
7708 DebugLoc DL = Op.getDebugLoc();
7711 if (Cond.getOpcode() == ISD::SETCC) {
7712 SDValue NewCond = LowerSETCC(Cond, DAG);
7713 if (NewCond.getNode())
7717 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7718 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7719 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7720 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7721 if (Cond.getOpcode() == X86ISD::SETCC &&
7722 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7723 isZero(Cond.getOperand(1).getOperand(1))) {
7724 SDValue Cmp = Cond.getOperand(1);
7726 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7728 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7729 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7730 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7732 SDValue CmpOp0 = Cmp.getOperand(0);
7733 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7734 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7736 SDValue Res = // Res = 0 or -1.
7737 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7738 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7740 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7741 Res = DAG.getNOT(DL, Res, Res.getValueType());
7743 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7744 if (N2C == 0 || !N2C->isNullValue())
7745 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7750 // Look past (and (setcc_carry (cmp ...)), 1).
7751 if (Cond.getOpcode() == ISD::AND &&
7752 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7753 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7754 if (C && C->getAPIntValue() == 1)
7755 Cond = Cond.getOperand(0);
7758 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7759 // setting operand in place of the X86ISD::SETCC.
7760 if (Cond.getOpcode() == X86ISD::SETCC ||
7761 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7762 CC = Cond.getOperand(0);
7764 SDValue Cmp = Cond.getOperand(1);
7765 unsigned Opc = Cmp.getOpcode();
7766 EVT VT = Op.getValueType();
7768 bool IllegalFPCMov = false;
7769 if (VT.isFloatingPoint() && !VT.isVector() &&
7770 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7771 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7773 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7774 Opc == X86ISD::BT) { // FIXME
7781 // Look pass the truncate.
7782 if (Cond.getOpcode() == ISD::TRUNCATE)
7783 Cond = Cond.getOperand(0);
7785 // We know the result of AND is compared against zero. Try to match
7787 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7788 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7789 if (NewSetCC.getNode()) {
7790 CC = NewSetCC.getOperand(0);
7791 Cond = NewSetCC.getOperand(1);
7798 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7799 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7802 // a < b ? -1 : 0 -> RES = ~setcc_carry
7803 // a < b ? 0 : -1 -> RES = setcc_carry
7804 // a >= b ? -1 : 0 -> RES = setcc_carry
7805 // a >= b ? 0 : -1 -> RES = ~setcc_carry
7806 if (Cond.getOpcode() == X86ISD::CMP) {
7807 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7809 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7810 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7811 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7812 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7813 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7814 return DAG.getNOT(DL, Res, Res.getValueType());
7819 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7820 // condition is true.
7821 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7822 SDValue Ops[] = { Op2, Op1, CC, Cond };
7823 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7826 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7827 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7828 // from the AND / OR.
7829 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7830 Opc = Op.getOpcode();
7831 if (Opc != ISD::OR && Opc != ISD::AND)
7833 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7834 Op.getOperand(0).hasOneUse() &&
7835 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7836 Op.getOperand(1).hasOneUse());
7839 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7840 // 1 and that the SETCC node has a single use.
7841 static bool isXor1OfSetCC(SDValue Op) {
7842 if (Op.getOpcode() != ISD::XOR)
7844 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7845 if (N1C && N1C->getAPIntValue() == 1) {
7846 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7847 Op.getOperand(0).hasOneUse();
7852 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7853 bool addTest = true;
7854 SDValue Chain = Op.getOperand(0);
7855 SDValue Cond = Op.getOperand(1);
7856 SDValue Dest = Op.getOperand(2);
7857 DebugLoc dl = Op.getDebugLoc();
7860 if (Cond.getOpcode() == ISD::SETCC) {
7861 SDValue NewCond = LowerSETCC(Cond, DAG);
7862 if (NewCond.getNode())
7866 // FIXME: LowerXALUO doesn't handle these!!
7867 else if (Cond.getOpcode() == X86ISD::ADD ||
7868 Cond.getOpcode() == X86ISD::SUB ||
7869 Cond.getOpcode() == X86ISD::SMUL ||
7870 Cond.getOpcode() == X86ISD::UMUL)
7871 Cond = LowerXALUO(Cond, DAG);
7874 // Look pass (and (setcc_carry (cmp ...)), 1).
7875 if (Cond.getOpcode() == ISD::AND &&
7876 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7877 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7878 if (C && C->getAPIntValue() == 1)
7879 Cond = Cond.getOperand(0);
7882 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7883 // setting operand in place of the X86ISD::SETCC.
7884 if (Cond.getOpcode() == X86ISD::SETCC ||
7885 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7886 CC = Cond.getOperand(0);
7888 SDValue Cmp = Cond.getOperand(1);
7889 unsigned Opc = Cmp.getOpcode();
7890 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7891 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7895 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7899 // These can only come from an arithmetic instruction with overflow,
7900 // e.g. SADDO, UADDO.
7901 Cond = Cond.getNode()->getOperand(1);
7908 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7909 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7910 if (CondOpc == ISD::OR) {
7911 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7912 // two branches instead of an explicit OR instruction with a
7914 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7915 isX86LogicalCmp(Cmp)) {
7916 CC = Cond.getOperand(0).getOperand(0);
7917 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7918 Chain, Dest, CC, Cmp);
7919 CC = Cond.getOperand(1).getOperand(0);
7923 } else { // ISD::AND
7924 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7925 // two branches instead of an explicit AND instruction with a
7926 // separate test. However, we only do this if this block doesn't
7927 // have a fall-through edge, because this requires an explicit
7928 // jmp when the condition is false.
7929 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7930 isX86LogicalCmp(Cmp) &&
7931 Op.getNode()->hasOneUse()) {
7932 X86::CondCode CCode =
7933 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7934 CCode = X86::GetOppositeBranchCondition(CCode);
7935 CC = DAG.getConstant(CCode, MVT::i8);
7936 SDNode *User = *Op.getNode()->use_begin();
7937 // Look for an unconditional branch following this conditional branch.
7938 // We need this because we need to reverse the successors in order
7939 // to implement FCMP_OEQ.
7940 if (User->getOpcode() == ISD::BR) {
7941 SDValue FalseBB = User->getOperand(1);
7943 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7944 assert(NewBR == User);
7948 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7949 Chain, Dest, CC, Cmp);
7950 X86::CondCode CCode =
7951 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7952 CCode = X86::GetOppositeBranchCondition(CCode);
7953 CC = DAG.getConstant(CCode, MVT::i8);
7959 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7960 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7961 // It should be transformed during dag combiner except when the condition
7962 // is set by a arithmetics with overflow node.
7963 X86::CondCode CCode =
7964 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7965 CCode = X86::GetOppositeBranchCondition(CCode);
7966 CC = DAG.getConstant(CCode, MVT::i8);
7967 Cond = Cond.getOperand(0).getOperand(1);
7973 // Look pass the truncate.
7974 if (Cond.getOpcode() == ISD::TRUNCATE)
7975 Cond = Cond.getOperand(0);
7977 // We know the result of AND is compared against zero. Try to match
7979 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7980 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7981 if (NewSetCC.getNode()) {
7982 CC = NewSetCC.getOperand(0);
7983 Cond = NewSetCC.getOperand(1);
7990 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7991 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7993 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7994 Chain, Dest, CC, Cond);
7998 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7999 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8000 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8001 // that the guard pages used by the OS virtual memory manager are allocated in
8002 // correct sequence.
8004 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8005 SelectionDAG &DAG) const {
8006 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8007 "This should be used only on Windows targets");
8008 assert(!Subtarget->isTargetEnvMacho());
8009 DebugLoc dl = Op.getDebugLoc();
8012 SDValue Chain = Op.getOperand(0);
8013 SDValue Size = Op.getOperand(1);
8014 // FIXME: Ensure alignment here
8018 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8019 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8021 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8022 Flag = Chain.getValue(1);
8024 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8026 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8027 Flag = Chain.getValue(1);
8029 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8031 SDValue Ops1[2] = { Chain.getValue(0), Chain };
8032 return DAG.getMergeValues(Ops1, 2, dl);
8035 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8036 MachineFunction &MF = DAG.getMachineFunction();
8037 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8039 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8040 DebugLoc DL = Op.getDebugLoc();
8042 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8043 // vastart just stores the address of the VarArgsFrameIndex slot into the
8044 // memory location argument.
8045 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8047 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8048 MachinePointerInfo(SV), false, false, 0);
8052 // gp_offset (0 - 6 * 8)
8053 // fp_offset (48 - 48 + 8 * 16)
8054 // overflow_arg_area (point to parameters coming in memory).
8056 SmallVector<SDValue, 8> MemOps;
8057 SDValue FIN = Op.getOperand(1);
8059 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8060 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8062 FIN, MachinePointerInfo(SV), false, false, 0);
8063 MemOps.push_back(Store);
8066 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8067 FIN, DAG.getIntPtrConstant(4));
8068 Store = DAG.getStore(Op.getOperand(0), DL,
8069 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8071 FIN, MachinePointerInfo(SV, 4), false, false, 0);
8072 MemOps.push_back(Store);
8074 // Store ptr to overflow_arg_area
8075 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8076 FIN, DAG.getIntPtrConstant(4));
8077 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8079 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8080 MachinePointerInfo(SV, 8),
8082 MemOps.push_back(Store);
8084 // Store ptr to reg_save_area.
8085 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8086 FIN, DAG.getIntPtrConstant(8));
8087 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8089 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8090 MachinePointerInfo(SV, 16), false, false, 0);
8091 MemOps.push_back(Store);
8092 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8093 &MemOps[0], MemOps.size());
8096 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8097 assert(Subtarget->is64Bit() &&
8098 "LowerVAARG only handles 64-bit va_arg!");
8099 assert((Subtarget->isTargetLinux() ||
8100 Subtarget->isTargetDarwin()) &&
8101 "Unhandled target in LowerVAARG");
8102 assert(Op.getNode()->getNumOperands() == 4);
8103 SDValue Chain = Op.getOperand(0);
8104 SDValue SrcPtr = Op.getOperand(1);
8105 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8106 unsigned Align = Op.getConstantOperandVal(3);
8107 DebugLoc dl = Op.getDebugLoc();
8109 EVT ArgVT = Op.getNode()->getValueType(0);
8110 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8111 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8114 // Decide which area this value should be read from.
8115 // TODO: Implement the AMD64 ABI in its entirety. This simple
8116 // selection mechanism works only for the basic types.
8117 if (ArgVT == MVT::f80) {
8118 llvm_unreachable("va_arg for f80 not yet implemented");
8119 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8120 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
8121 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8122 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
8124 llvm_unreachable("Unhandled argument type in LowerVAARG");
8128 // Sanity Check: Make sure using fp_offset makes sense.
8129 assert(!UseSoftFloat &&
8130 !(DAG.getMachineFunction()
8131 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8132 Subtarget->hasXMM());
8135 // Insert VAARG_64 node into the DAG
8136 // VAARG_64 returns two values: Variable Argument Address, Chain
8137 SmallVector<SDValue, 11> InstOps;
8138 InstOps.push_back(Chain);
8139 InstOps.push_back(SrcPtr);
8140 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8141 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8142 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8143 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8144 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8145 VTs, &InstOps[0], InstOps.size(),
8147 MachinePointerInfo(SV),
8152 Chain = VAARG.getValue(1);
8154 // Load the next argument and return it
8155 return DAG.getLoad(ArgVT, dl,
8158 MachinePointerInfo(),
8162 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8163 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8164 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8165 SDValue Chain = Op.getOperand(0);
8166 SDValue DstPtr = Op.getOperand(1);
8167 SDValue SrcPtr = Op.getOperand(2);
8168 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8169 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8170 DebugLoc DL = Op.getDebugLoc();
8172 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8173 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8175 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8179 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8180 DebugLoc dl = Op.getDebugLoc();
8181 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8183 default: return SDValue(); // Don't custom lower most intrinsics.
8184 // Comparison intrinsics.
8185 case Intrinsic::x86_sse_comieq_ss:
8186 case Intrinsic::x86_sse_comilt_ss:
8187 case Intrinsic::x86_sse_comile_ss:
8188 case Intrinsic::x86_sse_comigt_ss:
8189 case Intrinsic::x86_sse_comige_ss:
8190 case Intrinsic::x86_sse_comineq_ss:
8191 case Intrinsic::x86_sse_ucomieq_ss:
8192 case Intrinsic::x86_sse_ucomilt_ss:
8193 case Intrinsic::x86_sse_ucomile_ss:
8194 case Intrinsic::x86_sse_ucomigt_ss:
8195 case Intrinsic::x86_sse_ucomige_ss:
8196 case Intrinsic::x86_sse_ucomineq_ss:
8197 case Intrinsic::x86_sse2_comieq_sd:
8198 case Intrinsic::x86_sse2_comilt_sd:
8199 case Intrinsic::x86_sse2_comile_sd:
8200 case Intrinsic::x86_sse2_comigt_sd:
8201 case Intrinsic::x86_sse2_comige_sd:
8202 case Intrinsic::x86_sse2_comineq_sd:
8203 case Intrinsic::x86_sse2_ucomieq_sd:
8204 case Intrinsic::x86_sse2_ucomilt_sd:
8205 case Intrinsic::x86_sse2_ucomile_sd:
8206 case Intrinsic::x86_sse2_ucomigt_sd:
8207 case Intrinsic::x86_sse2_ucomige_sd:
8208 case Intrinsic::x86_sse2_ucomineq_sd: {
8210 ISD::CondCode CC = ISD::SETCC_INVALID;
8213 case Intrinsic::x86_sse_comieq_ss:
8214 case Intrinsic::x86_sse2_comieq_sd:
8218 case Intrinsic::x86_sse_comilt_ss:
8219 case Intrinsic::x86_sse2_comilt_sd:
8223 case Intrinsic::x86_sse_comile_ss:
8224 case Intrinsic::x86_sse2_comile_sd:
8228 case Intrinsic::x86_sse_comigt_ss:
8229 case Intrinsic::x86_sse2_comigt_sd:
8233 case Intrinsic::x86_sse_comige_ss:
8234 case Intrinsic::x86_sse2_comige_sd:
8238 case Intrinsic::x86_sse_comineq_ss:
8239 case Intrinsic::x86_sse2_comineq_sd:
8243 case Intrinsic::x86_sse_ucomieq_ss:
8244 case Intrinsic::x86_sse2_ucomieq_sd:
8245 Opc = X86ISD::UCOMI;
8248 case Intrinsic::x86_sse_ucomilt_ss:
8249 case Intrinsic::x86_sse2_ucomilt_sd:
8250 Opc = X86ISD::UCOMI;
8253 case Intrinsic::x86_sse_ucomile_ss:
8254 case Intrinsic::x86_sse2_ucomile_sd:
8255 Opc = X86ISD::UCOMI;
8258 case Intrinsic::x86_sse_ucomigt_ss:
8259 case Intrinsic::x86_sse2_ucomigt_sd:
8260 Opc = X86ISD::UCOMI;
8263 case Intrinsic::x86_sse_ucomige_ss:
8264 case Intrinsic::x86_sse2_ucomige_sd:
8265 Opc = X86ISD::UCOMI;
8268 case Intrinsic::x86_sse_ucomineq_ss:
8269 case Intrinsic::x86_sse2_ucomineq_sd:
8270 Opc = X86ISD::UCOMI;
8275 SDValue LHS = Op.getOperand(1);
8276 SDValue RHS = Op.getOperand(2);
8277 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8278 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8279 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8280 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8281 DAG.getConstant(X86CC, MVT::i8), Cond);
8282 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8284 // ptest and testp intrinsics. The intrinsic these come from are designed to
8285 // return an integer value, not just an instruction so lower it to the ptest
8286 // or testp pattern and a setcc for the result.
8287 case Intrinsic::x86_sse41_ptestz:
8288 case Intrinsic::x86_sse41_ptestc:
8289 case Intrinsic::x86_sse41_ptestnzc:
8290 case Intrinsic::x86_avx_ptestz_256:
8291 case Intrinsic::x86_avx_ptestc_256:
8292 case Intrinsic::x86_avx_ptestnzc_256:
8293 case Intrinsic::x86_avx_vtestz_ps:
8294 case Intrinsic::x86_avx_vtestc_ps:
8295 case Intrinsic::x86_avx_vtestnzc_ps:
8296 case Intrinsic::x86_avx_vtestz_pd:
8297 case Intrinsic::x86_avx_vtestc_pd:
8298 case Intrinsic::x86_avx_vtestnzc_pd:
8299 case Intrinsic::x86_avx_vtestz_ps_256:
8300 case Intrinsic::x86_avx_vtestc_ps_256:
8301 case Intrinsic::x86_avx_vtestnzc_ps_256:
8302 case Intrinsic::x86_avx_vtestz_pd_256:
8303 case Intrinsic::x86_avx_vtestc_pd_256:
8304 case Intrinsic::x86_avx_vtestnzc_pd_256: {
8305 bool IsTestPacked = false;
8308 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8309 case Intrinsic::x86_avx_vtestz_ps:
8310 case Intrinsic::x86_avx_vtestz_pd:
8311 case Intrinsic::x86_avx_vtestz_ps_256:
8312 case Intrinsic::x86_avx_vtestz_pd_256:
8313 IsTestPacked = true; // Fallthrough
8314 case Intrinsic::x86_sse41_ptestz:
8315 case Intrinsic::x86_avx_ptestz_256:
8317 X86CC = X86::COND_E;
8319 case Intrinsic::x86_avx_vtestc_ps:
8320 case Intrinsic::x86_avx_vtestc_pd:
8321 case Intrinsic::x86_avx_vtestc_ps_256:
8322 case Intrinsic::x86_avx_vtestc_pd_256:
8323 IsTestPacked = true; // Fallthrough
8324 case Intrinsic::x86_sse41_ptestc:
8325 case Intrinsic::x86_avx_ptestc_256:
8327 X86CC = X86::COND_B;
8329 case Intrinsic::x86_avx_vtestnzc_ps:
8330 case Intrinsic::x86_avx_vtestnzc_pd:
8331 case Intrinsic::x86_avx_vtestnzc_ps_256:
8332 case Intrinsic::x86_avx_vtestnzc_pd_256:
8333 IsTestPacked = true; // Fallthrough
8334 case Intrinsic::x86_sse41_ptestnzc:
8335 case Intrinsic::x86_avx_ptestnzc_256:
8337 X86CC = X86::COND_A;
8341 SDValue LHS = Op.getOperand(1);
8342 SDValue RHS = Op.getOperand(2);
8343 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8344 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8345 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8346 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8347 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8350 // Fix vector shift instructions where the last operand is a non-immediate
8352 case Intrinsic::x86_sse2_pslli_w:
8353 case Intrinsic::x86_sse2_pslli_d:
8354 case Intrinsic::x86_sse2_pslli_q:
8355 case Intrinsic::x86_sse2_psrli_w:
8356 case Intrinsic::x86_sse2_psrli_d:
8357 case Intrinsic::x86_sse2_psrli_q:
8358 case Intrinsic::x86_sse2_psrai_w:
8359 case Intrinsic::x86_sse2_psrai_d:
8360 case Intrinsic::x86_mmx_pslli_w:
8361 case Intrinsic::x86_mmx_pslli_d:
8362 case Intrinsic::x86_mmx_pslli_q:
8363 case Intrinsic::x86_mmx_psrli_w:
8364 case Intrinsic::x86_mmx_psrli_d:
8365 case Intrinsic::x86_mmx_psrli_q:
8366 case Intrinsic::x86_mmx_psrai_w:
8367 case Intrinsic::x86_mmx_psrai_d: {
8368 SDValue ShAmt = Op.getOperand(2);
8369 if (isa<ConstantSDNode>(ShAmt))
8372 unsigned NewIntNo = 0;
8373 EVT ShAmtVT = MVT::v4i32;
8375 case Intrinsic::x86_sse2_pslli_w:
8376 NewIntNo = Intrinsic::x86_sse2_psll_w;
8378 case Intrinsic::x86_sse2_pslli_d:
8379 NewIntNo = Intrinsic::x86_sse2_psll_d;
8381 case Intrinsic::x86_sse2_pslli_q:
8382 NewIntNo = Intrinsic::x86_sse2_psll_q;
8384 case Intrinsic::x86_sse2_psrli_w:
8385 NewIntNo = Intrinsic::x86_sse2_psrl_w;
8387 case Intrinsic::x86_sse2_psrli_d:
8388 NewIntNo = Intrinsic::x86_sse2_psrl_d;
8390 case Intrinsic::x86_sse2_psrli_q:
8391 NewIntNo = Intrinsic::x86_sse2_psrl_q;
8393 case Intrinsic::x86_sse2_psrai_w:
8394 NewIntNo = Intrinsic::x86_sse2_psra_w;
8396 case Intrinsic::x86_sse2_psrai_d:
8397 NewIntNo = Intrinsic::x86_sse2_psra_d;
8400 ShAmtVT = MVT::v2i32;
8402 case Intrinsic::x86_mmx_pslli_w:
8403 NewIntNo = Intrinsic::x86_mmx_psll_w;
8405 case Intrinsic::x86_mmx_pslli_d:
8406 NewIntNo = Intrinsic::x86_mmx_psll_d;
8408 case Intrinsic::x86_mmx_pslli_q:
8409 NewIntNo = Intrinsic::x86_mmx_psll_q;
8411 case Intrinsic::x86_mmx_psrli_w:
8412 NewIntNo = Intrinsic::x86_mmx_psrl_w;
8414 case Intrinsic::x86_mmx_psrli_d:
8415 NewIntNo = Intrinsic::x86_mmx_psrl_d;
8417 case Intrinsic::x86_mmx_psrli_q:
8418 NewIntNo = Intrinsic::x86_mmx_psrl_q;
8420 case Intrinsic::x86_mmx_psrai_w:
8421 NewIntNo = Intrinsic::x86_mmx_psra_w;
8423 case Intrinsic::x86_mmx_psrai_d:
8424 NewIntNo = Intrinsic::x86_mmx_psra_d;
8426 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8432 // The vector shift intrinsics with scalars uses 32b shift amounts but
8433 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8437 ShOps[1] = DAG.getConstant(0, MVT::i32);
8438 if (ShAmtVT == MVT::v4i32) {
8439 ShOps[2] = DAG.getUNDEF(MVT::i32);
8440 ShOps[3] = DAG.getUNDEF(MVT::i32);
8441 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8443 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8444 // FIXME this must be lowered to get rid of the invalid type.
8447 EVT VT = Op.getValueType();
8448 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8449 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8450 DAG.getConstant(NewIntNo, MVT::i32),
8451 Op.getOperand(1), ShAmt);
8456 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8457 SelectionDAG &DAG) const {
8458 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8459 MFI->setReturnAddressIsTaken(true);
8461 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8462 DebugLoc dl = Op.getDebugLoc();
8465 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8467 DAG.getConstant(TD->getPointerSize(),
8468 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8469 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8470 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8472 MachinePointerInfo(), false, false, 0);
8475 // Just load the return address.
8476 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8477 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8478 RetAddrFI, MachinePointerInfo(), false, false, 0);
8481 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8482 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8483 MFI->setFrameAddressIsTaken(true);
8485 EVT VT = Op.getValueType();
8486 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
8487 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8488 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8489 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8491 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8492 MachinePointerInfo(),
8497 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8498 SelectionDAG &DAG) const {
8499 return DAG.getIntPtrConstant(2*TD->getPointerSize());
8502 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8503 MachineFunction &MF = DAG.getMachineFunction();
8504 SDValue Chain = Op.getOperand(0);
8505 SDValue Offset = Op.getOperand(1);
8506 SDValue Handler = Op.getOperand(2);
8507 DebugLoc dl = Op.getDebugLoc();
8509 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8510 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8512 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8514 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8515 DAG.getIntPtrConstant(TD->getPointerSize()));
8516 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8517 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8519 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8520 MF.getRegInfo().addLiveOut(StoreAddrReg);
8522 return DAG.getNode(X86ISD::EH_RETURN, dl,
8524 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8527 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8528 SelectionDAG &DAG) const {
8529 SDValue Root = Op.getOperand(0);
8530 SDValue Trmp = Op.getOperand(1); // trampoline
8531 SDValue FPtr = Op.getOperand(2); // nested function
8532 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8533 DebugLoc dl = Op.getDebugLoc();
8535 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8537 if (Subtarget->is64Bit()) {
8538 SDValue OutChains[6];
8540 // Large code-model.
8541 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8542 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8544 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8545 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8547 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8549 // Load the pointer to the nested function into R11.
8550 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8551 SDValue Addr = Trmp;
8552 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8553 Addr, MachinePointerInfo(TrmpAddr),
8556 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8557 DAG.getConstant(2, MVT::i64));
8558 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8559 MachinePointerInfo(TrmpAddr, 2),
8562 // Load the 'nest' parameter value into R10.
8563 // R10 is specified in X86CallingConv.td
8564 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8565 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8566 DAG.getConstant(10, MVT::i64));
8567 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8568 Addr, MachinePointerInfo(TrmpAddr, 10),
8571 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8572 DAG.getConstant(12, MVT::i64));
8573 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8574 MachinePointerInfo(TrmpAddr, 12),
8577 // Jump to the nested function.
8578 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8579 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8580 DAG.getConstant(20, MVT::i64));
8581 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8582 Addr, MachinePointerInfo(TrmpAddr, 20),
8585 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8586 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8587 DAG.getConstant(22, MVT::i64));
8588 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8589 MachinePointerInfo(TrmpAddr, 22),
8593 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8594 return DAG.getMergeValues(Ops, 2, dl);
8596 const Function *Func =
8597 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8598 CallingConv::ID CC = Func->getCallingConv();
8603 llvm_unreachable("Unsupported calling convention");
8604 case CallingConv::C:
8605 case CallingConv::X86_StdCall: {
8606 // Pass 'nest' parameter in ECX.
8607 // Must be kept in sync with X86CallingConv.td
8610 // Check that ECX wasn't needed by an 'inreg' parameter.
8611 const FunctionType *FTy = Func->getFunctionType();
8612 const AttrListPtr &Attrs = Func->getAttributes();
8614 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8615 unsigned InRegCount = 0;
8618 for (FunctionType::param_iterator I = FTy->param_begin(),
8619 E = FTy->param_end(); I != E; ++I, ++Idx)
8620 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8621 // FIXME: should only count parameters that are lowered to integers.
8622 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8624 if (InRegCount > 2) {
8625 report_fatal_error("Nest register in use - reduce number of inreg"
8631 case CallingConv::X86_FastCall:
8632 case CallingConv::X86_ThisCall:
8633 case CallingConv::Fast:
8634 // Pass 'nest' parameter in EAX.
8635 // Must be kept in sync with X86CallingConv.td
8640 SDValue OutChains[4];
8643 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8644 DAG.getConstant(10, MVT::i32));
8645 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8647 // This is storing the opcode for MOV32ri.
8648 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8649 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8650 OutChains[0] = DAG.getStore(Root, dl,
8651 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8652 Trmp, MachinePointerInfo(TrmpAddr),
8655 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8656 DAG.getConstant(1, MVT::i32));
8657 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8658 MachinePointerInfo(TrmpAddr, 1),
8661 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8662 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8663 DAG.getConstant(5, MVT::i32));
8664 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8665 MachinePointerInfo(TrmpAddr, 5),
8668 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8669 DAG.getConstant(6, MVT::i32));
8670 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8671 MachinePointerInfo(TrmpAddr, 6),
8675 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8676 return DAG.getMergeValues(Ops, 2, dl);
8680 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8681 SelectionDAG &DAG) const {
8683 The rounding mode is in bits 11:10 of FPSR, and has the following
8690 FLT_ROUNDS, on the other hand, expects the following:
8697 To perform the conversion, we do:
8698 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8701 MachineFunction &MF = DAG.getMachineFunction();
8702 const TargetMachine &TM = MF.getTarget();
8703 const TargetFrameLowering &TFI = *TM.getFrameLowering();
8704 unsigned StackAlignment = TFI.getStackAlignment();
8705 EVT VT = Op.getValueType();
8706 DebugLoc DL = Op.getDebugLoc();
8708 // Save FP Control Word to stack slot
8709 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8710 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8713 MachineMemOperand *MMO =
8714 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8715 MachineMemOperand::MOStore, 2, 2);
8717 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8718 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8719 DAG.getVTList(MVT::Other),
8720 Ops, 2, MVT::i16, MMO);
8722 // Load FP Control Word from stack slot
8723 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8724 MachinePointerInfo(), false, false, 0);
8726 // Transform as necessary
8728 DAG.getNode(ISD::SRL, DL, MVT::i16,
8729 DAG.getNode(ISD::AND, DL, MVT::i16,
8730 CWD, DAG.getConstant(0x800, MVT::i16)),
8731 DAG.getConstant(11, MVT::i8));
8733 DAG.getNode(ISD::SRL, DL, MVT::i16,
8734 DAG.getNode(ISD::AND, DL, MVT::i16,
8735 CWD, DAG.getConstant(0x400, MVT::i16)),
8736 DAG.getConstant(9, MVT::i8));
8739 DAG.getNode(ISD::AND, DL, MVT::i16,
8740 DAG.getNode(ISD::ADD, DL, MVT::i16,
8741 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8742 DAG.getConstant(1, MVT::i16)),
8743 DAG.getConstant(3, MVT::i16));
8746 return DAG.getNode((VT.getSizeInBits() < 16 ?
8747 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8750 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8751 EVT VT = Op.getValueType();
8753 unsigned NumBits = VT.getSizeInBits();
8754 DebugLoc dl = Op.getDebugLoc();
8756 Op = Op.getOperand(0);
8757 if (VT == MVT::i8) {
8758 // Zero extend to i32 since there is not an i8 bsr.
8760 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8763 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8764 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8765 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8767 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8770 DAG.getConstant(NumBits+NumBits-1, OpVT),
8771 DAG.getConstant(X86::COND_E, MVT::i8),
8774 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8776 // Finally xor with NumBits-1.
8777 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8780 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8784 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8785 EVT VT = Op.getValueType();
8787 unsigned NumBits = VT.getSizeInBits();
8788 DebugLoc dl = Op.getDebugLoc();
8790 Op = Op.getOperand(0);
8791 if (VT == MVT::i8) {
8793 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8796 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8797 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8798 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8800 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8803 DAG.getConstant(NumBits, OpVT),
8804 DAG.getConstant(X86::COND_E, MVT::i8),
8807 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8810 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8814 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8815 EVT VT = Op.getValueType();
8816 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8817 DebugLoc dl = Op.getDebugLoc();
8819 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8820 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8821 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8822 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8823 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8825 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8826 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8827 // return AloBlo + AloBhi + AhiBlo;
8829 SDValue A = Op.getOperand(0);
8830 SDValue B = Op.getOperand(1);
8832 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8833 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8834 A, DAG.getConstant(32, MVT::i32));
8835 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8836 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8837 B, DAG.getConstant(32, MVT::i32));
8838 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8839 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8841 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8842 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8844 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8845 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8847 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8848 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8849 AloBhi, DAG.getConstant(32, MVT::i32));
8850 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8851 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8852 AhiBlo, DAG.getConstant(32, MVT::i32));
8853 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8854 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8858 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8860 EVT VT = Op.getValueType();
8861 DebugLoc dl = Op.getDebugLoc();
8862 SDValue R = Op.getOperand(0);
8863 SDValue Amt = Op.getOperand(1);
8865 LLVMContext *Context = DAG.getContext();
8868 if (!Subtarget->hasSSE2()) return SDValue();
8870 // Optimize shl/srl/sra with constant shift amount.
8871 if (isSplatVector(Amt.getNode())) {
8872 SDValue SclrAmt = Amt->getOperand(0);
8873 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8874 uint64_t ShiftAmt = C->getZExtValue();
8876 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8877 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8878 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8879 R, DAG.getConstant(ShiftAmt, MVT::i32));
8881 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
8882 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8883 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8884 R, DAG.getConstant(ShiftAmt, MVT::i32));
8886 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
8887 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8888 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8889 R, DAG.getConstant(ShiftAmt, MVT::i32));
8891 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
8892 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8893 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8894 R, DAG.getConstant(ShiftAmt, MVT::i32));
8896 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
8897 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8898 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8899 R, DAG.getConstant(ShiftAmt, MVT::i32));
8901 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
8902 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8903 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8904 R, DAG.getConstant(ShiftAmt, MVT::i32));
8906 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
8907 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8908 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8909 R, DAG.getConstant(ShiftAmt, MVT::i32));
8911 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
8912 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8913 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8914 R, DAG.getConstant(ShiftAmt, MVT::i32));
8918 // Lower SHL with variable shift amount.
8919 // Cannot lower SHL without SSE4.1 or later.
8920 if (!Subtarget->hasSSE41()) return SDValue();
8922 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
8923 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8924 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8925 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8927 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8929 std::vector<Constant*> CV(4, CI);
8930 Constant *C = ConstantVector::get(CV);
8931 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8932 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8933 MachinePointerInfo::getConstantPool(),
8936 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8937 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8938 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8939 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8941 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
8943 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8944 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8945 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8947 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8948 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8950 std::vector<Constant*> CVM1(16, CM1);
8951 std::vector<Constant*> CVM2(16, CM2);
8952 Constant *C = ConstantVector::get(CVM1);
8953 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8954 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8955 MachinePointerInfo::getConstantPool(),
8958 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8959 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8960 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8961 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8962 DAG.getConstant(4, MVT::i32));
8963 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8965 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8967 C = ConstantVector::get(CVM2);
8968 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8969 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8970 MachinePointerInfo::getConstantPool(),
8973 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8974 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8975 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8976 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8977 DAG.getConstant(2, MVT::i32));
8978 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8980 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8982 // return pblendv(r, r+r, a);
8983 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8984 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8990 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8991 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8992 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8993 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8994 // has only one use.
8995 SDNode *N = Op.getNode();
8996 SDValue LHS = N->getOperand(0);
8997 SDValue RHS = N->getOperand(1);
8998 unsigned BaseOp = 0;
9000 DebugLoc DL = Op.getDebugLoc();
9001 switch (Op.getOpcode()) {
9002 default: llvm_unreachable("Unknown ovf instruction!");
9004 // A subtract of one will be selected as a INC. Note that INC doesn't
9005 // set CF, so we can't do this for UADDO.
9006 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9008 BaseOp = X86ISD::INC;
9012 BaseOp = X86ISD::ADD;
9016 BaseOp = X86ISD::ADD;
9020 // A subtract of one will be selected as a DEC. Note that DEC doesn't
9021 // set CF, so we can't do this for USUBO.
9022 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9024 BaseOp = X86ISD::DEC;
9028 BaseOp = X86ISD::SUB;
9032 BaseOp = X86ISD::SUB;
9036 BaseOp = X86ISD::SMUL;
9039 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9040 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9042 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9045 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9046 DAG.getConstant(X86::COND_O, MVT::i32),
9047 SDValue(Sum.getNode(), 2));
9049 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9054 // Also sets EFLAGS.
9055 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9056 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9059 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9060 DAG.getConstant(Cond, MVT::i32),
9061 SDValue(Sum.getNode(), 1));
9063 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9067 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9068 DebugLoc dl = Op.getDebugLoc();
9070 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
9071 // There isn't any reason to disable it if the target processor supports it.
9072 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
9073 SDValue Chain = Op.getOperand(0);
9074 SDValue Zero = DAG.getConstant(0, MVT::i32);
9076 DAG.getRegister(X86::ESP, MVT::i32), // Base
9077 DAG.getTargetConstant(1, MVT::i8), // Scale
9078 DAG.getRegister(0, MVT::i32), // Index
9079 DAG.getTargetConstant(0, MVT::i32), // Disp
9080 DAG.getRegister(0, MVT::i32), // Segment.
9085 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9086 array_lengthof(Ops));
9087 return SDValue(Res, 0);
9090 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9092 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9094 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9095 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9096 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9097 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9099 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9100 if (!Op1 && !Op2 && !Op3 && Op4)
9101 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9103 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9104 if (Op1 && !Op2 && !Op3 && !Op4)
9105 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9107 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9109 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9112 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9113 EVT T = Op.getValueType();
9114 DebugLoc DL = Op.getDebugLoc();
9117 switch(T.getSimpleVT().SimpleTy) {
9119 assert(false && "Invalid value type!");
9120 case MVT::i8: Reg = X86::AL; size = 1; break;
9121 case MVT::i16: Reg = X86::AX; size = 2; break;
9122 case MVT::i32: Reg = X86::EAX; size = 4; break;
9124 assert(Subtarget->is64Bit() && "Node not type legal!");
9125 Reg = X86::RAX; size = 8;
9128 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9129 Op.getOperand(2), SDValue());
9130 SDValue Ops[] = { cpIn.getValue(0),
9133 DAG.getTargetConstant(size, MVT::i8),
9135 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9136 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9137 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9140 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9144 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9145 SelectionDAG &DAG) const {
9146 assert(Subtarget->is64Bit() && "Result not type legalized?");
9147 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9148 SDValue TheChain = Op.getOperand(0);
9149 DebugLoc dl = Op.getDebugLoc();
9150 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9151 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9152 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9154 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9155 DAG.getConstant(32, MVT::i8));
9157 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9160 return DAG.getMergeValues(Ops, 2, dl);
9163 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9164 SelectionDAG &DAG) const {
9165 EVT SrcVT = Op.getOperand(0).getValueType();
9166 EVT DstVT = Op.getValueType();
9167 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9168 Subtarget->hasMMX() && "Unexpected custom BITCAST");
9169 assert((DstVT == MVT::i64 ||
9170 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9171 "Unexpected custom BITCAST");
9172 // i64 <=> MMX conversions are Legal.
9173 if (SrcVT==MVT::i64 && DstVT.isVector())
9175 if (DstVT==MVT::i64 && SrcVT.isVector())
9177 // MMX <=> MMX conversions are Legal.
9178 if (SrcVT.isVector() && DstVT.isVector())
9180 // All other conversions need to be expanded.
9184 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9185 SDNode *Node = Op.getNode();
9186 DebugLoc dl = Node->getDebugLoc();
9187 EVT T = Node->getValueType(0);
9188 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9189 DAG.getConstant(0, T), Node->getOperand(2));
9190 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9191 cast<AtomicSDNode>(Node)->getMemoryVT(),
9192 Node->getOperand(0),
9193 Node->getOperand(1), negOp,
9194 cast<AtomicSDNode>(Node)->getSrcValue(),
9195 cast<AtomicSDNode>(Node)->getAlignment());
9198 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9199 EVT VT = Op.getNode()->getValueType(0);
9201 // Let legalize expand this if it isn't a legal type yet.
9202 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9205 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9208 bool ExtraOp = false;
9209 switch (Op.getOpcode()) {
9210 default: assert(0 && "Invalid code");
9211 case ISD::ADDC: Opc = X86ISD::ADD; break;
9212 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9213 case ISD::SUBC: Opc = X86ISD::SUB; break;
9214 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9218 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9220 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9221 Op.getOperand(1), Op.getOperand(2));
9224 /// LowerOperation - Provide custom lowering hooks for some operations.
9226 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9227 switch (Op.getOpcode()) {
9228 default: llvm_unreachable("Should not custom lower this!");
9229 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
9230 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
9231 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
9232 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
9233 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
9234 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
9235 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9236 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9237 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
9238 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
9239 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
9240 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9241 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9242 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9243 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
9244 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
9245 case ISD::SHL_PARTS:
9246 case ISD::SRA_PARTS:
9247 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
9248 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
9249 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
9250 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
9251 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
9252 case ISD::FABS: return LowerFABS(Op, DAG);
9253 case ISD::FNEG: return LowerFNEG(Op, DAG);
9254 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
9255 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
9256 case ISD::SETCC: return LowerSETCC(Op, DAG);
9257 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
9258 case ISD::SELECT: return LowerSELECT(Op, DAG);
9259 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
9260 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
9261 case ISD::VASTART: return LowerVASTART(Op, DAG);
9262 case ISD::VAARG: return LowerVAARG(Op, DAG);
9263 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
9264 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9265 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9266 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9267 case ISD::FRAME_TO_ARGS_OFFSET:
9268 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9269 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9270 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
9271 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
9272 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9273 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
9274 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
9275 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
9278 case ISD::SHL: return LowerShift(Op, DAG);
9284 case ISD::UMULO: return LowerXALUO(Op, DAG);
9285 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
9286 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
9290 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9294 void X86TargetLowering::
9295 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9296 SelectionDAG &DAG, unsigned NewOp) const {
9297 EVT T = Node->getValueType(0);
9298 DebugLoc dl = Node->getDebugLoc();
9299 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9301 SDValue Chain = Node->getOperand(0);
9302 SDValue In1 = Node->getOperand(1);
9303 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9304 Node->getOperand(2), DAG.getIntPtrConstant(0));
9305 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9306 Node->getOperand(2), DAG.getIntPtrConstant(1));
9307 SDValue Ops[] = { Chain, In1, In2L, In2H };
9308 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9310 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9311 cast<MemSDNode>(Node)->getMemOperand());
9312 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9313 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9314 Results.push_back(Result.getValue(2));
9317 /// ReplaceNodeResults - Replace a node with an illegal result type
9318 /// with a new node built out of custom code.
9319 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9320 SmallVectorImpl<SDValue>&Results,
9321 SelectionDAG &DAG) const {
9322 DebugLoc dl = N->getDebugLoc();
9323 switch (N->getOpcode()) {
9325 assert(false && "Do not know how to custom type legalize this operation!");
9331 // We don't want to expand or promote these.
9333 case ISD::FP_TO_SINT: {
9334 std::pair<SDValue,SDValue> Vals =
9335 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9336 SDValue FIST = Vals.first, StackSlot = Vals.second;
9337 if (FIST.getNode() != 0) {
9338 EVT VT = N->getValueType(0);
9339 // Return a load from the stack slot.
9340 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9341 MachinePointerInfo(), false, false, 0));
9345 case ISD::READCYCLECOUNTER: {
9346 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9347 SDValue TheChain = N->getOperand(0);
9348 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9349 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9351 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9353 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9354 SDValue Ops[] = { eax, edx };
9355 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9356 Results.push_back(edx.getValue(1));
9359 case ISD::ATOMIC_CMP_SWAP: {
9360 EVT T = N->getValueType(0);
9361 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9362 SDValue cpInL, cpInH;
9363 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9364 DAG.getConstant(0, MVT::i32));
9365 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9366 DAG.getConstant(1, MVT::i32));
9367 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9368 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9370 SDValue swapInL, swapInH;
9371 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9372 DAG.getConstant(0, MVT::i32));
9373 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9374 DAG.getConstant(1, MVT::i32));
9375 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9377 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9378 swapInL.getValue(1));
9379 SDValue Ops[] = { swapInH.getValue(0),
9381 swapInH.getValue(1) };
9382 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9383 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9384 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9386 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9387 MVT::i32, Result.getValue(1));
9388 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9389 MVT::i32, cpOutL.getValue(2));
9390 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9391 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9392 Results.push_back(cpOutH.getValue(1));
9395 case ISD::ATOMIC_LOAD_ADD:
9396 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9398 case ISD::ATOMIC_LOAD_AND:
9399 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9401 case ISD::ATOMIC_LOAD_NAND:
9402 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9404 case ISD::ATOMIC_LOAD_OR:
9405 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9407 case ISD::ATOMIC_LOAD_SUB:
9408 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9410 case ISD::ATOMIC_LOAD_XOR:
9411 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9413 case ISD::ATOMIC_SWAP:
9414 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9419 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9421 default: return NULL;
9422 case X86ISD::BSF: return "X86ISD::BSF";
9423 case X86ISD::BSR: return "X86ISD::BSR";
9424 case X86ISD::SHLD: return "X86ISD::SHLD";
9425 case X86ISD::SHRD: return "X86ISD::SHRD";
9426 case X86ISD::FAND: return "X86ISD::FAND";
9427 case X86ISD::FOR: return "X86ISD::FOR";
9428 case X86ISD::FXOR: return "X86ISD::FXOR";
9429 case X86ISD::FSRL: return "X86ISD::FSRL";
9430 case X86ISD::FILD: return "X86ISD::FILD";
9431 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
9432 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9433 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9434 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9435 case X86ISD::FLD: return "X86ISD::FLD";
9436 case X86ISD::FST: return "X86ISD::FST";
9437 case X86ISD::CALL: return "X86ISD::CALL";
9438 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
9439 case X86ISD::BT: return "X86ISD::BT";
9440 case X86ISD::CMP: return "X86ISD::CMP";
9441 case X86ISD::COMI: return "X86ISD::COMI";
9442 case X86ISD::UCOMI: return "X86ISD::UCOMI";
9443 case X86ISD::SETCC: return "X86ISD::SETCC";
9444 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
9445 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
9446 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
9447 case X86ISD::CMOV: return "X86ISD::CMOV";
9448 case X86ISD::BRCOND: return "X86ISD::BRCOND";
9449 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
9450 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
9451 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
9452 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
9453 case X86ISD::Wrapper: return "X86ISD::Wrapper";
9454 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
9455 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
9456 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
9457 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
9458 case X86ISD::PINSRB: return "X86ISD::PINSRB";
9459 case X86ISD::PINSRW: return "X86ISD::PINSRW";
9460 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
9461 case X86ISD::PANDN: return "X86ISD::PANDN";
9462 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
9463 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
9464 case X86ISD::PSIGND: return "X86ISD::PSIGND";
9465 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB";
9466 case X86ISD::FMAX: return "X86ISD::FMAX";
9467 case X86ISD::FMIN: return "X86ISD::FMIN";
9468 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
9469 case X86ISD::FRCP: return "X86ISD::FRCP";
9470 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
9471 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
9472 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
9473 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
9474 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
9475 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
9476 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
9477 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
9478 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
9479 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
9480 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
9481 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
9482 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
9483 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
9484 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
9485 case X86ISD::VSHL: return "X86ISD::VSHL";
9486 case X86ISD::VSRL: return "X86ISD::VSRL";
9487 case X86ISD::CMPPD: return "X86ISD::CMPPD";
9488 case X86ISD::CMPPS: return "X86ISD::CMPPS";
9489 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
9490 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
9491 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
9492 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
9493 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
9494 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
9495 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
9496 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
9497 case X86ISD::ADD: return "X86ISD::ADD";
9498 case X86ISD::SUB: return "X86ISD::SUB";
9499 case X86ISD::ADC: return "X86ISD::ADC";
9500 case X86ISD::SBB: return "X86ISD::SBB";
9501 case X86ISD::SMUL: return "X86ISD::SMUL";
9502 case X86ISD::UMUL: return "X86ISD::UMUL";
9503 case X86ISD::INC: return "X86ISD::INC";
9504 case X86ISD::DEC: return "X86ISD::DEC";
9505 case X86ISD::OR: return "X86ISD::OR";
9506 case X86ISD::XOR: return "X86ISD::XOR";
9507 case X86ISD::AND: return "X86ISD::AND";
9508 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
9509 case X86ISD::PTEST: return "X86ISD::PTEST";
9510 case X86ISD::TESTP: return "X86ISD::TESTP";
9511 case X86ISD::PALIGN: return "X86ISD::PALIGN";
9512 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
9513 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
9514 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
9515 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
9516 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
9517 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
9518 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
9519 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
9520 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
9521 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
9522 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
9523 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
9524 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
9525 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
9526 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
9527 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
9528 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
9529 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
9530 case X86ISD::MOVSD: return "X86ISD::MOVSD";
9531 case X86ISD::MOVSS: return "X86ISD::MOVSS";
9532 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
9533 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
9534 case X86ISD::VUNPCKLPS: return "X86ISD::VUNPCKLPS";
9535 case X86ISD::VUNPCKLPD: return "X86ISD::VUNPCKLPD";
9536 case X86ISD::VUNPCKLPSY: return "X86ISD::VUNPCKLPSY";
9537 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
9538 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
9539 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
9540 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
9541 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
9542 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
9543 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
9544 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
9545 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
9546 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
9547 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
9548 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9549 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
9550 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
9554 // isLegalAddressingMode - Return true if the addressing mode represented
9555 // by AM is legal for this target, for a load/store of the specified type.
9556 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9557 const Type *Ty) const {
9558 // X86 supports extremely general addressing modes.
9559 CodeModel::Model M = getTargetMachine().getCodeModel();
9560 Reloc::Model R = getTargetMachine().getRelocationModel();
9562 // X86 allows a sign-extended 32-bit immediate field as a displacement.
9563 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9568 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9570 // If a reference to this global requires an extra load, we can't fold it.
9571 if (isGlobalStubReference(GVFlags))
9574 // If BaseGV requires a register for the PIC base, we cannot also have a
9575 // BaseReg specified.
9576 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9579 // If lower 4G is not available, then we must use rip-relative addressing.
9580 if ((M != CodeModel::Small || R != Reloc::Static) &&
9581 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9591 // These scales always work.
9596 // These scales are formed with basereg+scalereg. Only accept if there is
9601 default: // Other stuff never works.
9609 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9610 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9612 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9613 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9614 if (NumBits1 <= NumBits2)
9619 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9620 if (!VT1.isInteger() || !VT2.isInteger())
9622 unsigned NumBits1 = VT1.getSizeInBits();
9623 unsigned NumBits2 = VT2.getSizeInBits();
9624 if (NumBits1 <= NumBits2)
9629 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9630 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9631 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9634 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9635 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9636 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9639 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9640 // i16 instructions are longer (0x66 prefix) and potentially slower.
9641 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9644 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9645 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9646 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9647 /// are assumed to be legal.
9649 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9651 // Very little shuffling can be done for 64-bit vectors right now.
9652 if (VT.getSizeInBits() == 64)
9653 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9655 // FIXME: pshufb, blends, shifts.
9656 return (VT.getVectorNumElements() == 2 ||
9657 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9658 isMOVLMask(M, VT) ||
9659 isSHUFPMask(M, VT) ||
9660 isPSHUFDMask(M, VT) ||
9661 isPSHUFHWMask(M, VT) ||
9662 isPSHUFLWMask(M, VT) ||
9663 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9664 isUNPCKLMask(M, VT) ||
9665 isUNPCKHMask(M, VT) ||
9666 isUNPCKL_v_undef_Mask(M, VT) ||
9667 isUNPCKH_v_undef_Mask(M, VT));
9671 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9673 unsigned NumElts = VT.getVectorNumElements();
9674 // FIXME: This collection of masks seems suspect.
9677 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9678 return (isMOVLMask(Mask, VT) ||
9679 isCommutedMOVLMask(Mask, VT, true) ||
9680 isSHUFPMask(Mask, VT) ||
9681 isCommutedSHUFPMask(Mask, VT));
9686 //===----------------------------------------------------------------------===//
9687 // X86 Scheduler Hooks
9688 //===----------------------------------------------------------------------===//
9690 // private utility function
9692 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9693 MachineBasicBlock *MBB,
9700 TargetRegisterClass *RC,
9701 bool invSrc) const {
9702 // For the atomic bitwise operator, we generate
9705 // ld t1 = [bitinstr.addr]
9706 // op t2 = t1, [bitinstr.val]
9708 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9710 // fallthrough -->nextMBB
9711 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9712 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9713 MachineFunction::iterator MBBIter = MBB;
9716 /// First build the CFG
9717 MachineFunction *F = MBB->getParent();
9718 MachineBasicBlock *thisMBB = MBB;
9719 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9720 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9721 F->insert(MBBIter, newMBB);
9722 F->insert(MBBIter, nextMBB);
9724 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9725 nextMBB->splice(nextMBB->begin(), thisMBB,
9726 llvm::next(MachineBasicBlock::iterator(bInstr)),
9728 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9730 // Update thisMBB to fall through to newMBB
9731 thisMBB->addSuccessor(newMBB);
9733 // newMBB jumps to itself and fall through to nextMBB
9734 newMBB->addSuccessor(nextMBB);
9735 newMBB->addSuccessor(newMBB);
9737 // Insert instructions into newMBB based on incoming instruction
9738 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9739 "unexpected number of operands");
9740 DebugLoc dl = bInstr->getDebugLoc();
9741 MachineOperand& destOper = bInstr->getOperand(0);
9742 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9743 int numArgs = bInstr->getNumOperands() - 1;
9744 for (int i=0; i < numArgs; ++i)
9745 argOpers[i] = &bInstr->getOperand(i+1);
9747 // x86 address has 4 operands: base, index, scale, and displacement
9748 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9749 int valArgIndx = lastAddrIndx + 1;
9751 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9752 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9753 for (int i=0; i <= lastAddrIndx; ++i)
9754 (*MIB).addOperand(*argOpers[i]);
9756 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9758 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9763 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9764 assert((argOpers[valArgIndx]->isReg() ||
9765 argOpers[valArgIndx]->isImm()) &&
9767 if (argOpers[valArgIndx]->isReg())
9768 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9770 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9772 (*MIB).addOperand(*argOpers[valArgIndx]);
9774 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9777 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9778 for (int i=0; i <= lastAddrIndx; ++i)
9779 (*MIB).addOperand(*argOpers[i]);
9781 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9782 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9783 bInstr->memoperands_end());
9785 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9789 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9791 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9795 // private utility function: 64 bit atomics on 32 bit host.
9797 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9798 MachineBasicBlock *MBB,
9803 bool invSrc) const {
9804 // For the atomic bitwise operator, we generate
9805 // thisMBB (instructions are in pairs, except cmpxchg8b)
9806 // ld t1,t2 = [bitinstr.addr]
9808 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9809 // op t5, t6 <- out1, out2, [bitinstr.val]
9810 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9811 // mov ECX, EBX <- t5, t6
9812 // mov EAX, EDX <- t1, t2
9813 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9814 // mov t3, t4 <- EAX, EDX
9816 // result in out1, out2
9817 // fallthrough -->nextMBB
9819 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9820 const unsigned LoadOpc = X86::MOV32rm;
9821 const unsigned NotOpc = X86::NOT32r;
9822 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9823 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9824 MachineFunction::iterator MBBIter = MBB;
9827 /// First build the CFG
9828 MachineFunction *F = MBB->getParent();
9829 MachineBasicBlock *thisMBB = MBB;
9830 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9831 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9832 F->insert(MBBIter, newMBB);
9833 F->insert(MBBIter, nextMBB);
9835 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9836 nextMBB->splice(nextMBB->begin(), thisMBB,
9837 llvm::next(MachineBasicBlock::iterator(bInstr)),
9839 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9841 // Update thisMBB to fall through to newMBB
9842 thisMBB->addSuccessor(newMBB);
9844 // newMBB jumps to itself and fall through to nextMBB
9845 newMBB->addSuccessor(nextMBB);
9846 newMBB->addSuccessor(newMBB);
9848 DebugLoc dl = bInstr->getDebugLoc();
9849 // Insert instructions into newMBB based on incoming instruction
9850 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9851 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9852 "unexpected number of operands");
9853 MachineOperand& dest1Oper = bInstr->getOperand(0);
9854 MachineOperand& dest2Oper = bInstr->getOperand(1);
9855 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9856 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9857 argOpers[i] = &bInstr->getOperand(i+2);
9859 // We use some of the operands multiple times, so conservatively just
9860 // clear any kill flags that might be present.
9861 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9862 argOpers[i]->setIsKill(false);
9865 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9866 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9868 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9869 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9870 for (int i=0; i <= lastAddrIndx; ++i)
9871 (*MIB).addOperand(*argOpers[i]);
9872 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9873 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9874 // add 4 to displacement.
9875 for (int i=0; i <= lastAddrIndx-2; ++i)
9876 (*MIB).addOperand(*argOpers[i]);
9877 MachineOperand newOp3 = *(argOpers[3]);
9879 newOp3.setImm(newOp3.getImm()+4);
9881 newOp3.setOffset(newOp3.getOffset()+4);
9882 (*MIB).addOperand(newOp3);
9883 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9885 // t3/4 are defined later, at the bottom of the loop
9886 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9887 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9888 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9889 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9890 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9891 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9893 // The subsequent operations should be using the destination registers of
9894 //the PHI instructions.
9896 t1 = F->getRegInfo().createVirtualRegister(RC);
9897 t2 = F->getRegInfo().createVirtualRegister(RC);
9898 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9899 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9901 t1 = dest1Oper.getReg();
9902 t2 = dest2Oper.getReg();
9905 int valArgIndx = lastAddrIndx + 1;
9906 assert((argOpers[valArgIndx]->isReg() ||
9907 argOpers[valArgIndx]->isImm()) &&
9909 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9910 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9911 if (argOpers[valArgIndx]->isReg())
9912 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9914 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9915 if (regOpcL != X86::MOV32rr)
9917 (*MIB).addOperand(*argOpers[valArgIndx]);
9918 assert(argOpers[valArgIndx + 1]->isReg() ==
9919 argOpers[valArgIndx]->isReg());
9920 assert(argOpers[valArgIndx + 1]->isImm() ==
9921 argOpers[valArgIndx]->isImm());
9922 if (argOpers[valArgIndx + 1]->isReg())
9923 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9925 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9926 if (regOpcH != X86::MOV32rr)
9928 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9930 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9932 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9935 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9937 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9940 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9941 for (int i=0; i <= lastAddrIndx; ++i)
9942 (*MIB).addOperand(*argOpers[i]);
9944 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9945 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9946 bInstr->memoperands_end());
9948 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9949 MIB.addReg(X86::EAX);
9950 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9951 MIB.addReg(X86::EDX);
9954 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9956 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9960 // private utility function
9962 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9963 MachineBasicBlock *MBB,
9964 unsigned cmovOpc) const {
9965 // For the atomic min/max operator, we generate
9968 // ld t1 = [min/max.addr]
9969 // mov t2 = [min/max.val]
9971 // cmov[cond] t2 = t1
9973 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9975 // fallthrough -->nextMBB
9977 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9978 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9979 MachineFunction::iterator MBBIter = MBB;
9982 /// First build the CFG
9983 MachineFunction *F = MBB->getParent();
9984 MachineBasicBlock *thisMBB = MBB;
9985 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9986 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9987 F->insert(MBBIter, newMBB);
9988 F->insert(MBBIter, nextMBB);
9990 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9991 nextMBB->splice(nextMBB->begin(), thisMBB,
9992 llvm::next(MachineBasicBlock::iterator(mInstr)),
9994 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9996 // Update thisMBB to fall through to newMBB
9997 thisMBB->addSuccessor(newMBB);
9999 // newMBB jumps to newMBB and fall through to nextMBB
10000 newMBB->addSuccessor(nextMBB);
10001 newMBB->addSuccessor(newMBB);
10003 DebugLoc dl = mInstr->getDebugLoc();
10004 // Insert instructions into newMBB based on incoming instruction
10005 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10006 "unexpected number of operands");
10007 MachineOperand& destOper = mInstr->getOperand(0);
10008 MachineOperand* argOpers[2 + X86::AddrNumOperands];
10009 int numArgs = mInstr->getNumOperands() - 1;
10010 for (int i=0; i < numArgs; ++i)
10011 argOpers[i] = &mInstr->getOperand(i+1);
10013 // x86 address has 4 operands: base, index, scale, and displacement
10014 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10015 int valArgIndx = lastAddrIndx + 1;
10017 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10018 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10019 for (int i=0; i <= lastAddrIndx; ++i)
10020 (*MIB).addOperand(*argOpers[i]);
10022 // We only support register and immediate values
10023 assert((argOpers[valArgIndx]->isReg() ||
10024 argOpers[valArgIndx]->isImm()) &&
10025 "invalid operand");
10027 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10028 if (argOpers[valArgIndx]->isReg())
10029 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10031 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10032 (*MIB).addOperand(*argOpers[valArgIndx]);
10034 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10037 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10042 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10043 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10047 // Cmp and exchange if none has modified the memory location
10048 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10049 for (int i=0; i <= lastAddrIndx; ++i)
10050 (*MIB).addOperand(*argOpers[i]);
10052 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10053 (*MIB).setMemRefs(mInstr->memoperands_begin(),
10054 mInstr->memoperands_end());
10056 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10057 MIB.addReg(X86::EAX);
10060 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10062 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
10066 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10067 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10068 // in the .td file.
10069 MachineBasicBlock *
10070 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10071 unsigned numArgs, bool memArg) const {
10072 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10073 "Target must have SSE4.2 or AVX features enabled");
10075 DebugLoc dl = MI->getDebugLoc();
10076 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10078 if (!Subtarget->hasAVX()) {
10080 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10082 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10085 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10087 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10090 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10091 for (unsigned i = 0; i < numArgs; ++i) {
10092 MachineOperand &Op = MI->getOperand(i+1);
10093 if (!(Op.isReg() && Op.isImplicit()))
10094 MIB.addOperand(Op);
10096 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10097 .addReg(X86::XMM0);
10099 MI->eraseFromParent();
10103 MachineBasicBlock *
10104 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10105 DebugLoc dl = MI->getDebugLoc();
10106 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10108 // Address into RAX/EAX, other two args into ECX, EDX.
10109 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10110 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10111 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10112 for (int i = 0; i < X86::AddrNumOperands; ++i)
10113 MIB.addOperand(MI->getOperand(i));
10115 unsigned ValOps = X86::AddrNumOperands;
10116 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10117 .addReg(MI->getOperand(ValOps).getReg());
10118 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10119 .addReg(MI->getOperand(ValOps+1).getReg());
10121 // The instruction doesn't actually take any operands though.
10122 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10124 MI->eraseFromParent(); // The pseudo is gone now.
10128 MachineBasicBlock *
10129 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10130 DebugLoc dl = MI->getDebugLoc();
10131 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10133 // First arg in ECX, the second in EAX.
10134 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10135 .addReg(MI->getOperand(0).getReg());
10136 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10137 .addReg(MI->getOperand(1).getReg());
10139 // The instruction doesn't actually take any operands though.
10140 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10142 MI->eraseFromParent(); // The pseudo is gone now.
10146 MachineBasicBlock *
10147 X86TargetLowering::EmitVAARG64WithCustomInserter(
10149 MachineBasicBlock *MBB) const {
10150 // Emit va_arg instruction on X86-64.
10152 // Operands to this pseudo-instruction:
10153 // 0 ) Output : destination address (reg)
10154 // 1-5) Input : va_list address (addr, i64mem)
10155 // 6 ) ArgSize : Size (in bytes) of vararg type
10156 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10157 // 8 ) Align : Alignment of type
10158 // 9 ) EFLAGS (implicit-def)
10160 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10161 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10163 unsigned DestReg = MI->getOperand(0).getReg();
10164 MachineOperand &Base = MI->getOperand(1);
10165 MachineOperand &Scale = MI->getOperand(2);
10166 MachineOperand &Index = MI->getOperand(3);
10167 MachineOperand &Disp = MI->getOperand(4);
10168 MachineOperand &Segment = MI->getOperand(5);
10169 unsigned ArgSize = MI->getOperand(6).getImm();
10170 unsigned ArgMode = MI->getOperand(7).getImm();
10171 unsigned Align = MI->getOperand(8).getImm();
10173 // Memory Reference
10174 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10175 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10176 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10178 // Machine Information
10179 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10180 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10181 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10182 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10183 DebugLoc DL = MI->getDebugLoc();
10185 // struct va_list {
10188 // i64 overflow_area (address)
10189 // i64 reg_save_area (address)
10191 // sizeof(va_list) = 24
10192 // alignment(va_list) = 8
10194 unsigned TotalNumIntRegs = 6;
10195 unsigned TotalNumXMMRegs = 8;
10196 bool UseGPOffset = (ArgMode == 1);
10197 bool UseFPOffset = (ArgMode == 2);
10198 unsigned MaxOffset = TotalNumIntRegs * 8 +
10199 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10201 /* Align ArgSize to a multiple of 8 */
10202 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10203 bool NeedsAlign = (Align > 8);
10205 MachineBasicBlock *thisMBB = MBB;
10206 MachineBasicBlock *overflowMBB;
10207 MachineBasicBlock *offsetMBB;
10208 MachineBasicBlock *endMBB;
10210 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
10211 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
10212 unsigned OffsetReg = 0;
10214 if (!UseGPOffset && !UseFPOffset) {
10215 // If we only pull from the overflow region, we don't create a branch.
10216 // We don't need to alter control flow.
10217 OffsetDestReg = 0; // unused
10218 OverflowDestReg = DestReg;
10221 overflowMBB = thisMBB;
10224 // First emit code to check if gp_offset (or fp_offset) is below the bound.
10225 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10226 // If not, pull from overflow_area. (branch to overflowMBB)
10231 // offsetMBB overflowMBB
10236 // Registers for the PHI in endMBB
10237 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10238 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10240 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10241 MachineFunction *MF = MBB->getParent();
10242 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10243 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10244 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10246 MachineFunction::iterator MBBIter = MBB;
10249 // Insert the new basic blocks
10250 MF->insert(MBBIter, offsetMBB);
10251 MF->insert(MBBIter, overflowMBB);
10252 MF->insert(MBBIter, endMBB);
10254 // Transfer the remainder of MBB and its successor edges to endMBB.
10255 endMBB->splice(endMBB->begin(), thisMBB,
10256 llvm::next(MachineBasicBlock::iterator(MI)),
10258 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10260 // Make offsetMBB and overflowMBB successors of thisMBB
10261 thisMBB->addSuccessor(offsetMBB);
10262 thisMBB->addSuccessor(overflowMBB);
10264 // endMBB is a successor of both offsetMBB and overflowMBB
10265 offsetMBB->addSuccessor(endMBB);
10266 overflowMBB->addSuccessor(endMBB);
10268 // Load the offset value into a register
10269 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10270 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10274 .addDisp(Disp, UseFPOffset ? 4 : 0)
10275 .addOperand(Segment)
10276 .setMemRefs(MMOBegin, MMOEnd);
10278 // Check if there is enough room left to pull this argument.
10279 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10281 .addImm(MaxOffset + 8 - ArgSizeA8);
10283 // Branch to "overflowMBB" if offset >= max
10284 // Fall through to "offsetMBB" otherwise
10285 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10286 .addMBB(overflowMBB);
10289 // In offsetMBB, emit code to use the reg_save_area.
10291 assert(OffsetReg != 0);
10293 // Read the reg_save_area address.
10294 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10295 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10300 .addOperand(Segment)
10301 .setMemRefs(MMOBegin, MMOEnd);
10303 // Zero-extend the offset
10304 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10305 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10308 .addImm(X86::sub_32bit);
10310 // Add the offset to the reg_save_area to get the final address.
10311 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10312 .addReg(OffsetReg64)
10313 .addReg(RegSaveReg);
10315 // Compute the offset for the next argument
10316 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10317 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10319 .addImm(UseFPOffset ? 16 : 8);
10321 // Store it back into the va_list.
10322 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10326 .addDisp(Disp, UseFPOffset ? 4 : 0)
10327 .addOperand(Segment)
10328 .addReg(NextOffsetReg)
10329 .setMemRefs(MMOBegin, MMOEnd);
10332 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10337 // Emit code to use overflow area
10340 // Load the overflow_area address into a register.
10341 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10342 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10347 .addOperand(Segment)
10348 .setMemRefs(MMOBegin, MMOEnd);
10350 // If we need to align it, do so. Otherwise, just copy the address
10351 // to OverflowDestReg.
10353 // Align the overflow address
10354 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10355 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10357 // aligned_addr = (addr + (align-1)) & ~(align-1)
10358 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10359 .addReg(OverflowAddrReg)
10362 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10364 .addImm(~(uint64_t)(Align-1));
10366 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10367 .addReg(OverflowAddrReg);
10370 // Compute the next overflow address after this argument.
10371 // (the overflow address should be kept 8-byte aligned)
10372 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10373 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10374 .addReg(OverflowDestReg)
10375 .addImm(ArgSizeA8);
10377 // Store the new overflow address.
10378 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10383 .addOperand(Segment)
10384 .addReg(NextAddrReg)
10385 .setMemRefs(MMOBegin, MMOEnd);
10387 // If we branched, emit the PHI to the front of endMBB.
10389 BuildMI(*endMBB, endMBB->begin(), DL,
10390 TII->get(X86::PHI), DestReg)
10391 .addReg(OffsetDestReg).addMBB(offsetMBB)
10392 .addReg(OverflowDestReg).addMBB(overflowMBB);
10395 // Erase the pseudo instruction
10396 MI->eraseFromParent();
10401 MachineBasicBlock *
10402 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10404 MachineBasicBlock *MBB) const {
10405 // Emit code to save XMM registers to the stack. The ABI says that the
10406 // number of registers to save is given in %al, so it's theoretically
10407 // possible to do an indirect jump trick to avoid saving all of them,
10408 // however this code takes a simpler approach and just executes all
10409 // of the stores if %al is non-zero. It's less code, and it's probably
10410 // easier on the hardware branch predictor, and stores aren't all that
10411 // expensive anyway.
10413 // Create the new basic blocks. One block contains all the XMM stores,
10414 // and one block is the final destination regardless of whether any
10415 // stores were performed.
10416 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10417 MachineFunction *F = MBB->getParent();
10418 MachineFunction::iterator MBBIter = MBB;
10420 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10421 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10422 F->insert(MBBIter, XMMSaveMBB);
10423 F->insert(MBBIter, EndMBB);
10425 // Transfer the remainder of MBB and its successor edges to EndMBB.
10426 EndMBB->splice(EndMBB->begin(), MBB,
10427 llvm::next(MachineBasicBlock::iterator(MI)),
10429 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10431 // The original block will now fall through to the XMM save block.
10432 MBB->addSuccessor(XMMSaveMBB);
10433 // The XMMSaveMBB will fall through to the end block.
10434 XMMSaveMBB->addSuccessor(EndMBB);
10436 // Now add the instructions.
10437 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10438 DebugLoc DL = MI->getDebugLoc();
10440 unsigned CountReg = MI->getOperand(0).getReg();
10441 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10442 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10444 if (!Subtarget->isTargetWin64()) {
10445 // If %al is 0, branch around the XMM save block.
10446 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10447 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10448 MBB->addSuccessor(EndMBB);
10451 // In the XMM save block, save all the XMM argument registers.
10452 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10453 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10454 MachineMemOperand *MMO =
10455 F->getMachineMemOperand(
10456 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10457 MachineMemOperand::MOStore,
10458 /*Size=*/16, /*Align=*/16);
10459 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10460 .addFrameIndex(RegSaveFrameIndex)
10461 .addImm(/*Scale=*/1)
10462 .addReg(/*IndexReg=*/0)
10463 .addImm(/*Disp=*/Offset)
10464 .addReg(/*Segment=*/0)
10465 .addReg(MI->getOperand(i).getReg())
10466 .addMemOperand(MMO);
10469 MI->eraseFromParent(); // The pseudo instruction is gone now.
10474 MachineBasicBlock *
10475 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10476 MachineBasicBlock *BB) const {
10477 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10478 DebugLoc DL = MI->getDebugLoc();
10480 // To "insert" a SELECT_CC instruction, we actually have to insert the
10481 // diamond control-flow pattern. The incoming instruction knows the
10482 // destination vreg to set, the condition code register to branch on, the
10483 // true/false values to select between, and a branch opcode to use.
10484 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10485 MachineFunction::iterator It = BB;
10491 // cmpTY ccX, r1, r2
10493 // fallthrough --> copy0MBB
10494 MachineBasicBlock *thisMBB = BB;
10495 MachineFunction *F = BB->getParent();
10496 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10497 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10498 F->insert(It, copy0MBB);
10499 F->insert(It, sinkMBB);
10501 // If the EFLAGS register isn't dead in the terminator, then claim that it's
10502 // live into the sink and copy blocks.
10503 const MachineFunction *MF = BB->getParent();
10504 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10505 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10507 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10508 const MachineOperand &MO = MI->getOperand(I);
10509 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10510 unsigned Reg = MO.getReg();
10511 if (Reg != X86::EFLAGS) continue;
10512 copy0MBB->addLiveIn(Reg);
10513 sinkMBB->addLiveIn(Reg);
10516 // Transfer the remainder of BB and its successor edges to sinkMBB.
10517 sinkMBB->splice(sinkMBB->begin(), BB,
10518 llvm::next(MachineBasicBlock::iterator(MI)),
10520 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10522 // Add the true and fallthrough blocks as its successors.
10523 BB->addSuccessor(copy0MBB);
10524 BB->addSuccessor(sinkMBB);
10526 // Create the conditional branch instruction.
10528 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10529 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10532 // %FalseValue = ...
10533 // # fallthrough to sinkMBB
10534 copy0MBB->addSuccessor(sinkMBB);
10537 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10539 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10540 TII->get(X86::PHI), MI->getOperand(0).getReg())
10541 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10542 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10544 MI->eraseFromParent(); // The pseudo instruction is gone now.
10548 MachineBasicBlock *
10549 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10550 MachineBasicBlock *BB) const {
10551 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10552 DebugLoc DL = MI->getDebugLoc();
10554 assert(!Subtarget->isTargetEnvMacho());
10556 // The lowering is pretty easy: we're just emitting the call to _alloca. The
10557 // non-trivial part is impdef of ESP.
10559 if (Subtarget->isTargetWin64()) {
10560 if (Subtarget->isTargetCygMing()) {
10561 // ___chkstk(Mingw64):
10562 // Clobbers R10, R11, RAX and EFLAGS.
10564 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10565 .addExternalSymbol("___chkstk")
10566 .addReg(X86::RAX, RegState::Implicit)
10567 .addReg(X86::RSP, RegState::Implicit)
10568 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10569 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10570 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10572 // __chkstk(MSVCRT): does not update stack pointer.
10573 // Clobbers R10, R11 and EFLAGS.
10574 // FIXME: RAX(allocated size) might be reused and not killed.
10575 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10576 .addExternalSymbol("__chkstk")
10577 .addReg(X86::RAX, RegState::Implicit)
10578 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10579 // RAX has the offset to subtracted from RSP.
10580 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10585 const char *StackProbeSymbol =
10586 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10588 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10589 .addExternalSymbol(StackProbeSymbol)
10590 .addReg(X86::EAX, RegState::Implicit)
10591 .addReg(X86::ESP, RegState::Implicit)
10592 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10593 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10594 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10597 MI->eraseFromParent(); // The pseudo instruction is gone now.
10601 MachineBasicBlock *
10602 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10603 MachineBasicBlock *BB) const {
10604 // This is pretty easy. We're taking the value that we received from
10605 // our load from the relocation, sticking it in either RDI (x86-64)
10606 // or EAX and doing an indirect call. The return value will then
10607 // be in the normal return register.
10608 const X86InstrInfo *TII
10609 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10610 DebugLoc DL = MI->getDebugLoc();
10611 MachineFunction *F = BB->getParent();
10613 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10614 assert(MI->getOperand(3).isGlobal() && "This should be a global");
10616 if (Subtarget->is64Bit()) {
10617 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10618 TII->get(X86::MOV64rm), X86::RDI)
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::CALL64m));
10625 addDirectMem(MIB, X86::RDI);
10626 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10627 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10628 TII->get(X86::MOV32rm), X86::EAX)
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);
10637 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10638 TII->get(X86::MOV32rm), X86::EAX)
10639 .addReg(TII->getGlobalBaseReg(F))
10640 .addImm(0).addReg(0)
10641 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10642 MI->getOperand(3).getTargetFlags())
10644 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10645 addDirectMem(MIB, X86::EAX);
10648 MI->eraseFromParent(); // The pseudo instruction is gone now.
10652 MachineBasicBlock *
10653 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10654 MachineBasicBlock *BB) const {
10655 switch (MI->getOpcode()) {
10656 default: assert(false && "Unexpected instr type to insert");
10657 case X86::TAILJMPd64:
10658 case X86::TAILJMPr64:
10659 case X86::TAILJMPm64:
10660 assert(!"TAILJMP64 would not be touched here.");
10661 case X86::TCRETURNdi64:
10662 case X86::TCRETURNri64:
10663 case X86::TCRETURNmi64:
10664 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10665 // On AMD64, additional defs should be added before register allocation.
10666 if (!Subtarget->isTargetWin64()) {
10667 MI->addRegisterDefined(X86::RSI);
10668 MI->addRegisterDefined(X86::RDI);
10669 MI->addRegisterDefined(X86::XMM6);
10670 MI->addRegisterDefined(X86::XMM7);
10671 MI->addRegisterDefined(X86::XMM8);
10672 MI->addRegisterDefined(X86::XMM9);
10673 MI->addRegisterDefined(X86::XMM10);
10674 MI->addRegisterDefined(X86::XMM11);
10675 MI->addRegisterDefined(X86::XMM12);
10676 MI->addRegisterDefined(X86::XMM13);
10677 MI->addRegisterDefined(X86::XMM14);
10678 MI->addRegisterDefined(X86::XMM15);
10681 case X86::WIN_ALLOCA:
10682 return EmitLoweredWinAlloca(MI, BB);
10683 case X86::TLSCall_32:
10684 case X86::TLSCall_64:
10685 return EmitLoweredTLSCall(MI, BB);
10686 case X86::CMOV_GR8:
10687 case X86::CMOV_FR32:
10688 case X86::CMOV_FR64:
10689 case X86::CMOV_V4F32:
10690 case X86::CMOV_V2F64:
10691 case X86::CMOV_V2I64:
10692 case X86::CMOV_GR16:
10693 case X86::CMOV_GR32:
10694 case X86::CMOV_RFP32:
10695 case X86::CMOV_RFP64:
10696 case X86::CMOV_RFP80:
10697 return EmitLoweredSelect(MI, BB);
10699 case X86::FP32_TO_INT16_IN_MEM:
10700 case X86::FP32_TO_INT32_IN_MEM:
10701 case X86::FP32_TO_INT64_IN_MEM:
10702 case X86::FP64_TO_INT16_IN_MEM:
10703 case X86::FP64_TO_INT32_IN_MEM:
10704 case X86::FP64_TO_INT64_IN_MEM:
10705 case X86::FP80_TO_INT16_IN_MEM:
10706 case X86::FP80_TO_INT32_IN_MEM:
10707 case X86::FP80_TO_INT64_IN_MEM: {
10708 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10709 DebugLoc DL = MI->getDebugLoc();
10711 // Change the floating point control register to use "round towards zero"
10712 // mode when truncating to an integer value.
10713 MachineFunction *F = BB->getParent();
10714 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10715 addFrameReference(BuildMI(*BB, MI, DL,
10716 TII->get(X86::FNSTCW16m)), CWFrameIdx);
10718 // Load the old value of the high byte of the control word...
10720 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10721 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10724 // Set the high part to be round to zero...
10725 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10728 // Reload the modified control word now...
10729 addFrameReference(BuildMI(*BB, MI, DL,
10730 TII->get(X86::FLDCW16m)), CWFrameIdx);
10732 // Restore the memory image of control word to original value
10733 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10736 // Get the X86 opcode to use.
10738 switch (MI->getOpcode()) {
10739 default: llvm_unreachable("illegal opcode!");
10740 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10741 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10742 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10743 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10744 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10745 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10746 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10747 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10748 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10752 MachineOperand &Op = MI->getOperand(0);
10754 AM.BaseType = X86AddressMode::RegBase;
10755 AM.Base.Reg = Op.getReg();
10757 AM.BaseType = X86AddressMode::FrameIndexBase;
10758 AM.Base.FrameIndex = Op.getIndex();
10760 Op = MI->getOperand(1);
10762 AM.Scale = Op.getImm();
10763 Op = MI->getOperand(2);
10765 AM.IndexReg = Op.getImm();
10766 Op = MI->getOperand(3);
10767 if (Op.isGlobal()) {
10768 AM.GV = Op.getGlobal();
10770 AM.Disp = Op.getImm();
10772 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10773 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10775 // Reload the original control word now.
10776 addFrameReference(BuildMI(*BB, MI, DL,
10777 TII->get(X86::FLDCW16m)), CWFrameIdx);
10779 MI->eraseFromParent(); // The pseudo instruction is gone now.
10782 // String/text processing lowering.
10783 case X86::PCMPISTRM128REG:
10784 case X86::VPCMPISTRM128REG:
10785 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10786 case X86::PCMPISTRM128MEM:
10787 case X86::VPCMPISTRM128MEM:
10788 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10789 case X86::PCMPESTRM128REG:
10790 case X86::VPCMPESTRM128REG:
10791 return EmitPCMP(MI, BB, 5, false /* in mem */);
10792 case X86::PCMPESTRM128MEM:
10793 case X86::VPCMPESTRM128MEM:
10794 return EmitPCMP(MI, BB, 5, true /* in mem */);
10796 // Thread synchronization.
10798 return EmitMonitor(MI, BB);
10800 return EmitMwait(MI, BB);
10802 // Atomic Lowering.
10803 case X86::ATOMAND32:
10804 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10805 X86::AND32ri, X86::MOV32rm,
10807 X86::NOT32r, X86::EAX,
10808 X86::GR32RegisterClass);
10809 case X86::ATOMOR32:
10810 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10811 X86::OR32ri, X86::MOV32rm,
10813 X86::NOT32r, X86::EAX,
10814 X86::GR32RegisterClass);
10815 case X86::ATOMXOR32:
10816 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10817 X86::XOR32ri, X86::MOV32rm,
10819 X86::NOT32r, X86::EAX,
10820 X86::GR32RegisterClass);
10821 case X86::ATOMNAND32:
10822 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10823 X86::AND32ri, X86::MOV32rm,
10825 X86::NOT32r, X86::EAX,
10826 X86::GR32RegisterClass, true);
10827 case X86::ATOMMIN32:
10828 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10829 case X86::ATOMMAX32:
10830 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10831 case X86::ATOMUMIN32:
10832 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10833 case X86::ATOMUMAX32:
10834 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10836 case X86::ATOMAND16:
10837 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10838 X86::AND16ri, X86::MOV16rm,
10840 X86::NOT16r, X86::AX,
10841 X86::GR16RegisterClass);
10842 case X86::ATOMOR16:
10843 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10844 X86::OR16ri, X86::MOV16rm,
10846 X86::NOT16r, X86::AX,
10847 X86::GR16RegisterClass);
10848 case X86::ATOMXOR16:
10849 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10850 X86::XOR16ri, X86::MOV16rm,
10852 X86::NOT16r, X86::AX,
10853 X86::GR16RegisterClass);
10854 case X86::ATOMNAND16:
10855 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10856 X86::AND16ri, X86::MOV16rm,
10858 X86::NOT16r, X86::AX,
10859 X86::GR16RegisterClass, true);
10860 case X86::ATOMMIN16:
10861 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10862 case X86::ATOMMAX16:
10863 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10864 case X86::ATOMUMIN16:
10865 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10866 case X86::ATOMUMAX16:
10867 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10869 case X86::ATOMAND8:
10870 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10871 X86::AND8ri, X86::MOV8rm,
10873 X86::NOT8r, X86::AL,
10874 X86::GR8RegisterClass);
10876 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10877 X86::OR8ri, X86::MOV8rm,
10879 X86::NOT8r, X86::AL,
10880 X86::GR8RegisterClass);
10881 case X86::ATOMXOR8:
10882 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10883 X86::XOR8ri, X86::MOV8rm,
10885 X86::NOT8r, X86::AL,
10886 X86::GR8RegisterClass);
10887 case X86::ATOMNAND8:
10888 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10889 X86::AND8ri, X86::MOV8rm,
10891 X86::NOT8r, X86::AL,
10892 X86::GR8RegisterClass, true);
10893 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10894 // This group is for 64-bit host.
10895 case X86::ATOMAND64:
10896 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10897 X86::AND64ri32, X86::MOV64rm,
10899 X86::NOT64r, X86::RAX,
10900 X86::GR64RegisterClass);
10901 case X86::ATOMOR64:
10902 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10903 X86::OR64ri32, X86::MOV64rm,
10905 X86::NOT64r, X86::RAX,
10906 X86::GR64RegisterClass);
10907 case X86::ATOMXOR64:
10908 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10909 X86::XOR64ri32, X86::MOV64rm,
10911 X86::NOT64r, X86::RAX,
10912 X86::GR64RegisterClass);
10913 case X86::ATOMNAND64:
10914 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10915 X86::AND64ri32, X86::MOV64rm,
10917 X86::NOT64r, X86::RAX,
10918 X86::GR64RegisterClass, true);
10919 case X86::ATOMMIN64:
10920 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10921 case X86::ATOMMAX64:
10922 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10923 case X86::ATOMUMIN64:
10924 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10925 case X86::ATOMUMAX64:
10926 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10928 // This group does 64-bit operations on a 32-bit host.
10929 case X86::ATOMAND6432:
10930 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10931 X86::AND32rr, X86::AND32rr,
10932 X86::AND32ri, X86::AND32ri,
10934 case X86::ATOMOR6432:
10935 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10936 X86::OR32rr, X86::OR32rr,
10937 X86::OR32ri, X86::OR32ri,
10939 case X86::ATOMXOR6432:
10940 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10941 X86::XOR32rr, X86::XOR32rr,
10942 X86::XOR32ri, X86::XOR32ri,
10944 case X86::ATOMNAND6432:
10945 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10946 X86::AND32rr, X86::AND32rr,
10947 X86::AND32ri, X86::AND32ri,
10949 case X86::ATOMADD6432:
10950 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10951 X86::ADD32rr, X86::ADC32rr,
10952 X86::ADD32ri, X86::ADC32ri,
10954 case X86::ATOMSUB6432:
10955 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10956 X86::SUB32rr, X86::SBB32rr,
10957 X86::SUB32ri, X86::SBB32ri,
10959 case X86::ATOMSWAP6432:
10960 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10961 X86::MOV32rr, X86::MOV32rr,
10962 X86::MOV32ri, X86::MOV32ri,
10964 case X86::VASTART_SAVE_XMM_REGS:
10965 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10967 case X86::VAARG_64:
10968 return EmitVAARG64WithCustomInserter(MI, BB);
10972 //===----------------------------------------------------------------------===//
10973 // X86 Optimization Hooks
10974 //===----------------------------------------------------------------------===//
10976 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10980 const SelectionDAG &DAG,
10981 unsigned Depth) const {
10982 unsigned Opc = Op.getOpcode();
10983 assert((Opc >= ISD::BUILTIN_OP_END ||
10984 Opc == ISD::INTRINSIC_WO_CHAIN ||
10985 Opc == ISD::INTRINSIC_W_CHAIN ||
10986 Opc == ISD::INTRINSIC_VOID) &&
10987 "Should use MaskedValueIsZero if you don't know whether Op"
10988 " is a target node!");
10990 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
11004 // These nodes' second result is a boolean.
11005 if (Op.getResNo() == 0)
11008 case X86ISD::SETCC:
11009 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11010 Mask.getBitWidth() - 1);
11015 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11016 unsigned Depth) const {
11017 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11018 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11019 return Op.getValueType().getScalarType().getSizeInBits();
11025 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11026 /// node is a GlobalAddress + offset.
11027 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11028 const GlobalValue* &GA,
11029 int64_t &Offset) const {
11030 if (N->getOpcode() == X86ISD::Wrapper) {
11031 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11032 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11033 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11037 return TargetLowering::isGAPlusOffset(N, GA, Offset);
11040 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
11041 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
11042 /// if the load addresses are consecutive, non-overlapping, and in the right
11044 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11045 TargetLowering::DAGCombinerInfo &DCI) {
11046 DebugLoc dl = N->getDebugLoc();
11047 EVT VT = N->getValueType(0);
11049 if (VT.getSizeInBits() != 128)
11052 // Don't create instructions with illegal types after legalize types has run.
11053 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11054 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11057 SmallVector<SDValue, 16> Elts;
11058 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11059 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11061 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11064 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11065 /// generation and convert it from being a bunch of shuffles and extracts
11066 /// to a simple store and scalar loads to extract the elements.
11067 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11068 const TargetLowering &TLI) {
11069 SDValue InputVector = N->getOperand(0);
11071 // Only operate on vectors of 4 elements, where the alternative shuffling
11072 // gets to be more expensive.
11073 if (InputVector.getValueType() != MVT::v4i32)
11076 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11077 // single use which is a sign-extend or zero-extend, and all elements are
11079 SmallVector<SDNode *, 4> Uses;
11080 unsigned ExtractedElements = 0;
11081 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11082 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11083 if (UI.getUse().getResNo() != InputVector.getResNo())
11086 SDNode *Extract = *UI;
11087 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11090 if (Extract->getValueType(0) != MVT::i32)
11092 if (!Extract->hasOneUse())
11094 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11095 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11097 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11100 // Record which element was extracted.
11101 ExtractedElements |=
11102 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11104 Uses.push_back(Extract);
11107 // If not all the elements were used, this may not be worthwhile.
11108 if (ExtractedElements != 15)
11111 // Ok, we've now decided to do the transformation.
11112 DebugLoc dl = InputVector.getDebugLoc();
11114 // Store the value to a temporary stack slot.
11115 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11116 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11117 MachinePointerInfo(), false, false, 0);
11119 // Replace each use (extract) with a load of the appropriate element.
11120 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11121 UE = Uses.end(); UI != UE; ++UI) {
11122 SDNode *Extract = *UI;
11124 // cOMpute the element's address.
11125 SDValue Idx = Extract->getOperand(1);
11127 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11128 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11129 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11131 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11132 StackPtr, OffsetVal);
11134 // Load the scalar.
11135 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11136 ScalarAddr, MachinePointerInfo(),
11139 // Replace the exact with the load.
11140 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11143 // The replacement was made in place; don't return anything.
11147 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11148 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11149 const X86Subtarget *Subtarget) {
11150 DebugLoc DL = N->getDebugLoc();
11151 SDValue Cond = N->getOperand(0);
11152 // Get the LHS/RHS of the select.
11153 SDValue LHS = N->getOperand(1);
11154 SDValue RHS = N->getOperand(2);
11156 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11157 // instructions match the semantics of the common C idiom x<y?x:y but not
11158 // x<=y?x:y, because of how they handle negative zero (which can be
11159 // ignored in unsafe-math mode).
11160 if (Subtarget->hasSSE2() &&
11161 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11162 Cond.getOpcode() == ISD::SETCC) {
11163 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11165 unsigned Opcode = 0;
11166 // Check for x CC y ? x : y.
11167 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11168 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11172 // Converting this to a min would handle NaNs incorrectly, and swapping
11173 // the operands would cause it to handle comparisons between positive
11174 // and negative zero incorrectly.
11175 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11176 if (!UnsafeFPMath &&
11177 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11179 std::swap(LHS, RHS);
11181 Opcode = X86ISD::FMIN;
11184 // Converting this to a min would handle comparisons between positive
11185 // and negative zero incorrectly.
11186 if (!UnsafeFPMath &&
11187 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11189 Opcode = X86ISD::FMIN;
11192 // Converting this to a min would handle both negative zeros and NaNs
11193 // incorrectly, but we can swap the operands to fix both.
11194 std::swap(LHS, RHS);
11198 Opcode = X86ISD::FMIN;
11202 // Converting this to a max would handle comparisons between positive
11203 // and negative zero incorrectly.
11204 if (!UnsafeFPMath &&
11205 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11207 Opcode = X86ISD::FMAX;
11210 // Converting this to a max would handle NaNs incorrectly, and swapping
11211 // the operands would cause it to handle comparisons between positive
11212 // and negative zero incorrectly.
11213 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11214 if (!UnsafeFPMath &&
11215 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11217 std::swap(LHS, RHS);
11219 Opcode = X86ISD::FMAX;
11222 // Converting this to a max would handle both negative zeros and NaNs
11223 // incorrectly, but we can swap the operands to fix both.
11224 std::swap(LHS, RHS);
11228 Opcode = X86ISD::FMAX;
11231 // Check for x CC y ? y : x -- a min/max with reversed arms.
11232 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11233 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11237 // Converting this to a min would handle comparisons between positive
11238 // and negative zero incorrectly, and swapping the operands would
11239 // cause it to handle NaNs incorrectly.
11240 if (!UnsafeFPMath &&
11241 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11242 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11244 std::swap(LHS, RHS);
11246 Opcode = X86ISD::FMIN;
11249 // Converting this to a min would handle NaNs incorrectly.
11250 if (!UnsafeFPMath &&
11251 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11253 Opcode = X86ISD::FMIN;
11256 // Converting this to a min would handle both negative zeros and NaNs
11257 // incorrectly, but we can swap the operands to fix both.
11258 std::swap(LHS, RHS);
11262 Opcode = X86ISD::FMIN;
11266 // Converting this to a max would handle NaNs incorrectly.
11267 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11269 Opcode = X86ISD::FMAX;
11272 // Converting this to a max would handle comparisons between positive
11273 // and negative zero incorrectly, and swapping the operands would
11274 // cause it to handle NaNs incorrectly.
11275 if (!UnsafeFPMath &&
11276 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11277 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11279 std::swap(LHS, RHS);
11281 Opcode = X86ISD::FMAX;
11284 // Converting this to a max would handle both negative zeros and NaNs
11285 // incorrectly, but we can swap the operands to fix both.
11286 std::swap(LHS, RHS);
11290 Opcode = X86ISD::FMAX;
11296 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11299 // If this is a select between two integer constants, try to do some
11301 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11302 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11303 // Don't do this for crazy integer types.
11304 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11305 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11306 // so that TrueC (the true value) is larger than FalseC.
11307 bool NeedsCondInvert = false;
11309 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11310 // Efficiently invertible.
11311 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
11312 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
11313 isa<ConstantSDNode>(Cond.getOperand(1))))) {
11314 NeedsCondInvert = true;
11315 std::swap(TrueC, FalseC);
11318 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
11319 if (FalseC->getAPIntValue() == 0 &&
11320 TrueC->getAPIntValue().isPowerOf2()) {
11321 if (NeedsCondInvert) // Invert the condition if needed.
11322 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11323 DAG.getConstant(1, Cond.getValueType()));
11325 // Zero extend the condition if needed.
11326 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11328 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11329 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11330 DAG.getConstant(ShAmt, MVT::i8));
11333 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11334 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11335 if (NeedsCondInvert) // Invert the condition if needed.
11336 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11337 DAG.getConstant(1, Cond.getValueType()));
11339 // Zero extend the condition if needed.
11340 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11341 FalseC->getValueType(0), Cond);
11342 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11343 SDValue(FalseC, 0));
11346 // Optimize cases that will turn into an LEA instruction. This requires
11347 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11348 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11349 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11350 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11352 bool isFastMultiplier = false;
11354 switch ((unsigned char)Diff) {
11356 case 1: // result = add base, cond
11357 case 2: // result = lea base( , cond*2)
11358 case 3: // result = lea base(cond, cond*2)
11359 case 4: // result = lea base( , cond*4)
11360 case 5: // result = lea base(cond, cond*4)
11361 case 8: // result = lea base( , cond*8)
11362 case 9: // result = lea base(cond, cond*8)
11363 isFastMultiplier = true;
11368 if (isFastMultiplier) {
11369 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11370 if (NeedsCondInvert) // Invert the condition if needed.
11371 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11372 DAG.getConstant(1, Cond.getValueType()));
11374 // Zero extend the condition if needed.
11375 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11377 // Scale the condition by the difference.
11379 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11380 DAG.getConstant(Diff, Cond.getValueType()));
11382 // Add the base if non-zero.
11383 if (FalseC->getAPIntValue() != 0)
11384 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11385 SDValue(FalseC, 0));
11395 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11396 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11397 TargetLowering::DAGCombinerInfo &DCI) {
11398 DebugLoc DL = N->getDebugLoc();
11400 // If the flag operand isn't dead, don't touch this CMOV.
11401 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11404 SDValue FalseOp = N->getOperand(0);
11405 SDValue TrueOp = N->getOperand(1);
11406 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11407 SDValue Cond = N->getOperand(3);
11408 if (CC == X86::COND_E || CC == X86::COND_NE) {
11409 switch (Cond.getOpcode()) {
11413 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11414 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11415 return (CC == X86::COND_E) ? FalseOp : TrueOp;
11419 // If this is a select between two integer constants, try to do some
11420 // optimizations. Note that the operands are ordered the opposite of SELECT
11422 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11423 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11424 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11425 // larger than FalseC (the false value).
11426 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11427 CC = X86::GetOppositeBranchCondition(CC);
11428 std::swap(TrueC, FalseC);
11431 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
11432 // This is efficient for any integer data type (including i8/i16) and
11434 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11435 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11436 DAG.getConstant(CC, MVT::i8), Cond);
11438 // Zero extend the condition if needed.
11439 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11441 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11442 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11443 DAG.getConstant(ShAmt, MVT::i8));
11444 if (N->getNumValues() == 2) // Dead flag value?
11445 return DCI.CombineTo(N, Cond, SDValue());
11449 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
11450 // for any integer data type, including i8/i16.
11451 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11452 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11453 DAG.getConstant(CC, MVT::i8), Cond);
11455 // Zero extend the condition if needed.
11456 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11457 FalseC->getValueType(0), Cond);
11458 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11459 SDValue(FalseC, 0));
11461 if (N->getNumValues() == 2) // Dead flag value?
11462 return DCI.CombineTo(N, Cond, SDValue());
11466 // Optimize cases that will turn into an LEA instruction. This requires
11467 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11468 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11469 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11470 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11472 bool isFastMultiplier = false;
11474 switch ((unsigned char)Diff) {
11476 case 1: // result = add base, cond
11477 case 2: // result = lea base( , cond*2)
11478 case 3: // result = lea base(cond, cond*2)
11479 case 4: // result = lea base( , cond*4)
11480 case 5: // result = lea base(cond, cond*4)
11481 case 8: // result = lea base( , cond*8)
11482 case 9: // result = lea base(cond, cond*8)
11483 isFastMultiplier = true;
11488 if (isFastMultiplier) {
11489 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11490 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11491 DAG.getConstant(CC, MVT::i8), Cond);
11492 // Zero extend the condition if needed.
11493 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11495 // Scale the condition by the difference.
11497 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11498 DAG.getConstant(Diff, Cond.getValueType()));
11500 // Add the base if non-zero.
11501 if (FalseC->getAPIntValue() != 0)
11502 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11503 SDValue(FalseC, 0));
11504 if (N->getNumValues() == 2) // Dead flag value?
11505 return DCI.CombineTo(N, Cond, SDValue());
11515 /// PerformMulCombine - Optimize a single multiply with constant into two
11516 /// in order to implement it with two cheaper instructions, e.g.
11517 /// LEA + SHL, LEA + LEA.
11518 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11519 TargetLowering::DAGCombinerInfo &DCI) {
11520 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11523 EVT VT = N->getValueType(0);
11524 if (VT != MVT::i64)
11527 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11530 uint64_t MulAmt = C->getZExtValue();
11531 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11534 uint64_t MulAmt1 = 0;
11535 uint64_t MulAmt2 = 0;
11536 if ((MulAmt % 9) == 0) {
11538 MulAmt2 = MulAmt / 9;
11539 } else if ((MulAmt % 5) == 0) {
11541 MulAmt2 = MulAmt / 5;
11542 } else if ((MulAmt % 3) == 0) {
11544 MulAmt2 = MulAmt / 3;
11547 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11548 DebugLoc DL = N->getDebugLoc();
11550 if (isPowerOf2_64(MulAmt2) &&
11551 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11552 // If second multiplifer is pow2, issue it first. We want the multiply by
11553 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11555 std::swap(MulAmt1, MulAmt2);
11558 if (isPowerOf2_64(MulAmt1))
11559 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11560 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11562 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11563 DAG.getConstant(MulAmt1, VT));
11565 if (isPowerOf2_64(MulAmt2))
11566 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11567 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11569 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11570 DAG.getConstant(MulAmt2, VT));
11572 // Do not add new nodes to DAG combiner worklist.
11573 DCI.CombineTo(N, NewMul, false);
11578 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11579 SDValue N0 = N->getOperand(0);
11580 SDValue N1 = N->getOperand(1);
11581 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11582 EVT VT = N0.getValueType();
11584 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11585 // since the result of setcc_c is all zero's or all ones.
11586 if (N1C && N0.getOpcode() == ISD::AND &&
11587 N0.getOperand(1).getOpcode() == ISD::Constant) {
11588 SDValue N00 = N0.getOperand(0);
11589 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11590 ((N00.getOpcode() == ISD::ANY_EXTEND ||
11591 N00.getOpcode() == ISD::ZERO_EXTEND) &&
11592 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11593 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11594 APInt ShAmt = N1C->getAPIntValue();
11595 Mask = Mask.shl(ShAmt);
11597 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11598 N00, DAG.getConstant(Mask, VT));
11605 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11607 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11608 const X86Subtarget *Subtarget) {
11609 EVT VT = N->getValueType(0);
11610 if (!VT.isVector() && VT.isInteger() &&
11611 N->getOpcode() == ISD::SHL)
11612 return PerformSHLCombine(N, DAG);
11614 // On X86 with SSE2 support, we can transform this to a vector shift if
11615 // all elements are shifted by the same amount. We can't do this in legalize
11616 // because the a constant vector is typically transformed to a constant pool
11617 // so we have no knowledge of the shift amount.
11618 if (!Subtarget->hasSSE2())
11621 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11624 SDValue ShAmtOp = N->getOperand(1);
11625 EVT EltVT = VT.getVectorElementType();
11626 DebugLoc DL = N->getDebugLoc();
11627 SDValue BaseShAmt = SDValue();
11628 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11629 unsigned NumElts = VT.getVectorNumElements();
11631 for (; i != NumElts; ++i) {
11632 SDValue Arg = ShAmtOp.getOperand(i);
11633 if (Arg.getOpcode() == ISD::UNDEF) continue;
11637 for (; i != NumElts; ++i) {
11638 SDValue Arg = ShAmtOp.getOperand(i);
11639 if (Arg.getOpcode() == ISD::UNDEF) continue;
11640 if (Arg != BaseShAmt) {
11644 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11645 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11646 SDValue InVec = ShAmtOp.getOperand(0);
11647 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11648 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11650 for (; i != NumElts; ++i) {
11651 SDValue Arg = InVec.getOperand(i);
11652 if (Arg.getOpcode() == ISD::UNDEF) continue;
11656 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11657 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11658 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11659 if (C->getZExtValue() == SplatIdx)
11660 BaseShAmt = InVec.getOperand(1);
11663 if (BaseShAmt.getNode() == 0)
11664 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11665 DAG.getIntPtrConstant(0));
11669 // The shift amount is an i32.
11670 if (EltVT.bitsGT(MVT::i32))
11671 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11672 else if (EltVT.bitsLT(MVT::i32))
11673 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11675 // The shift amount is identical so we can do a vector shift.
11676 SDValue ValOp = N->getOperand(0);
11677 switch (N->getOpcode()) {
11679 llvm_unreachable("Unknown shift opcode!");
11682 if (VT == MVT::v2i64)
11683 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11684 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11686 if (VT == MVT::v4i32)
11687 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11688 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11690 if (VT == MVT::v8i16)
11691 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11692 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11696 if (VT == MVT::v4i32)
11697 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11698 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11700 if (VT == MVT::v8i16)
11701 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11702 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11706 if (VT == MVT::v2i64)
11707 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11708 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11710 if (VT == MVT::v4i32)
11711 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11712 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11714 if (VT == MVT::v8i16)
11715 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11716 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11724 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
11725 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
11726 // and friends. Likewise for OR -> CMPNEQSS.
11727 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
11728 TargetLowering::DAGCombinerInfo &DCI,
11729 const X86Subtarget *Subtarget) {
11732 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
11733 // we're requiring SSE2 for both.
11734 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
11735 SDValue N0 = N->getOperand(0);
11736 SDValue N1 = N->getOperand(1);
11737 SDValue CMP0 = N0->getOperand(1);
11738 SDValue CMP1 = N1->getOperand(1);
11739 DebugLoc DL = N->getDebugLoc();
11741 // The SETCCs should both refer to the same CMP.
11742 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
11745 SDValue CMP00 = CMP0->getOperand(0);
11746 SDValue CMP01 = CMP0->getOperand(1);
11747 EVT VT = CMP00.getValueType();
11749 if (VT == MVT::f32 || VT == MVT::f64) {
11750 bool ExpectingFlags = false;
11751 // Check for any users that want flags:
11752 for (SDNode::use_iterator UI = N->use_begin(),
11754 !ExpectingFlags && UI != UE; ++UI)
11755 switch (UI->getOpcode()) {
11760 ExpectingFlags = true;
11762 case ISD::CopyToReg:
11763 case ISD::SIGN_EXTEND:
11764 case ISD::ZERO_EXTEND:
11765 case ISD::ANY_EXTEND:
11769 if (!ExpectingFlags) {
11770 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
11771 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
11773 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
11774 X86::CondCode tmp = cc0;
11779 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
11780 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
11781 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
11782 X86ISD::NodeType NTOperator = is64BitFP ?
11783 X86ISD::FSETCCsd : X86ISD::FSETCCss;
11784 // FIXME: need symbolic constants for these magic numbers.
11785 // See X86ATTInstPrinter.cpp:printSSECC().
11786 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
11787 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
11788 DAG.getConstant(x86cc, MVT::i8));
11789 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
11791 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
11792 DAG.getConstant(1, MVT::i32));
11793 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
11794 return OneBitOfTruth;
11802 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11803 TargetLowering::DAGCombinerInfo &DCI,
11804 const X86Subtarget *Subtarget) {
11805 if (DCI.isBeforeLegalizeOps())
11808 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11812 // Want to form PANDN nodes, in the hopes of then easily combining them with
11813 // OR and AND nodes to form PBLEND/PSIGN.
11814 EVT VT = N->getValueType(0);
11815 if (VT != MVT::v2i64)
11818 SDValue N0 = N->getOperand(0);
11819 SDValue N1 = N->getOperand(1);
11820 DebugLoc DL = N->getDebugLoc();
11822 // Check LHS for vnot
11823 if (N0.getOpcode() == ISD::XOR &&
11824 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11825 return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11827 // Check RHS for vnot
11828 if (N1.getOpcode() == ISD::XOR &&
11829 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11830 return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11835 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11836 TargetLowering::DAGCombinerInfo &DCI,
11837 const X86Subtarget *Subtarget) {
11838 if (DCI.isBeforeLegalizeOps())
11841 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11845 EVT VT = N->getValueType(0);
11846 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11849 SDValue N0 = N->getOperand(0);
11850 SDValue N1 = N->getOperand(1);
11852 // look for psign/blend
11853 if (Subtarget->hasSSSE3()) {
11854 if (VT == MVT::v2i64) {
11855 // Canonicalize pandn to RHS
11856 if (N0.getOpcode() == X86ISD::PANDN)
11858 // or (and (m, x), (pandn m, y))
11859 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11860 SDValue Mask = N1.getOperand(0);
11861 SDValue X = N1.getOperand(1);
11863 if (N0.getOperand(0) == Mask)
11864 Y = N0.getOperand(1);
11865 if (N0.getOperand(1) == Mask)
11866 Y = N0.getOperand(0);
11868 // Check to see if the mask appeared in both the AND and PANDN and
11872 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11873 if (Mask.getOpcode() != ISD::BITCAST ||
11874 X.getOpcode() != ISD::BITCAST ||
11875 Y.getOpcode() != ISD::BITCAST)
11878 // Look through mask bitcast.
11879 Mask = Mask.getOperand(0);
11880 EVT MaskVT = Mask.getValueType();
11882 // Validate that the Mask operand is a vector sra node. The sra node
11883 // will be an intrinsic.
11884 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11887 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11888 // there is no psrai.b
11889 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11890 case Intrinsic::x86_sse2_psrai_w:
11891 case Intrinsic::x86_sse2_psrai_d:
11893 default: return SDValue();
11896 // Check that the SRA is all signbits.
11897 SDValue SraC = Mask.getOperand(2);
11898 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
11899 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11900 if ((SraAmt + 1) != EltBits)
11903 DebugLoc DL = N->getDebugLoc();
11905 // Now we know we at least have a plendvb with the mask val. See if
11906 // we can form a psignb/w/d.
11907 // psign = x.type == y.type == mask.type && y = sub(0, x);
11908 X = X.getOperand(0);
11909 Y = Y.getOperand(0);
11910 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11911 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11912 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11915 case 8: Opc = X86ISD::PSIGNB; break;
11916 case 16: Opc = X86ISD::PSIGNW; break;
11917 case 32: Opc = X86ISD::PSIGND; break;
11921 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11922 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11925 // PBLENDVB only available on SSE 4.1
11926 if (!Subtarget->hasSSE41())
11929 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11930 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11931 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11932 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11933 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11938 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11939 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11941 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11943 if (!N0.hasOneUse() || !N1.hasOneUse())
11946 SDValue ShAmt0 = N0.getOperand(1);
11947 if (ShAmt0.getValueType() != MVT::i8)
11949 SDValue ShAmt1 = N1.getOperand(1);
11950 if (ShAmt1.getValueType() != MVT::i8)
11952 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11953 ShAmt0 = ShAmt0.getOperand(0);
11954 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11955 ShAmt1 = ShAmt1.getOperand(0);
11957 DebugLoc DL = N->getDebugLoc();
11958 unsigned Opc = X86ISD::SHLD;
11959 SDValue Op0 = N0.getOperand(0);
11960 SDValue Op1 = N1.getOperand(0);
11961 if (ShAmt0.getOpcode() == ISD::SUB) {
11962 Opc = X86ISD::SHRD;
11963 std::swap(Op0, Op1);
11964 std::swap(ShAmt0, ShAmt1);
11967 unsigned Bits = VT.getSizeInBits();
11968 if (ShAmt1.getOpcode() == ISD::SUB) {
11969 SDValue Sum = ShAmt1.getOperand(0);
11970 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11971 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11972 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11973 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11974 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11975 return DAG.getNode(Opc, DL, VT,
11977 DAG.getNode(ISD::TRUNCATE, DL,
11980 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11981 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11983 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11984 return DAG.getNode(Opc, DL, VT,
11985 N0.getOperand(0), N1.getOperand(0),
11986 DAG.getNode(ISD::TRUNCATE, DL,
11993 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11994 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11995 const X86Subtarget *Subtarget) {
11996 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
11997 // the FP state in cases where an emms may be missing.
11998 // A preferable solution to the general problem is to figure out the right
11999 // places to insert EMMS. This qualifies as a quick hack.
12001 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
12002 StoreSDNode *St = cast<StoreSDNode>(N);
12003 EVT VT = St->getValue().getValueType();
12004 if (VT.getSizeInBits() != 64)
12007 const Function *F = DAG.getMachineFunction().getFunction();
12008 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
12009 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
12010 && Subtarget->hasSSE2();
12011 if ((VT.isVector() ||
12012 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
12013 isa<LoadSDNode>(St->getValue()) &&
12014 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
12015 St->getChain().hasOneUse() && !St->isVolatile()) {
12016 SDNode* LdVal = St->getValue().getNode();
12017 LoadSDNode *Ld = 0;
12018 int TokenFactorIndex = -1;
12019 SmallVector<SDValue, 8> Ops;
12020 SDNode* ChainVal = St->getChain().getNode();
12021 // Must be a store of a load. We currently handle two cases: the load
12022 // is a direct child, and it's under an intervening TokenFactor. It is
12023 // possible to dig deeper under nested TokenFactors.
12024 if (ChainVal == LdVal)
12025 Ld = cast<LoadSDNode>(St->getChain());
12026 else if (St->getValue().hasOneUse() &&
12027 ChainVal->getOpcode() == ISD::TokenFactor) {
12028 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
12029 if (ChainVal->getOperand(i).getNode() == LdVal) {
12030 TokenFactorIndex = i;
12031 Ld = cast<LoadSDNode>(St->getValue());
12033 Ops.push_back(ChainVal->getOperand(i));
12037 if (!Ld || !ISD::isNormalLoad(Ld))
12040 // If this is not the MMX case, i.e. we are just turning i64 load/store
12041 // into f64 load/store, avoid the transformation if there are multiple
12042 // uses of the loaded value.
12043 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
12046 DebugLoc LdDL = Ld->getDebugLoc();
12047 DebugLoc StDL = N->getDebugLoc();
12048 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
12049 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
12051 if (Subtarget->is64Bit() || F64IsLegal) {
12052 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
12053 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
12054 Ld->getPointerInfo(), Ld->isVolatile(),
12055 Ld->isNonTemporal(), Ld->getAlignment());
12056 SDValue NewChain = NewLd.getValue(1);
12057 if (TokenFactorIndex != -1) {
12058 Ops.push_back(NewChain);
12059 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12062 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
12063 St->getPointerInfo(),
12064 St->isVolatile(), St->isNonTemporal(),
12065 St->getAlignment());
12068 // Otherwise, lower to two pairs of 32-bit loads / stores.
12069 SDValue LoAddr = Ld->getBasePtr();
12070 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
12071 DAG.getConstant(4, MVT::i32));
12073 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
12074 Ld->getPointerInfo(),
12075 Ld->isVolatile(), Ld->isNonTemporal(),
12076 Ld->getAlignment());
12077 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
12078 Ld->getPointerInfo().getWithOffset(4),
12079 Ld->isVolatile(), Ld->isNonTemporal(),
12080 MinAlign(Ld->getAlignment(), 4));
12082 SDValue NewChain = LoLd.getValue(1);
12083 if (TokenFactorIndex != -1) {
12084 Ops.push_back(LoLd);
12085 Ops.push_back(HiLd);
12086 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12090 LoAddr = St->getBasePtr();
12091 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
12092 DAG.getConstant(4, MVT::i32));
12094 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
12095 St->getPointerInfo(),
12096 St->isVolatile(), St->isNonTemporal(),
12097 St->getAlignment());
12098 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12099 St->getPointerInfo().getWithOffset(4),
12101 St->isNonTemporal(),
12102 MinAlign(St->getAlignment(), 4));
12103 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12108 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12109 /// X86ISD::FXOR nodes.
12110 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12111 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12112 // F[X]OR(0.0, x) -> x
12113 // F[X]OR(x, 0.0) -> x
12114 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12115 if (C->getValueAPF().isPosZero())
12116 return N->getOperand(1);
12117 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12118 if (C->getValueAPF().isPosZero())
12119 return N->getOperand(0);
12123 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12124 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12125 // FAND(0.0, x) -> 0.0
12126 // FAND(x, 0.0) -> 0.0
12127 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12128 if (C->getValueAPF().isPosZero())
12129 return N->getOperand(0);
12130 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12131 if (C->getValueAPF().isPosZero())
12132 return N->getOperand(1);
12136 static SDValue PerformBTCombine(SDNode *N,
12138 TargetLowering::DAGCombinerInfo &DCI) {
12139 // BT ignores high bits in the bit index operand.
12140 SDValue Op1 = N->getOperand(1);
12141 if (Op1.hasOneUse()) {
12142 unsigned BitWidth = Op1.getValueSizeInBits();
12143 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12144 APInt KnownZero, KnownOne;
12145 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12146 !DCI.isBeforeLegalizeOps());
12147 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12148 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12149 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12150 DCI.CommitTargetLoweringOpt(TLO);
12155 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12156 SDValue Op = N->getOperand(0);
12157 if (Op.getOpcode() == ISD::BITCAST)
12158 Op = Op.getOperand(0);
12159 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12160 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12161 VT.getVectorElementType().getSizeInBits() ==
12162 OpVT.getVectorElementType().getSizeInBits()) {
12163 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12168 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12169 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
12170 // (and (i32 x86isd::setcc_carry), 1)
12171 // This eliminates the zext. This transformation is necessary because
12172 // ISD::SETCC is always legalized to i8.
12173 DebugLoc dl = N->getDebugLoc();
12174 SDValue N0 = N->getOperand(0);
12175 EVT VT = N->getValueType(0);
12176 if (N0.getOpcode() == ISD::AND &&
12178 N0.getOperand(0).hasOneUse()) {
12179 SDValue N00 = N0.getOperand(0);
12180 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12182 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12183 if (!C || C->getZExtValue() != 1)
12185 return DAG.getNode(ISD::AND, dl, VT,
12186 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12187 N00.getOperand(0), N00.getOperand(1)),
12188 DAG.getConstant(1, VT));
12194 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12195 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12196 unsigned X86CC = N->getConstantOperandVal(0);
12197 SDValue EFLAG = N->getOperand(1);
12198 DebugLoc DL = N->getDebugLoc();
12200 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12201 // a zext and produces an all-ones bit which is more useful than 0/1 in some
12203 if (X86CC == X86::COND_B)
12204 return DAG.getNode(ISD::AND, DL, MVT::i8,
12205 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12206 DAG.getConstant(X86CC, MVT::i8), EFLAG),
12207 DAG.getConstant(1, MVT::i8));
12212 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
12213 const X86TargetLowering *XTLI) {
12214 SDValue Op0 = N->getOperand(0);
12215 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
12216 // a 32-bit target where SSE doesn't support i64->FP operations.
12217 if (Op0.getOpcode() == ISD::LOAD) {
12218 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
12219 EVT VT = Ld->getValueType(0);
12220 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
12221 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
12222 !XTLI->getSubtarget()->is64Bit() &&
12223 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12224 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
12225 Ld->getChain(), Op0, DAG);
12226 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
12233 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12234 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12235 X86TargetLowering::DAGCombinerInfo &DCI) {
12236 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12237 // the result is either zero or one (depending on the input carry bit).
12238 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12239 if (X86::isZeroNode(N->getOperand(0)) &&
12240 X86::isZeroNode(N->getOperand(1)) &&
12241 // We don't have a good way to replace an EFLAGS use, so only do this when
12243 SDValue(N, 1).use_empty()) {
12244 DebugLoc DL = N->getDebugLoc();
12245 EVT VT = N->getValueType(0);
12246 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12247 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12248 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12249 DAG.getConstant(X86::COND_B,MVT::i8),
12251 DAG.getConstant(1, VT));
12252 return DCI.CombineTo(N, Res1, CarryOut);
12258 // fold (add Y, (sete X, 0)) -> adc 0, Y
12259 // (add Y, (setne X, 0)) -> sbb -1, Y
12260 // (sub (sete X, 0), Y) -> sbb 0, Y
12261 // (sub (setne X, 0), Y) -> adc -1, Y
12262 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12263 DebugLoc DL = N->getDebugLoc();
12265 // Look through ZExts.
12266 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12267 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12270 SDValue SetCC = Ext.getOperand(0);
12271 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12274 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12275 if (CC != X86::COND_E && CC != X86::COND_NE)
12278 SDValue Cmp = SetCC.getOperand(1);
12279 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12280 !X86::isZeroNode(Cmp.getOperand(1)) ||
12281 !Cmp.getOperand(0).getValueType().isInteger())
12284 SDValue CmpOp0 = Cmp.getOperand(0);
12285 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12286 DAG.getConstant(1, CmpOp0.getValueType()));
12288 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12289 if (CC == X86::COND_NE)
12290 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12291 DL, OtherVal.getValueType(), OtherVal,
12292 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12293 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12294 DL, OtherVal.getValueType(), OtherVal,
12295 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12298 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12299 DAGCombinerInfo &DCI) const {
12300 SelectionDAG &DAG = DCI.DAG;
12301 switch (N->getOpcode()) {
12303 case ISD::EXTRACT_VECTOR_ELT:
12304 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12305 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
12306 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
12308 case ISD::SUB: return OptimizeConditonalInDecrement(N, DAG);
12309 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
12310 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
12313 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
12314 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
12315 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
12316 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
12317 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
12319 case X86ISD::FOR: return PerformFORCombine(N, DAG);
12320 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
12321 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
12322 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
12323 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
12324 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
12325 case X86ISD::SHUFPS: // Handle all target specific shuffles
12326 case X86ISD::SHUFPD:
12327 case X86ISD::PALIGN:
12328 case X86ISD::PUNPCKHBW:
12329 case X86ISD::PUNPCKHWD:
12330 case X86ISD::PUNPCKHDQ:
12331 case X86ISD::PUNPCKHQDQ:
12332 case X86ISD::UNPCKHPS:
12333 case X86ISD::UNPCKHPD:
12334 case X86ISD::PUNPCKLBW:
12335 case X86ISD::PUNPCKLWD:
12336 case X86ISD::PUNPCKLDQ:
12337 case X86ISD::PUNPCKLQDQ:
12338 case X86ISD::UNPCKLPS:
12339 case X86ISD::UNPCKLPD:
12340 case X86ISD::VUNPCKLPS:
12341 case X86ISD::VUNPCKLPD:
12342 case X86ISD::VUNPCKLPSY:
12343 case X86ISD::VUNPCKLPDY:
12344 case X86ISD::MOVHLPS:
12345 case X86ISD::MOVLHPS:
12346 case X86ISD::PSHUFD:
12347 case X86ISD::PSHUFHW:
12348 case X86ISD::PSHUFLW:
12349 case X86ISD::MOVSS:
12350 case X86ISD::MOVSD:
12351 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12357 /// isTypeDesirableForOp - Return true if the target has native support for
12358 /// the specified value type and it is 'desirable' to use the type for the
12359 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12360 /// instruction encodings are longer and some i16 instructions are slow.
12361 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12362 if (!isTypeLegal(VT))
12364 if (VT != MVT::i16)
12371 case ISD::SIGN_EXTEND:
12372 case ISD::ZERO_EXTEND:
12373 case ISD::ANY_EXTEND:
12386 /// IsDesirableToPromoteOp - This method query the target whether it is
12387 /// beneficial for dag combiner to promote the specified node. If true, it
12388 /// should return the desired promotion type by reference.
12389 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12390 EVT VT = Op.getValueType();
12391 if (VT != MVT::i16)
12394 bool Promote = false;
12395 bool Commute = false;
12396 switch (Op.getOpcode()) {
12399 LoadSDNode *LD = cast<LoadSDNode>(Op);
12400 // If the non-extending load has a single use and it's not live out, then it
12401 // might be folded.
12402 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12403 Op.hasOneUse()*/) {
12404 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12405 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12406 // The only case where we'd want to promote LOAD (rather then it being
12407 // promoted as an operand is when it's only use is liveout.
12408 if (UI->getOpcode() != ISD::CopyToReg)
12415 case ISD::SIGN_EXTEND:
12416 case ISD::ZERO_EXTEND:
12417 case ISD::ANY_EXTEND:
12422 SDValue N0 = Op.getOperand(0);
12423 // Look out for (store (shl (load), x)).
12424 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12437 SDValue N0 = Op.getOperand(0);
12438 SDValue N1 = Op.getOperand(1);
12439 if (!Commute && MayFoldLoad(N1))
12441 // Avoid disabling potential load folding opportunities.
12442 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12444 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12454 //===----------------------------------------------------------------------===//
12455 // X86 Inline Assembly Support
12456 //===----------------------------------------------------------------------===//
12458 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12459 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12461 std::string AsmStr = IA->getAsmString();
12463 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12464 SmallVector<StringRef, 4> AsmPieces;
12465 SplitString(AsmStr, AsmPieces, ";\n");
12467 switch (AsmPieces.size()) {
12468 default: return false;
12470 AsmStr = AsmPieces[0];
12472 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
12474 // FIXME: this should verify that we are targeting a 486 or better. If not,
12475 // we will turn this bswap into something that will be lowered to logical ops
12476 // instead of emitting the bswap asm. For now, we don't support 486 or lower
12477 // so don't worry about this.
12479 if (AsmPieces.size() == 2 &&
12480 (AsmPieces[0] == "bswap" ||
12481 AsmPieces[0] == "bswapq" ||
12482 AsmPieces[0] == "bswapl") &&
12483 (AsmPieces[1] == "$0" ||
12484 AsmPieces[1] == "${0:q}")) {
12485 // No need to check constraints, nothing other than the equivalent of
12486 // "=r,0" would be valid here.
12487 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12488 if (!Ty || Ty->getBitWidth() % 16 != 0)
12490 return IntrinsicLowering::LowerToByteSwap(CI);
12492 // rorw $$8, ${0:w} --> llvm.bswap.i16
12493 if (CI->getType()->isIntegerTy(16) &&
12494 AsmPieces.size() == 3 &&
12495 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12496 AsmPieces[1] == "$$8," &&
12497 AsmPieces[2] == "${0:w}" &&
12498 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12500 const std::string &ConstraintsStr = IA->getConstraintString();
12501 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12502 std::sort(AsmPieces.begin(), AsmPieces.end());
12503 if (AsmPieces.size() == 4 &&
12504 AsmPieces[0] == "~{cc}" &&
12505 AsmPieces[1] == "~{dirflag}" &&
12506 AsmPieces[2] == "~{flags}" &&
12507 AsmPieces[3] == "~{fpsr}") {
12508 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12509 if (!Ty || Ty->getBitWidth() % 16 != 0)
12511 return IntrinsicLowering::LowerToByteSwap(CI);
12516 if (CI->getType()->isIntegerTy(32) &&
12517 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12518 SmallVector<StringRef, 4> Words;
12519 SplitString(AsmPieces[0], Words, " \t,");
12520 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12521 Words[2] == "${0:w}") {
12523 SplitString(AsmPieces[1], Words, " \t,");
12524 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12525 Words[2] == "$0") {
12527 SplitString(AsmPieces[2], Words, " \t,");
12528 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12529 Words[2] == "${0:w}") {
12531 const std::string &ConstraintsStr = IA->getConstraintString();
12532 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12533 std::sort(AsmPieces.begin(), AsmPieces.end());
12534 if (AsmPieces.size() == 4 &&
12535 AsmPieces[0] == "~{cc}" &&
12536 AsmPieces[1] == "~{dirflag}" &&
12537 AsmPieces[2] == "~{flags}" &&
12538 AsmPieces[3] == "~{fpsr}") {
12539 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12540 if (!Ty || Ty->getBitWidth() % 16 != 0)
12542 return IntrinsicLowering::LowerToByteSwap(CI);
12549 if (CI->getType()->isIntegerTy(64)) {
12550 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12551 if (Constraints.size() >= 2 &&
12552 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12553 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12554 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
12555 SmallVector<StringRef, 4> Words;
12556 SplitString(AsmPieces[0], Words, " \t");
12557 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12559 SplitString(AsmPieces[1], Words, " \t");
12560 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12562 SplitString(AsmPieces[2], Words, " \t,");
12563 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12564 Words[2] == "%edx") {
12565 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12566 if (!Ty || Ty->getBitWidth() % 16 != 0)
12568 return IntrinsicLowering::LowerToByteSwap(CI);
12581 /// getConstraintType - Given a constraint letter, return the type of
12582 /// constraint it is for this target.
12583 X86TargetLowering::ConstraintType
12584 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12585 if (Constraint.size() == 1) {
12586 switch (Constraint[0]) {
12597 return C_RegisterClass;
12621 return TargetLowering::getConstraintType(Constraint);
12624 /// Examine constraint type and operand type and determine a weight value.
12625 /// This object must already have been set up with the operand type
12626 /// and the current alternative constraint selected.
12627 TargetLowering::ConstraintWeight
12628 X86TargetLowering::getSingleConstraintMatchWeight(
12629 AsmOperandInfo &info, const char *constraint) const {
12630 ConstraintWeight weight = CW_Invalid;
12631 Value *CallOperandVal = info.CallOperandVal;
12632 // If we don't have a value, we can't do a match,
12633 // but allow it at the lowest weight.
12634 if (CallOperandVal == NULL)
12636 const Type *type = CallOperandVal->getType();
12637 // Look at the constraint type.
12638 switch (*constraint) {
12640 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12651 if (CallOperandVal->getType()->isIntegerTy())
12652 weight = CW_SpecificReg;
12657 if (type->isFloatingPointTy())
12658 weight = CW_SpecificReg;
12661 if (type->isX86_MMXTy() && Subtarget->hasMMX())
12662 weight = CW_SpecificReg;
12666 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12667 weight = CW_Register;
12670 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12671 if (C->getZExtValue() <= 31)
12672 weight = CW_Constant;
12676 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12677 if (C->getZExtValue() <= 63)
12678 weight = CW_Constant;
12682 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12683 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12684 weight = CW_Constant;
12688 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12689 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12690 weight = CW_Constant;
12694 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12695 if (C->getZExtValue() <= 3)
12696 weight = CW_Constant;
12700 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12701 if (C->getZExtValue() <= 0xff)
12702 weight = CW_Constant;
12707 if (dyn_cast<ConstantFP>(CallOperandVal)) {
12708 weight = CW_Constant;
12712 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12713 if ((C->getSExtValue() >= -0x80000000LL) &&
12714 (C->getSExtValue() <= 0x7fffffffLL))
12715 weight = CW_Constant;
12719 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12720 if (C->getZExtValue() <= 0xffffffff)
12721 weight = CW_Constant;
12728 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12729 /// with another that has more specific requirements based on the type of the
12730 /// corresponding operand.
12731 const char *X86TargetLowering::
12732 LowerXConstraint(EVT ConstraintVT) const {
12733 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12734 // 'f' like normal targets.
12735 if (ConstraintVT.isFloatingPoint()) {
12736 if (Subtarget->hasXMMInt())
12738 if (Subtarget->hasXMM())
12742 return TargetLowering::LowerXConstraint(ConstraintVT);
12745 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12746 /// vector. If it is invalid, don't add anything to Ops.
12747 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12748 std::string &Constraint,
12749 std::vector<SDValue>&Ops,
12750 SelectionDAG &DAG) const {
12751 SDValue Result(0, 0);
12753 // Only support length 1 constraints for now.
12754 if (Constraint.length() > 1) return;
12756 char ConstraintLetter = Constraint[0];
12757 switch (ConstraintLetter) {
12760 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12761 if (C->getZExtValue() <= 31) {
12762 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12768 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12769 if (C->getZExtValue() <= 63) {
12770 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12776 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12777 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12778 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12784 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12785 if (C->getZExtValue() <= 255) {
12786 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12792 // 32-bit signed value
12793 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12794 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12795 C->getSExtValue())) {
12796 // Widen to 64 bits here to get it sign extended.
12797 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12800 // FIXME gcc accepts some relocatable values here too, but only in certain
12801 // memory models; it's complicated.
12806 // 32-bit unsigned value
12807 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12808 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12809 C->getZExtValue())) {
12810 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12814 // FIXME gcc accepts some relocatable values here too, but only in certain
12815 // memory models; it's complicated.
12819 // Literal immediates are always ok.
12820 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12821 // Widen to 64 bits here to get it sign extended.
12822 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12826 // In any sort of PIC mode addresses need to be computed at runtime by
12827 // adding in a register or some sort of table lookup. These can't
12828 // be used as immediates.
12829 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12832 // If we are in non-pic codegen mode, we allow the address of a global (with
12833 // an optional displacement) to be used with 'i'.
12834 GlobalAddressSDNode *GA = 0;
12835 int64_t Offset = 0;
12837 // Match either (GA), (GA+C), (GA+C1+C2), etc.
12839 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12840 Offset += GA->getOffset();
12842 } else if (Op.getOpcode() == ISD::ADD) {
12843 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12844 Offset += C->getZExtValue();
12845 Op = Op.getOperand(0);
12848 } else if (Op.getOpcode() == ISD::SUB) {
12849 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12850 Offset += -C->getZExtValue();
12851 Op = Op.getOperand(0);
12856 // Otherwise, this isn't something we can handle, reject it.
12860 const GlobalValue *GV = GA->getGlobal();
12861 // If we require an extra load to get this address, as in PIC mode, we
12862 // can't accept it.
12863 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12864 getTargetMachine())))
12867 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12868 GA->getValueType(0), Offset);
12873 if (Result.getNode()) {
12874 Ops.push_back(Result);
12877 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12880 std::pair<unsigned, const TargetRegisterClass*>
12881 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12883 // First, see if this is a constraint that directly corresponds to an LLVM
12885 if (Constraint.size() == 1) {
12886 // GCC Constraint Letters
12887 switch (Constraint[0]) {
12889 // TODO: Slight differences here in allocation order and leaving
12890 // RIP in the class. Do they matter any more here than they do
12891 // in the normal allocation?
12892 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12893 if (Subtarget->is64Bit()) {
12894 if (VT == MVT::i32 || VT == MVT::f32)
12895 return std::make_pair(0U, X86::GR32RegisterClass);
12896 else if (VT == MVT::i16)
12897 return std::make_pair(0U, X86::GR16RegisterClass);
12898 else if (VT == MVT::i8)
12899 return std::make_pair(0U, X86::GR8RegisterClass);
12900 else if (VT == MVT::i64 || VT == MVT::f64)
12901 return std::make_pair(0U, X86::GR64RegisterClass);
12904 // 32-bit fallthrough
12905 case 'Q': // Q_REGS
12906 if (VT == MVT::i32 || VT == MVT::f32)
12907 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
12908 else if (VT == MVT::i16)
12909 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
12910 else if (VT == MVT::i8)
12911 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
12912 else if (VT == MVT::i64)
12913 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
12915 case 'r': // GENERAL_REGS
12916 case 'l': // INDEX_REGS
12918 return std::make_pair(0U, X86::GR8RegisterClass);
12919 if (VT == MVT::i16)
12920 return std::make_pair(0U, X86::GR16RegisterClass);
12921 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
12922 return std::make_pair(0U, X86::GR32RegisterClass);
12923 return std::make_pair(0U, X86::GR64RegisterClass);
12924 case 'R': // LEGACY_REGS
12926 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12927 if (VT == MVT::i16)
12928 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12929 if (VT == MVT::i32 || !Subtarget->is64Bit())
12930 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12931 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12932 case 'f': // FP Stack registers.
12933 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12934 // value to the correct fpstack register class.
12935 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12936 return std::make_pair(0U, X86::RFP32RegisterClass);
12937 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12938 return std::make_pair(0U, X86::RFP64RegisterClass);
12939 return std::make_pair(0U, X86::RFP80RegisterClass);
12940 case 'y': // MMX_REGS if MMX allowed.
12941 if (!Subtarget->hasMMX()) break;
12942 return std::make_pair(0U, X86::VR64RegisterClass);
12943 case 'Y': // SSE_REGS if SSE2 allowed
12944 if (!Subtarget->hasXMMInt()) break;
12946 case 'x': // SSE_REGS if SSE1 allowed
12947 if (!Subtarget->hasXMM()) break;
12949 switch (VT.getSimpleVT().SimpleTy) {
12951 // Scalar SSE types.
12954 return std::make_pair(0U, X86::FR32RegisterClass);
12957 return std::make_pair(0U, X86::FR64RegisterClass);
12965 return std::make_pair(0U, X86::VR128RegisterClass);
12971 // Use the default implementation in TargetLowering to convert the register
12972 // constraint into a member of a register class.
12973 std::pair<unsigned, const TargetRegisterClass*> Res;
12974 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12976 // Not found as a standard register?
12977 if (Res.second == 0) {
12978 // Map st(0) -> st(7) -> ST0
12979 if (Constraint.size() == 7 && Constraint[0] == '{' &&
12980 tolower(Constraint[1]) == 's' &&
12981 tolower(Constraint[2]) == 't' &&
12982 Constraint[3] == '(' &&
12983 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12984 Constraint[5] == ')' &&
12985 Constraint[6] == '}') {
12987 Res.first = X86::ST0+Constraint[4]-'0';
12988 Res.second = X86::RFP80RegisterClass;
12992 // GCC allows "st(0)" to be called just plain "st".
12993 if (StringRef("{st}").equals_lower(Constraint)) {
12994 Res.first = X86::ST0;
12995 Res.second = X86::RFP80RegisterClass;
13000 if (StringRef("{flags}").equals_lower(Constraint)) {
13001 Res.first = X86::EFLAGS;
13002 Res.second = X86::CCRRegisterClass;
13006 // 'A' means EAX + EDX.
13007 if (Constraint == "A") {
13008 Res.first = X86::EAX;
13009 Res.second = X86::GR32_ADRegisterClass;
13015 // Otherwise, check to see if this is a register class of the wrong value
13016 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
13017 // turn into {ax},{dx}.
13018 if (Res.second->hasType(VT))
13019 return Res; // Correct type already, nothing to do.
13021 // All of the single-register GCC register classes map their values onto
13022 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
13023 // really want an 8-bit or 32-bit register, map to the appropriate register
13024 // class and return the appropriate register.
13025 if (Res.second == X86::GR16RegisterClass) {
13026 if (VT == MVT::i8) {
13027 unsigned DestReg = 0;
13028 switch (Res.first) {
13030 case X86::AX: DestReg = X86::AL; break;
13031 case X86::DX: DestReg = X86::DL; break;
13032 case X86::CX: DestReg = X86::CL; break;
13033 case X86::BX: DestReg = X86::BL; break;
13036 Res.first = DestReg;
13037 Res.second = X86::GR8RegisterClass;
13039 } else if (VT == MVT::i32) {
13040 unsigned DestReg = 0;
13041 switch (Res.first) {
13043 case X86::AX: DestReg = X86::EAX; break;
13044 case X86::DX: DestReg = X86::EDX; break;
13045 case X86::CX: DestReg = X86::ECX; break;
13046 case X86::BX: DestReg = X86::EBX; break;
13047 case X86::SI: DestReg = X86::ESI; break;
13048 case X86::DI: DestReg = X86::EDI; break;
13049 case X86::BP: DestReg = X86::EBP; break;
13050 case X86::SP: DestReg = X86::ESP; break;
13053 Res.first = DestReg;
13054 Res.second = X86::GR32RegisterClass;
13056 } else if (VT == MVT::i64) {
13057 unsigned DestReg = 0;
13058 switch (Res.first) {
13060 case X86::AX: DestReg = X86::RAX; break;
13061 case X86::DX: DestReg = X86::RDX; break;
13062 case X86::CX: DestReg = X86::RCX; break;
13063 case X86::BX: DestReg = X86::RBX; break;
13064 case X86::SI: DestReg = X86::RSI; break;
13065 case X86::DI: DestReg = X86::RDI; break;
13066 case X86::BP: DestReg = X86::RBP; break;
13067 case X86::SP: DestReg = X86::RSP; break;
13070 Res.first = DestReg;
13071 Res.second = X86::GR64RegisterClass;
13074 } else if (Res.second == X86::FR32RegisterClass ||
13075 Res.second == X86::FR64RegisterClass ||
13076 Res.second == X86::VR128RegisterClass) {
13077 // Handle references to XMM physical registers that got mapped into the
13078 // wrong class. This can happen with constraints like {xmm0} where the
13079 // target independent register mapper will just pick the first match it can
13080 // find, ignoring the required type.
13081 if (VT == MVT::f32)
13082 Res.second = X86::FR32RegisterClass;
13083 else if (VT == MVT::f64)
13084 Res.second = X86::FR64RegisterClass;
13085 else if (X86::VR128RegisterClass->hasType(VT))
13086 Res.second = X86::VR128RegisterClass;