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 if (Subtarget->is64Bit())
1101 setTargetDAGCombine(ISD::MUL);
1103 computeRegisterProperties();
1105 // On Darwin, -Os means optimize for size without hurting performance,
1106 // do not reduce the limit.
1107 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1108 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1109 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1110 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1111 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1112 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1113 setPrefLoopAlignment(16);
1114 benefitFromCodePlacementOpt = true;
1116 setPrefFunctionAlignment(4);
1120 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1125 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1126 /// the desired ByVal argument alignment.
1127 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1130 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1131 if (VTy->getBitWidth() == 128)
1133 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1134 unsigned EltAlign = 0;
1135 getMaxByValAlign(ATy->getElementType(), EltAlign);
1136 if (EltAlign > MaxAlign)
1137 MaxAlign = EltAlign;
1138 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1139 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1140 unsigned EltAlign = 0;
1141 getMaxByValAlign(STy->getElementType(i), EltAlign);
1142 if (EltAlign > MaxAlign)
1143 MaxAlign = EltAlign;
1151 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1152 /// function arguments in the caller parameter area. For X86, aggregates
1153 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1154 /// are at 4-byte boundaries.
1155 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1156 if (Subtarget->is64Bit()) {
1157 // Max of 8 and alignment of type.
1158 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1165 if (Subtarget->hasXMM())
1166 getMaxByValAlign(Ty, Align);
1170 /// getOptimalMemOpType - Returns the target specific optimal type for load
1171 /// and store operations as a result of memset, memcpy, and memmove
1172 /// lowering. If DstAlign is zero that means it's safe to destination
1173 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1174 /// means there isn't a need to check it against alignment requirement,
1175 /// probably because the source does not need to be loaded. If
1176 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1177 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1178 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1179 /// constant so it does not need to be loaded.
1180 /// It returns EVT::Other if the type should be determined using generic
1181 /// target-independent logic.
1183 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1184 unsigned DstAlign, unsigned SrcAlign,
1185 bool NonScalarIntSafe,
1187 MachineFunction &MF) const {
1188 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1189 // linux. This is because the stack realignment code can't handle certain
1190 // cases like PR2962. This should be removed when PR2962 is fixed.
1191 const Function *F = MF.getFunction();
1192 if (NonScalarIntSafe &&
1193 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1195 (Subtarget->isUnalignedMemAccessFast() ||
1196 ((DstAlign == 0 || DstAlign >= 16) &&
1197 (SrcAlign == 0 || SrcAlign >= 16))) &&
1198 Subtarget->getStackAlignment() >= 16) {
1199 if (Subtarget->hasSSE2())
1201 if (Subtarget->hasSSE1())
1203 } else if (!MemcpyStrSrc && Size >= 8 &&
1204 !Subtarget->is64Bit() &&
1205 Subtarget->getStackAlignment() >= 8 &&
1206 Subtarget->hasXMMInt()) {
1207 // Do not use f64 to lower memcpy if source is string constant. It's
1208 // better to use i32 to avoid the loads.
1212 if (Subtarget->is64Bit() && Size >= 8)
1217 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1218 /// current function. The returned value is a member of the
1219 /// MachineJumpTableInfo::JTEntryKind enum.
1220 unsigned X86TargetLowering::getJumpTableEncoding() const {
1221 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1223 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1224 Subtarget->isPICStyleGOT())
1225 return MachineJumpTableInfo::EK_Custom32;
1227 // Otherwise, use the normal jump table encoding heuristics.
1228 return TargetLowering::getJumpTableEncoding();
1232 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1233 const MachineBasicBlock *MBB,
1234 unsigned uid,MCContext &Ctx) const{
1235 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1236 Subtarget->isPICStyleGOT());
1237 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1239 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1240 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1243 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1245 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1246 SelectionDAG &DAG) const {
1247 if (!Subtarget->is64Bit())
1248 // This doesn't have DebugLoc associated with it, but is not really the
1249 // same as a Register.
1250 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1254 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1255 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1257 const MCExpr *X86TargetLowering::
1258 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1259 MCContext &Ctx) const {
1260 // X86-64 uses RIP relative addressing based on the jump table label.
1261 if (Subtarget->isPICStyleRIPRel())
1262 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1264 // Otherwise, the reference is relative to the PIC base.
1265 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1268 // FIXME: Why this routine is here? Move to RegInfo!
1269 std::pair<const TargetRegisterClass*, uint8_t>
1270 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1271 const TargetRegisterClass *RRC = 0;
1273 switch (VT.getSimpleVT().SimpleTy) {
1275 return TargetLowering::findRepresentativeClass(VT);
1276 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1277 RRC = (Subtarget->is64Bit()
1278 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1281 RRC = X86::VR64RegisterClass;
1283 case MVT::f32: case MVT::f64:
1284 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1285 case MVT::v4f32: case MVT::v2f64:
1286 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1288 RRC = X86::VR128RegisterClass;
1291 return std::make_pair(RRC, Cost);
1294 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1295 unsigned &Offset) const {
1296 if (!Subtarget->isTargetLinux())
1299 if (Subtarget->is64Bit()) {
1300 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1302 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1315 //===----------------------------------------------------------------------===//
1316 // Return Value Calling Convention Implementation
1317 //===----------------------------------------------------------------------===//
1319 #include "X86GenCallingConv.inc"
1322 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1323 const SmallVectorImpl<ISD::OutputArg> &Outs,
1324 LLVMContext &Context) const {
1325 SmallVector<CCValAssign, 16> RVLocs;
1326 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1328 return CCInfo.CheckReturn(Outs, RetCC_X86);
1332 X86TargetLowering::LowerReturn(SDValue Chain,
1333 CallingConv::ID CallConv, bool isVarArg,
1334 const SmallVectorImpl<ISD::OutputArg> &Outs,
1335 const SmallVectorImpl<SDValue> &OutVals,
1336 DebugLoc dl, SelectionDAG &DAG) const {
1337 MachineFunction &MF = DAG.getMachineFunction();
1338 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1340 SmallVector<CCValAssign, 16> RVLocs;
1341 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1342 RVLocs, *DAG.getContext());
1343 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1345 // Add the regs to the liveout set for the function.
1346 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1347 for (unsigned i = 0; i != RVLocs.size(); ++i)
1348 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1349 MRI.addLiveOut(RVLocs[i].getLocReg());
1353 SmallVector<SDValue, 6> RetOps;
1354 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1355 // Operand #1 = Bytes To Pop
1356 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1359 // Copy the result values into the output registers.
1360 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1361 CCValAssign &VA = RVLocs[i];
1362 assert(VA.isRegLoc() && "Can only return in registers!");
1363 SDValue ValToCopy = OutVals[i];
1364 EVT ValVT = ValToCopy.getValueType();
1366 // If this is x86-64, and we disabled SSE, we can't return FP values,
1367 // or SSE or MMX vectors.
1368 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1369 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1370 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1371 report_fatal_error("SSE register return with SSE disabled");
1373 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1374 // llvm-gcc has never done it right and no one has noticed, so this
1375 // should be OK for now.
1376 if (ValVT == MVT::f64 &&
1377 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1378 report_fatal_error("SSE2 register return with SSE2 disabled");
1380 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1381 // the RET instruction and handled by the FP Stackifier.
1382 if (VA.getLocReg() == X86::ST0 ||
1383 VA.getLocReg() == X86::ST1) {
1384 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1385 // change the value to the FP stack register class.
1386 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1387 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1388 RetOps.push_back(ValToCopy);
1389 // Don't emit a copytoreg.
1393 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1394 // which is returned in RAX / RDX.
1395 if (Subtarget->is64Bit()) {
1396 if (ValVT == MVT::x86mmx) {
1397 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1398 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1399 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1401 // If we don't have SSE2 available, convert to v4f32 so the generated
1402 // register is legal.
1403 if (!Subtarget->hasSSE2())
1404 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1409 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1410 Flag = Chain.getValue(1);
1413 // The x86-64 ABI for returning structs by value requires that we copy
1414 // the sret argument into %rax for the return. We saved the argument into
1415 // a virtual register in the entry block, so now we copy the value out
1417 if (Subtarget->is64Bit() &&
1418 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1419 MachineFunction &MF = DAG.getMachineFunction();
1420 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1421 unsigned Reg = FuncInfo->getSRetReturnReg();
1423 "SRetReturnReg should have been set in LowerFormalArguments().");
1424 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1426 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1427 Flag = Chain.getValue(1);
1429 // RAX now acts like a return value.
1430 MRI.addLiveOut(X86::RAX);
1433 RetOps[0] = Chain; // Update chain.
1435 // Add the flag if we have it.
1437 RetOps.push_back(Flag);
1439 return DAG.getNode(X86ISD::RET_FLAG, dl,
1440 MVT::Other, &RetOps[0], RetOps.size());
1443 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1444 if (N->getNumValues() != 1)
1446 if (!N->hasNUsesOfValue(1, 0))
1449 SDNode *Copy = *N->use_begin();
1450 if (Copy->getOpcode() != ISD::CopyToReg &&
1451 Copy->getOpcode() != ISD::FP_EXTEND)
1454 bool HasRet = false;
1455 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1457 if (UI->getOpcode() != X86ISD::RET_FLAG)
1466 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1467 ISD::NodeType ExtendKind) const {
1469 // TODO: Is this also valid on 32-bit?
1470 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1471 ReturnMVT = MVT::i8;
1473 ReturnMVT = MVT::i32;
1475 EVT MinVT = getRegisterType(Context, ReturnMVT);
1476 return VT.bitsLT(MinVT) ? MinVT : VT;
1479 /// LowerCallResult - Lower the result values of a call into the
1480 /// appropriate copies out of appropriate physical registers.
1483 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1484 CallingConv::ID CallConv, bool isVarArg,
1485 const SmallVectorImpl<ISD::InputArg> &Ins,
1486 DebugLoc dl, SelectionDAG &DAG,
1487 SmallVectorImpl<SDValue> &InVals) const {
1489 // Assign locations to each value returned by this call.
1490 SmallVector<CCValAssign, 16> RVLocs;
1491 bool Is64Bit = Subtarget->is64Bit();
1492 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1493 RVLocs, *DAG.getContext());
1494 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1496 // Copy all of the result registers out of their specified physreg.
1497 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1498 CCValAssign &VA = RVLocs[i];
1499 EVT CopyVT = VA.getValVT();
1501 // If this is x86-64, and we disabled SSE, we can't return FP values
1502 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1503 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1504 report_fatal_error("SSE register return with SSE disabled");
1509 // If this is a call to a function that returns an fp value on the floating
1510 // point stack, we must guarantee the the value is popped from the stack, so
1511 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1512 // if the return value is not used. We use the FpGET_ST0 instructions
1514 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1515 // If we prefer to use the value in xmm registers, copy it out as f80 and
1516 // use a truncate to move it from fp stack reg to xmm reg.
1517 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1518 bool isST0 = VA.getLocReg() == X86::ST0;
1520 if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1521 if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1522 if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1523 SDValue Ops[] = { Chain, InFlag };
1524 Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1526 Val = Chain.getValue(0);
1528 // Round the f80 to the right size, which also moves it to the appropriate
1530 if (CopyVT != VA.getValVT())
1531 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1532 // This truncation won't change the value.
1533 DAG.getIntPtrConstant(1));
1535 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1536 CopyVT, InFlag).getValue(1);
1537 Val = Chain.getValue(0);
1539 InFlag = Chain.getValue(2);
1540 InVals.push_back(Val);
1547 //===----------------------------------------------------------------------===//
1548 // C & StdCall & Fast Calling Convention implementation
1549 //===----------------------------------------------------------------------===//
1550 // StdCall calling convention seems to be standard for many Windows' API
1551 // routines and around. It differs from C calling convention just a little:
1552 // callee should clean up the stack, not caller. Symbols should be also
1553 // decorated in some fancy way :) It doesn't support any vector arguments.
1554 // For info on fast calling convention see Fast Calling Convention (tail call)
1555 // implementation LowerX86_32FastCCCallTo.
1557 /// CallIsStructReturn - Determines whether a call uses struct return
1559 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1563 return Outs[0].Flags.isSRet();
1566 /// ArgsAreStructReturn - Determines whether a function uses struct
1567 /// return semantics.
1569 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1573 return Ins[0].Flags.isSRet();
1576 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1577 /// by "Src" to address "Dst" with size and alignment information specified by
1578 /// the specific parameter attribute. The copy will be passed as a byval
1579 /// function parameter.
1581 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1582 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1584 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1586 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1587 /*isVolatile*/false, /*AlwaysInline=*/true,
1588 MachinePointerInfo(), MachinePointerInfo());
1591 /// IsTailCallConvention - Return true if the calling convention is one that
1592 /// supports tail call optimization.
1593 static bool IsTailCallConvention(CallingConv::ID CC) {
1594 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1597 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1598 if (!CI->isTailCall())
1602 CallingConv::ID CalleeCC = CS.getCallingConv();
1603 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1609 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1610 /// a tailcall target by changing its ABI.
1611 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1612 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1616 X86TargetLowering::LowerMemArgument(SDValue Chain,
1617 CallingConv::ID CallConv,
1618 const SmallVectorImpl<ISD::InputArg> &Ins,
1619 DebugLoc dl, SelectionDAG &DAG,
1620 const CCValAssign &VA,
1621 MachineFrameInfo *MFI,
1623 // Create the nodes corresponding to a load from this parameter slot.
1624 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1625 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1626 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1629 // If value is passed by pointer we have address passed instead of the value
1631 if (VA.getLocInfo() == CCValAssign::Indirect)
1632 ValVT = VA.getLocVT();
1634 ValVT = VA.getValVT();
1636 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1637 // changed with more analysis.
1638 // In case of tail call optimization mark all arguments mutable. Since they
1639 // could be overwritten by lowering of arguments in case of a tail call.
1640 if (Flags.isByVal()) {
1641 unsigned Bytes = Flags.getByValSize();
1642 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1643 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1644 return DAG.getFrameIndex(FI, getPointerTy());
1646 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1647 VA.getLocMemOffset(), isImmutable);
1648 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1649 return DAG.getLoad(ValVT, dl, Chain, FIN,
1650 MachinePointerInfo::getFixedStack(FI),
1656 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1657 CallingConv::ID CallConv,
1659 const SmallVectorImpl<ISD::InputArg> &Ins,
1662 SmallVectorImpl<SDValue> &InVals)
1664 MachineFunction &MF = DAG.getMachineFunction();
1665 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1667 const Function* Fn = MF.getFunction();
1668 if (Fn->hasExternalLinkage() &&
1669 Subtarget->isTargetCygMing() &&
1670 Fn->getName() == "main")
1671 FuncInfo->setForceFramePointer(true);
1673 MachineFrameInfo *MFI = MF.getFrameInfo();
1674 bool Is64Bit = Subtarget->is64Bit();
1675 bool IsWin64 = Subtarget->isTargetWin64();
1677 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1678 "Var args not supported with calling convention fastcc or ghc");
1680 // Assign locations to all of the incoming arguments.
1681 SmallVector<CCValAssign, 16> ArgLocs;
1682 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1683 ArgLocs, *DAG.getContext());
1685 // Allocate shadow area for Win64
1687 CCInfo.AllocateStack(32, 8);
1690 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1692 unsigned LastVal = ~0U;
1694 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1695 CCValAssign &VA = ArgLocs[i];
1696 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1698 assert(VA.getValNo() != LastVal &&
1699 "Don't support value assigned to multiple locs yet");
1700 LastVal = VA.getValNo();
1702 if (VA.isRegLoc()) {
1703 EVT RegVT = VA.getLocVT();
1704 TargetRegisterClass *RC = NULL;
1705 if (RegVT == MVT::i32)
1706 RC = X86::GR32RegisterClass;
1707 else if (Is64Bit && RegVT == MVT::i64)
1708 RC = X86::GR64RegisterClass;
1709 else if (RegVT == MVT::f32)
1710 RC = X86::FR32RegisterClass;
1711 else if (RegVT == MVT::f64)
1712 RC = X86::FR64RegisterClass;
1713 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1714 RC = X86::VR256RegisterClass;
1715 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1716 RC = X86::VR128RegisterClass;
1717 else if (RegVT == MVT::x86mmx)
1718 RC = X86::VR64RegisterClass;
1720 llvm_unreachable("Unknown argument type!");
1722 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1723 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1725 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1726 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1728 if (VA.getLocInfo() == CCValAssign::SExt)
1729 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1730 DAG.getValueType(VA.getValVT()));
1731 else if (VA.getLocInfo() == CCValAssign::ZExt)
1732 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1733 DAG.getValueType(VA.getValVT()));
1734 else if (VA.getLocInfo() == CCValAssign::BCvt)
1735 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1737 if (VA.isExtInLoc()) {
1738 // Handle MMX values passed in XMM regs.
1739 if (RegVT.isVector()) {
1740 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1743 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1746 assert(VA.isMemLoc());
1747 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1750 // If value is passed via pointer - do a load.
1751 if (VA.getLocInfo() == CCValAssign::Indirect)
1752 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1753 MachinePointerInfo(), false, false, 0);
1755 InVals.push_back(ArgValue);
1758 // The x86-64 ABI for returning structs by value requires that we copy
1759 // the sret argument into %rax for the return. Save the argument into
1760 // a virtual register so that we can access it from the return points.
1761 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1762 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1763 unsigned Reg = FuncInfo->getSRetReturnReg();
1765 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1766 FuncInfo->setSRetReturnReg(Reg);
1768 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1769 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1772 unsigned StackSize = CCInfo.getNextStackOffset();
1773 // Align stack specially for tail calls.
1774 if (FuncIsMadeTailCallSafe(CallConv))
1775 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1777 // If the function takes variable number of arguments, make a frame index for
1778 // the start of the first vararg value... for expansion of llvm.va_start.
1780 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1781 CallConv != CallingConv::X86_ThisCall)) {
1782 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1785 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1787 // FIXME: We should really autogenerate these arrays
1788 static const unsigned GPR64ArgRegsWin64[] = {
1789 X86::RCX, X86::RDX, X86::R8, X86::R9
1791 static const unsigned GPR64ArgRegs64Bit[] = {
1792 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1794 static const unsigned XMMArgRegs64Bit[] = {
1795 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1796 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1798 const unsigned *GPR64ArgRegs;
1799 unsigned NumXMMRegs = 0;
1802 // The XMM registers which might contain var arg parameters are shadowed
1803 // in their paired GPR. So we only need to save the GPR to their home
1805 TotalNumIntRegs = 4;
1806 GPR64ArgRegs = GPR64ArgRegsWin64;
1808 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1809 GPR64ArgRegs = GPR64ArgRegs64Bit;
1811 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1813 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1816 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1817 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1818 "SSE register cannot be used when SSE is disabled!");
1819 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1820 "SSE register cannot be used when SSE is disabled!");
1821 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1822 // Kernel mode asks for SSE to be disabled, so don't push them
1824 TotalNumXMMRegs = 0;
1827 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1828 // Get to the caller-allocated home save location. Add 8 to account
1829 // for the return address.
1830 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1831 FuncInfo->setRegSaveFrameIndex(
1832 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1833 // Fixup to set vararg frame on shadow area (4 x i64).
1835 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1837 // For X86-64, if there are vararg parameters that are passed via
1838 // registers, then we must store them to their spots on the stack so they
1839 // may be loaded by deferencing the result of va_next.
1840 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1841 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1842 FuncInfo->setRegSaveFrameIndex(
1843 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1847 // Store the integer parameter registers.
1848 SmallVector<SDValue, 8> MemOps;
1849 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1851 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1852 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1853 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1854 DAG.getIntPtrConstant(Offset));
1855 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1856 X86::GR64RegisterClass);
1857 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1859 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1860 MachinePointerInfo::getFixedStack(
1861 FuncInfo->getRegSaveFrameIndex(), Offset),
1863 MemOps.push_back(Store);
1867 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1868 // Now store the XMM (fp + vector) parameter registers.
1869 SmallVector<SDValue, 11> SaveXMMOps;
1870 SaveXMMOps.push_back(Chain);
1872 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1873 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1874 SaveXMMOps.push_back(ALVal);
1876 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1877 FuncInfo->getRegSaveFrameIndex()));
1878 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1879 FuncInfo->getVarArgsFPOffset()));
1881 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1882 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1883 X86::VR128RegisterClass);
1884 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1885 SaveXMMOps.push_back(Val);
1887 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1889 &SaveXMMOps[0], SaveXMMOps.size()));
1892 if (!MemOps.empty())
1893 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1894 &MemOps[0], MemOps.size());
1898 // Some CCs need callee pop.
1899 if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1900 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1902 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1903 // If this is an sret function, the return should pop the hidden pointer.
1904 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1905 FuncInfo->setBytesToPopOnReturn(4);
1909 // RegSaveFrameIndex is X86-64 only.
1910 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1911 if (CallConv == CallingConv::X86_FastCall ||
1912 CallConv == CallingConv::X86_ThisCall)
1913 // fastcc functions can't have varargs.
1914 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1921 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1922 SDValue StackPtr, SDValue Arg,
1923 DebugLoc dl, SelectionDAG &DAG,
1924 const CCValAssign &VA,
1925 ISD::ArgFlagsTy Flags) const {
1926 unsigned LocMemOffset = VA.getLocMemOffset();
1927 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1928 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1929 if (Flags.isByVal())
1930 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1932 return DAG.getStore(Chain, dl, Arg, PtrOff,
1933 MachinePointerInfo::getStack(LocMemOffset),
1937 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1938 /// optimization is performed and it is required.
1940 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1941 SDValue &OutRetAddr, SDValue Chain,
1942 bool IsTailCall, bool Is64Bit,
1943 int FPDiff, DebugLoc dl) const {
1944 // Adjust the Return address stack slot.
1945 EVT VT = getPointerTy();
1946 OutRetAddr = getReturnAddressFrameIndex(DAG);
1948 // Load the "old" Return address.
1949 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1951 return SDValue(OutRetAddr.getNode(), 1);
1954 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1955 /// optimization is performed and it is required (FPDiff!=0).
1957 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1958 SDValue Chain, SDValue RetAddrFrIdx,
1959 bool Is64Bit, int FPDiff, DebugLoc dl) {
1960 // Store the return address to the appropriate stack slot.
1961 if (!FPDiff) return Chain;
1962 // Calculate the new stack slot for the return address.
1963 int SlotSize = Is64Bit ? 8 : 4;
1964 int NewReturnAddrFI =
1965 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1966 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1967 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1968 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1969 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1975 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1976 CallingConv::ID CallConv, bool isVarArg,
1978 const SmallVectorImpl<ISD::OutputArg> &Outs,
1979 const SmallVectorImpl<SDValue> &OutVals,
1980 const SmallVectorImpl<ISD::InputArg> &Ins,
1981 DebugLoc dl, SelectionDAG &DAG,
1982 SmallVectorImpl<SDValue> &InVals) const {
1983 MachineFunction &MF = DAG.getMachineFunction();
1984 bool Is64Bit = Subtarget->is64Bit();
1985 bool IsWin64 = Subtarget->isTargetWin64();
1986 bool IsStructRet = CallIsStructReturn(Outs);
1987 bool IsSibcall = false;
1990 // Check if it's really possible to do a tail call.
1991 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1992 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1993 Outs, OutVals, Ins, DAG);
1995 // Sibcalls are automatically detected tailcalls which do not require
1997 if (!GuaranteedTailCallOpt && isTailCall)
2004 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2005 "Var args not supported with calling convention fastcc or ghc");
2007 // Analyze operands of the call, assigning locations to each operand.
2008 SmallVector<CCValAssign, 16> ArgLocs;
2009 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
2010 ArgLocs, *DAG.getContext());
2012 // Allocate shadow area for Win64
2014 CCInfo.AllocateStack(32, 8);
2017 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2019 // Get a count of how many bytes are to be pushed on the stack.
2020 unsigned NumBytes = CCInfo.getNextStackOffset();
2022 // This is a sibcall. The memory operands are available in caller's
2023 // own caller's stack.
2025 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2026 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2029 if (isTailCall && !IsSibcall) {
2030 // Lower arguments at fp - stackoffset + fpdiff.
2031 unsigned NumBytesCallerPushed =
2032 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2033 FPDiff = NumBytesCallerPushed - NumBytes;
2035 // Set the delta of movement of the returnaddr stackslot.
2036 // But only set if delta is greater than previous delta.
2037 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2038 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2042 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2044 SDValue RetAddrFrIdx;
2045 // Load return address for tail calls.
2046 if (isTailCall && FPDiff)
2047 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2048 Is64Bit, FPDiff, dl);
2050 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2051 SmallVector<SDValue, 8> MemOpChains;
2054 // Walk the register/memloc assignments, inserting copies/loads. In the case
2055 // of tail call optimization arguments are handle later.
2056 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2057 CCValAssign &VA = ArgLocs[i];
2058 EVT RegVT = VA.getLocVT();
2059 SDValue Arg = OutVals[i];
2060 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2061 bool isByVal = Flags.isByVal();
2063 // Promote the value if needed.
2064 switch (VA.getLocInfo()) {
2065 default: llvm_unreachable("Unknown loc info!");
2066 case CCValAssign::Full: break;
2067 case CCValAssign::SExt:
2068 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2070 case CCValAssign::ZExt:
2071 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2073 case CCValAssign::AExt:
2074 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2075 // Special case: passing MMX values in XMM registers.
2076 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2077 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2078 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2080 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2082 case CCValAssign::BCvt:
2083 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2085 case CCValAssign::Indirect: {
2086 // Store the argument.
2087 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2088 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2089 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2090 MachinePointerInfo::getFixedStack(FI),
2097 if (VA.isRegLoc()) {
2098 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2099 if (isVarArg && IsWin64) {
2100 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2101 // shadow reg if callee is a varargs function.
2102 unsigned ShadowReg = 0;
2103 switch (VA.getLocReg()) {
2104 case X86::XMM0: ShadowReg = X86::RCX; break;
2105 case X86::XMM1: ShadowReg = X86::RDX; break;
2106 case X86::XMM2: ShadowReg = X86::R8; break;
2107 case X86::XMM3: ShadowReg = X86::R9; break;
2110 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2112 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2113 assert(VA.isMemLoc());
2114 if (StackPtr.getNode() == 0)
2115 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2116 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2117 dl, DAG, VA, Flags));
2121 if (!MemOpChains.empty())
2122 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2123 &MemOpChains[0], MemOpChains.size());
2125 // Build a sequence of copy-to-reg nodes chained together with token chain
2126 // and flag operands which copy the outgoing args into registers.
2128 // Tail call byval lowering might overwrite argument registers so in case of
2129 // tail call optimization the copies to registers are lowered later.
2131 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2132 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2133 RegsToPass[i].second, InFlag);
2134 InFlag = Chain.getValue(1);
2137 if (Subtarget->isPICStyleGOT()) {
2138 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2141 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2142 DAG.getNode(X86ISD::GlobalBaseReg,
2143 DebugLoc(), getPointerTy()),
2145 InFlag = Chain.getValue(1);
2147 // If we are tail calling and generating PIC/GOT style code load the
2148 // address of the callee into ECX. The value in ecx is used as target of
2149 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2150 // for tail calls on PIC/GOT architectures. Normally we would just put the
2151 // address of GOT into ebx and then call target@PLT. But for tail calls
2152 // ebx would be restored (since ebx is callee saved) before jumping to the
2155 // Note: The actual moving to ECX is done further down.
2156 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2157 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2158 !G->getGlobal()->hasProtectedVisibility())
2159 Callee = LowerGlobalAddress(Callee, DAG);
2160 else if (isa<ExternalSymbolSDNode>(Callee))
2161 Callee = LowerExternalSymbol(Callee, DAG);
2165 if (Is64Bit && isVarArg && !IsWin64) {
2166 // From AMD64 ABI document:
2167 // For calls that may call functions that use varargs or stdargs
2168 // (prototype-less calls or calls to functions containing ellipsis (...) in
2169 // the declaration) %al is used as hidden argument to specify the number
2170 // of SSE registers used. The contents of %al do not need to match exactly
2171 // the number of registers, but must be an ubound on the number of SSE
2172 // registers used and is in the range 0 - 8 inclusive.
2174 // Count the number of XMM registers allocated.
2175 static const unsigned XMMArgRegs[] = {
2176 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2177 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2179 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2180 assert((Subtarget->hasXMM() || !NumXMMRegs)
2181 && "SSE registers cannot be used when SSE is disabled");
2183 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2184 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2185 InFlag = Chain.getValue(1);
2189 // For tail calls lower the arguments to the 'real' stack slot.
2191 // Force all the incoming stack arguments to be loaded from the stack
2192 // before any new outgoing arguments are stored to the stack, because the
2193 // outgoing stack slots may alias the incoming argument stack slots, and
2194 // the alias isn't otherwise explicit. This is slightly more conservative
2195 // than necessary, because it means that each store effectively depends
2196 // on every argument instead of just those arguments it would clobber.
2197 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2199 SmallVector<SDValue, 8> MemOpChains2;
2202 // Do not flag preceding copytoreg stuff together with the following stuff.
2204 if (GuaranteedTailCallOpt) {
2205 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2206 CCValAssign &VA = ArgLocs[i];
2209 assert(VA.isMemLoc());
2210 SDValue Arg = OutVals[i];
2211 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2212 // Create frame index.
2213 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2214 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2215 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2216 FIN = DAG.getFrameIndex(FI, getPointerTy());
2218 if (Flags.isByVal()) {
2219 // Copy relative to framepointer.
2220 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2221 if (StackPtr.getNode() == 0)
2222 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2224 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2226 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2230 // Store relative to framepointer.
2231 MemOpChains2.push_back(
2232 DAG.getStore(ArgChain, dl, Arg, FIN,
2233 MachinePointerInfo::getFixedStack(FI),
2239 if (!MemOpChains2.empty())
2240 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2241 &MemOpChains2[0], MemOpChains2.size());
2243 // Copy arguments to their registers.
2244 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2245 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2246 RegsToPass[i].second, InFlag);
2247 InFlag = Chain.getValue(1);
2251 // Store the return address to the appropriate stack slot.
2252 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2256 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2257 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2258 // In the 64-bit large code model, we have to make all calls
2259 // through a register, since the call instruction's 32-bit
2260 // pc-relative offset may not be large enough to hold the whole
2262 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2263 // If the callee is a GlobalAddress node (quite common, every direct call
2264 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2267 // We should use extra load for direct calls to dllimported functions in
2269 const GlobalValue *GV = G->getGlobal();
2270 if (!GV->hasDLLImportLinkage()) {
2271 unsigned char OpFlags = 0;
2273 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2274 // external symbols most go through the PLT in PIC mode. If the symbol
2275 // has hidden or protected visibility, or if it is static or local, then
2276 // we don't need to use the PLT - we can directly call it.
2277 if (Subtarget->isTargetELF() &&
2278 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2279 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2280 OpFlags = X86II::MO_PLT;
2281 } else if (Subtarget->isPICStyleStubAny() &&
2282 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2283 (!Subtarget->getTargetTriple().isMacOSX() ||
2284 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2285 // PC-relative references to external symbols should go through $stub,
2286 // unless we're building with the leopard linker or later, which
2287 // automatically synthesizes these stubs.
2288 OpFlags = X86II::MO_DARWIN_STUB;
2291 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2292 G->getOffset(), OpFlags);
2294 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2295 unsigned char OpFlags = 0;
2297 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2298 // external symbols should go through the PLT.
2299 if (Subtarget->isTargetELF() &&
2300 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2301 OpFlags = X86II::MO_PLT;
2302 } else if (Subtarget->isPICStyleStubAny() &&
2303 (!Subtarget->getTargetTriple().isMacOSX() ||
2304 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2305 // PC-relative references to external symbols should go through $stub,
2306 // unless we're building with the leopard linker or later, which
2307 // automatically synthesizes these stubs.
2308 OpFlags = X86II::MO_DARWIN_STUB;
2311 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2315 // Returns a chain & a flag for retval copy to use.
2316 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2317 SmallVector<SDValue, 8> Ops;
2319 if (!IsSibcall && isTailCall) {
2320 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2321 DAG.getIntPtrConstant(0, true), InFlag);
2322 InFlag = Chain.getValue(1);
2325 Ops.push_back(Chain);
2326 Ops.push_back(Callee);
2329 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2331 // Add argument registers to the end of the list so that they are known live
2333 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2334 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2335 RegsToPass[i].second.getValueType()));
2337 // Add an implicit use GOT pointer in EBX.
2338 if (!isTailCall && Subtarget->isPICStyleGOT())
2339 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2341 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2342 if (Is64Bit && isVarArg && !IsWin64)
2343 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2345 if (InFlag.getNode())
2346 Ops.push_back(InFlag);
2350 //// If this is the first return lowered for this function, add the regs
2351 //// to the liveout set for the function.
2352 // This isn't right, although it's probably harmless on x86; liveouts
2353 // should be computed from returns not tail calls. Consider a void
2354 // function making a tail call to a function returning int.
2355 return DAG.getNode(X86ISD::TC_RETURN, dl,
2356 NodeTys, &Ops[0], Ops.size());
2359 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2360 InFlag = Chain.getValue(1);
2362 // Create the CALLSEQ_END node.
2363 unsigned NumBytesForCalleeToPush;
2364 if (Subtarget->IsCalleePop(isVarArg, CallConv))
2365 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2366 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2367 // If this is a call to a struct-return function, the callee
2368 // pops the hidden struct pointer, so we have to push it back.
2369 // This is common for Darwin/X86, Linux & Mingw32 targets.
2370 NumBytesForCalleeToPush = 4;
2372 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2374 // Returns a flag for retval copy to use.
2376 Chain = DAG.getCALLSEQ_END(Chain,
2377 DAG.getIntPtrConstant(NumBytes, true),
2378 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2381 InFlag = Chain.getValue(1);
2384 // Handle result values, copying them out of physregs into vregs that we
2386 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2387 Ins, dl, DAG, InVals);
2391 //===----------------------------------------------------------------------===//
2392 // Fast Calling Convention (tail call) implementation
2393 //===----------------------------------------------------------------------===//
2395 // Like std call, callee cleans arguments, convention except that ECX is
2396 // reserved for storing the tail called function address. Only 2 registers are
2397 // free for argument passing (inreg). Tail call optimization is performed
2399 // * tailcallopt is enabled
2400 // * caller/callee are fastcc
2401 // On X86_64 architecture with GOT-style position independent code only local
2402 // (within module) calls are supported at the moment.
2403 // To keep the stack aligned according to platform abi the function
2404 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2405 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2406 // If a tail called function callee has more arguments than the caller the
2407 // caller needs to make sure that there is room to move the RETADDR to. This is
2408 // achieved by reserving an area the size of the argument delta right after the
2409 // original REtADDR, but before the saved framepointer or the spilled registers
2410 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2422 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2423 /// for a 16 byte align requirement.
2425 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2426 SelectionDAG& DAG) const {
2427 MachineFunction &MF = DAG.getMachineFunction();
2428 const TargetMachine &TM = MF.getTarget();
2429 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2430 unsigned StackAlignment = TFI.getStackAlignment();
2431 uint64_t AlignMask = StackAlignment - 1;
2432 int64_t Offset = StackSize;
2433 uint64_t SlotSize = TD->getPointerSize();
2434 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2435 // Number smaller than 12 so just add the difference.
2436 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2438 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2439 Offset = ((~AlignMask) & Offset) + StackAlignment +
2440 (StackAlignment-SlotSize);
2445 /// MatchingStackOffset - Return true if the given stack call argument is
2446 /// already available in the same position (relatively) of the caller's
2447 /// incoming argument stack.
2449 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2450 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2451 const X86InstrInfo *TII) {
2452 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2454 if (Arg.getOpcode() == ISD::CopyFromReg) {
2455 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2456 if (!TargetRegisterInfo::isVirtualRegister(VR))
2458 MachineInstr *Def = MRI->getVRegDef(VR);
2461 if (!Flags.isByVal()) {
2462 if (!TII->isLoadFromStackSlot(Def, FI))
2465 unsigned Opcode = Def->getOpcode();
2466 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2467 Def->getOperand(1).isFI()) {
2468 FI = Def->getOperand(1).getIndex();
2469 Bytes = Flags.getByValSize();
2473 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2474 if (Flags.isByVal())
2475 // ByVal argument is passed in as a pointer but it's now being
2476 // dereferenced. e.g.
2477 // define @foo(%struct.X* %A) {
2478 // tail call @bar(%struct.X* byval %A)
2481 SDValue Ptr = Ld->getBasePtr();
2482 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2485 FI = FINode->getIndex();
2489 assert(FI != INT_MAX);
2490 if (!MFI->isFixedObjectIndex(FI))
2492 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2495 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2496 /// for tail call optimization. Targets which want to do tail call
2497 /// optimization should implement this function.
2499 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2500 CallingConv::ID CalleeCC,
2502 bool isCalleeStructRet,
2503 bool isCallerStructRet,
2504 const SmallVectorImpl<ISD::OutputArg> &Outs,
2505 const SmallVectorImpl<SDValue> &OutVals,
2506 const SmallVectorImpl<ISD::InputArg> &Ins,
2507 SelectionDAG& DAG) const {
2508 if (!IsTailCallConvention(CalleeCC) &&
2509 CalleeCC != CallingConv::C)
2512 // If -tailcallopt is specified, make fastcc functions tail-callable.
2513 const MachineFunction &MF = DAG.getMachineFunction();
2514 const Function *CallerF = DAG.getMachineFunction().getFunction();
2515 CallingConv::ID CallerCC = CallerF->getCallingConv();
2516 bool CCMatch = CallerCC == CalleeCC;
2518 if (GuaranteedTailCallOpt) {
2519 if (IsTailCallConvention(CalleeCC) && CCMatch)
2524 // Look for obvious safe cases to perform tail call optimization that do not
2525 // require ABI changes. This is what gcc calls sibcall.
2527 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2528 // emit a special epilogue.
2529 if (RegInfo->needsStackRealignment(MF))
2532 // Also avoid sibcall optimization if either caller or callee uses struct
2533 // return semantics.
2534 if (isCalleeStructRet || isCallerStructRet)
2537 // Do not sibcall optimize vararg calls unless all arguments are passed via
2539 if (isVarArg && !Outs.empty()) {
2541 // Optimizing for varargs on Win64 is unlikely to be safe without
2542 // additional testing.
2543 if (Subtarget->isTargetWin64())
2546 SmallVector<CCValAssign, 16> ArgLocs;
2547 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2548 ArgLocs, *DAG.getContext());
2550 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2551 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2552 if (!ArgLocs[i].isRegLoc())
2556 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2557 // Therefore if it's not used by the call it is not safe to optimize this into
2559 bool Unused = false;
2560 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2567 SmallVector<CCValAssign, 16> RVLocs;
2568 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2569 RVLocs, *DAG.getContext());
2570 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2571 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2572 CCValAssign &VA = RVLocs[i];
2573 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2578 // If the calling conventions do not match, then we'd better make sure the
2579 // results are returned in the same way as what the caller expects.
2581 SmallVector<CCValAssign, 16> RVLocs1;
2582 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2583 RVLocs1, *DAG.getContext());
2584 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2586 SmallVector<CCValAssign, 16> RVLocs2;
2587 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2588 RVLocs2, *DAG.getContext());
2589 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2591 if (RVLocs1.size() != RVLocs2.size())
2593 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2594 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2596 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2598 if (RVLocs1[i].isRegLoc()) {
2599 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2602 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2608 // If the callee takes no arguments then go on to check the results of the
2610 if (!Outs.empty()) {
2611 // Check if stack adjustment is needed. For now, do not do this if any
2612 // argument is passed on the stack.
2613 SmallVector<CCValAssign, 16> ArgLocs;
2614 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2615 ArgLocs, *DAG.getContext());
2617 // Allocate shadow area for Win64
2618 if (Subtarget->isTargetWin64()) {
2619 CCInfo.AllocateStack(32, 8);
2622 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2623 if (CCInfo.getNextStackOffset()) {
2624 MachineFunction &MF = DAG.getMachineFunction();
2625 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2628 // Check if the arguments are already laid out in the right way as
2629 // the caller's fixed stack objects.
2630 MachineFrameInfo *MFI = MF.getFrameInfo();
2631 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2632 const X86InstrInfo *TII =
2633 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2634 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2635 CCValAssign &VA = ArgLocs[i];
2636 SDValue Arg = OutVals[i];
2637 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2638 if (VA.getLocInfo() == CCValAssign::Indirect)
2640 if (!VA.isRegLoc()) {
2641 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2648 // If the tailcall address may be in a register, then make sure it's
2649 // possible to register allocate for it. In 32-bit, the call address can
2650 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2651 // callee-saved registers are restored. These happen to be the same
2652 // registers used to pass 'inreg' arguments so watch out for those.
2653 if (!Subtarget->is64Bit() &&
2654 !isa<GlobalAddressSDNode>(Callee) &&
2655 !isa<ExternalSymbolSDNode>(Callee)) {
2656 unsigned NumInRegs = 0;
2657 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2658 CCValAssign &VA = ArgLocs[i];
2661 unsigned Reg = VA.getLocReg();
2664 case X86::EAX: case X86::EDX: case X86::ECX:
2665 if (++NumInRegs == 3)
2673 // An stdcall caller is expected to clean up its arguments; the callee
2674 // isn't going to do that.
2675 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2682 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2683 return X86::createFastISel(funcInfo);
2687 //===----------------------------------------------------------------------===//
2688 // Other Lowering Hooks
2689 //===----------------------------------------------------------------------===//
2691 static bool MayFoldLoad(SDValue Op) {
2692 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2695 static bool MayFoldIntoStore(SDValue Op) {
2696 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2699 static bool isTargetShuffle(unsigned Opcode) {
2701 default: return false;
2702 case X86ISD::PSHUFD:
2703 case X86ISD::PSHUFHW:
2704 case X86ISD::PSHUFLW:
2705 case X86ISD::SHUFPD:
2706 case X86ISD::PALIGN:
2707 case X86ISD::SHUFPS:
2708 case X86ISD::MOVLHPS:
2709 case X86ISD::MOVLHPD:
2710 case X86ISD::MOVHLPS:
2711 case X86ISD::MOVLPS:
2712 case X86ISD::MOVLPD:
2713 case X86ISD::MOVSHDUP:
2714 case X86ISD::MOVSLDUP:
2715 case X86ISD::MOVDDUP:
2718 case X86ISD::UNPCKLPS:
2719 case X86ISD::UNPCKLPD:
2720 case X86ISD::VUNPCKLPS:
2721 case X86ISD::VUNPCKLPD:
2722 case X86ISD::VUNPCKLPSY:
2723 case X86ISD::VUNPCKLPDY:
2724 case X86ISD::PUNPCKLWD:
2725 case X86ISD::PUNPCKLBW:
2726 case X86ISD::PUNPCKLDQ:
2727 case X86ISD::PUNPCKLQDQ:
2728 case X86ISD::UNPCKHPS:
2729 case X86ISD::UNPCKHPD:
2730 case X86ISD::PUNPCKHWD:
2731 case X86ISD::PUNPCKHBW:
2732 case X86ISD::PUNPCKHDQ:
2733 case X86ISD::PUNPCKHQDQ:
2739 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2740 SDValue V1, SelectionDAG &DAG) {
2742 default: llvm_unreachable("Unknown x86 shuffle node");
2743 case X86ISD::MOVSHDUP:
2744 case X86ISD::MOVSLDUP:
2745 case X86ISD::MOVDDUP:
2746 return DAG.getNode(Opc, dl, VT, V1);
2752 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2753 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2755 default: llvm_unreachable("Unknown x86 shuffle node");
2756 case X86ISD::PSHUFD:
2757 case X86ISD::PSHUFHW:
2758 case X86ISD::PSHUFLW:
2759 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2765 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2766 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2768 default: llvm_unreachable("Unknown x86 shuffle node");
2769 case X86ISD::PALIGN:
2770 case X86ISD::SHUFPD:
2771 case X86ISD::SHUFPS:
2772 return DAG.getNode(Opc, dl, VT, V1, V2,
2773 DAG.getConstant(TargetMask, MVT::i8));
2778 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2779 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2781 default: llvm_unreachable("Unknown x86 shuffle node");
2782 case X86ISD::MOVLHPS:
2783 case X86ISD::MOVLHPD:
2784 case X86ISD::MOVHLPS:
2785 case X86ISD::MOVLPS:
2786 case X86ISD::MOVLPD:
2789 case X86ISD::UNPCKLPS:
2790 case X86ISD::UNPCKLPD:
2791 case X86ISD::VUNPCKLPS:
2792 case X86ISD::VUNPCKLPD:
2793 case X86ISD::VUNPCKLPSY:
2794 case X86ISD::VUNPCKLPDY:
2795 case X86ISD::PUNPCKLWD:
2796 case X86ISD::PUNPCKLBW:
2797 case X86ISD::PUNPCKLDQ:
2798 case X86ISD::PUNPCKLQDQ:
2799 case X86ISD::UNPCKHPS:
2800 case X86ISD::UNPCKHPD:
2801 case X86ISD::PUNPCKHWD:
2802 case X86ISD::PUNPCKHBW:
2803 case X86ISD::PUNPCKHDQ:
2804 case X86ISD::PUNPCKHQDQ:
2805 return DAG.getNode(Opc, dl, VT, V1, V2);
2810 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2811 MachineFunction &MF = DAG.getMachineFunction();
2812 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2813 int ReturnAddrIndex = FuncInfo->getRAIndex();
2815 if (ReturnAddrIndex == 0) {
2816 // Set up a frame object for the return address.
2817 uint64_t SlotSize = TD->getPointerSize();
2818 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2820 FuncInfo->setRAIndex(ReturnAddrIndex);
2823 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2827 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2828 bool hasSymbolicDisplacement) {
2829 // Offset should fit into 32 bit immediate field.
2830 if (!isInt<32>(Offset))
2833 // If we don't have a symbolic displacement - we don't have any extra
2835 if (!hasSymbolicDisplacement)
2838 // FIXME: Some tweaks might be needed for medium code model.
2839 if (M != CodeModel::Small && M != CodeModel::Kernel)
2842 // For small code model we assume that latest object is 16MB before end of 31
2843 // bits boundary. We may also accept pretty large negative constants knowing
2844 // that all objects are in the positive half of address space.
2845 if (M == CodeModel::Small && Offset < 16*1024*1024)
2848 // For kernel code model we know that all object resist in the negative half
2849 // of 32bits address space. We may not accept negative offsets, since they may
2850 // be just off and we may accept pretty large positive ones.
2851 if (M == CodeModel::Kernel && Offset > 0)
2857 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2858 /// specific condition code, returning the condition code and the LHS/RHS of the
2859 /// comparison to make.
2860 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2861 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2863 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2864 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2865 // X > -1 -> X == 0, jump !sign.
2866 RHS = DAG.getConstant(0, RHS.getValueType());
2867 return X86::COND_NS;
2868 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2869 // X < 0 -> X == 0, jump on sign.
2871 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2873 RHS = DAG.getConstant(0, RHS.getValueType());
2874 return X86::COND_LE;
2878 switch (SetCCOpcode) {
2879 default: llvm_unreachable("Invalid integer condition!");
2880 case ISD::SETEQ: return X86::COND_E;
2881 case ISD::SETGT: return X86::COND_G;
2882 case ISD::SETGE: return X86::COND_GE;
2883 case ISD::SETLT: return X86::COND_L;
2884 case ISD::SETLE: return X86::COND_LE;
2885 case ISD::SETNE: return X86::COND_NE;
2886 case ISD::SETULT: return X86::COND_B;
2887 case ISD::SETUGT: return X86::COND_A;
2888 case ISD::SETULE: return X86::COND_BE;
2889 case ISD::SETUGE: return X86::COND_AE;
2893 // First determine if it is required or is profitable to flip the operands.
2895 // If LHS is a foldable load, but RHS is not, flip the condition.
2896 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2897 !ISD::isNON_EXTLoad(RHS.getNode())) {
2898 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2899 std::swap(LHS, RHS);
2902 switch (SetCCOpcode) {
2908 std::swap(LHS, RHS);
2912 // On a floating point condition, the flags are set as follows:
2914 // 0 | 0 | 0 | X > Y
2915 // 0 | 0 | 1 | X < Y
2916 // 1 | 0 | 0 | X == Y
2917 // 1 | 1 | 1 | unordered
2918 switch (SetCCOpcode) {
2919 default: llvm_unreachable("Condcode should be pre-legalized away");
2921 case ISD::SETEQ: return X86::COND_E;
2922 case ISD::SETOLT: // flipped
2924 case ISD::SETGT: return X86::COND_A;
2925 case ISD::SETOLE: // flipped
2927 case ISD::SETGE: return X86::COND_AE;
2928 case ISD::SETUGT: // flipped
2930 case ISD::SETLT: return X86::COND_B;
2931 case ISD::SETUGE: // flipped
2933 case ISD::SETLE: return X86::COND_BE;
2935 case ISD::SETNE: return X86::COND_NE;
2936 case ISD::SETUO: return X86::COND_P;
2937 case ISD::SETO: return X86::COND_NP;
2939 case ISD::SETUNE: return X86::COND_INVALID;
2943 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2944 /// code. Current x86 isa includes the following FP cmov instructions:
2945 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2946 static bool hasFPCMov(unsigned X86CC) {
2962 /// isFPImmLegal - Returns true if the target can instruction select the
2963 /// specified FP immediate natively. If false, the legalizer will
2964 /// materialize the FP immediate as a load from a constant pool.
2965 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2966 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2967 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2973 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2974 /// the specified range (L, H].
2975 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2976 return (Val < 0) || (Val >= Low && Val < Hi);
2979 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2980 /// specified value.
2981 static bool isUndefOrEqual(int Val, int CmpVal) {
2982 if (Val < 0 || Val == CmpVal)
2987 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2988 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2989 /// the second operand.
2990 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2991 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2992 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2993 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2994 return (Mask[0] < 2 && Mask[1] < 2);
2998 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2999 SmallVector<int, 8> M;
3001 return ::isPSHUFDMask(M, N->getValueType(0));
3004 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3005 /// is suitable for input to PSHUFHW.
3006 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3007 if (VT != MVT::v8i16)
3010 // Lower quadword copied in order or undef.
3011 for (int i = 0; i != 4; ++i)
3012 if (Mask[i] >= 0 && Mask[i] != i)
3015 // Upper quadword shuffled.
3016 for (int i = 4; i != 8; ++i)
3017 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3023 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3024 SmallVector<int, 8> M;
3026 return ::isPSHUFHWMask(M, N->getValueType(0));
3029 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3030 /// is suitable for input to PSHUFLW.
3031 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3032 if (VT != MVT::v8i16)
3035 // Upper quadword copied in order.
3036 for (int i = 4; i != 8; ++i)
3037 if (Mask[i] >= 0 && Mask[i] != i)
3040 // Lower quadword shuffled.
3041 for (int i = 0; i != 4; ++i)
3048 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3049 SmallVector<int, 8> M;
3051 return ::isPSHUFLWMask(M, N->getValueType(0));
3054 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3055 /// is suitable for input to PALIGNR.
3056 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3058 int i, e = VT.getVectorNumElements();
3060 // Do not handle v2i64 / v2f64 shuffles with palignr.
3061 if (e < 4 || !hasSSSE3)
3064 for (i = 0; i != e; ++i)
3068 // All undef, not a palignr.
3072 // Determine if it's ok to perform a palignr with only the LHS, since we
3073 // don't have access to the actual shuffle elements to see if RHS is undef.
3074 bool Unary = Mask[i] < (int)e;
3075 bool NeedsUnary = false;
3077 int s = Mask[i] - i;
3079 // Check the rest of the elements to see if they are consecutive.
3080 for (++i; i != e; ++i) {
3085 Unary = Unary && (m < (int)e);
3086 NeedsUnary = NeedsUnary || (m < s);
3088 if (NeedsUnary && !Unary)
3090 if (Unary && m != ((s+i) & (e-1)))
3092 if (!Unary && m != (s+i))
3098 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3099 SmallVector<int, 8> M;
3101 return ::isPALIGNRMask(M, N->getValueType(0), true);
3104 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3105 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3106 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3107 int NumElems = VT.getVectorNumElements();
3108 if (NumElems != 2 && NumElems != 4)
3111 int Half = NumElems / 2;
3112 for (int i = 0; i < Half; ++i)
3113 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3115 for (int i = Half; i < NumElems; ++i)
3116 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3122 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3123 SmallVector<int, 8> M;
3125 return ::isSHUFPMask(M, N->getValueType(0));
3128 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3129 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3130 /// half elements to come from vector 1 (which would equal the dest.) and
3131 /// the upper half to come from vector 2.
3132 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3133 int NumElems = VT.getVectorNumElements();
3135 if (NumElems != 2 && NumElems != 4)
3138 int Half = NumElems / 2;
3139 for (int i = 0; i < Half; ++i)
3140 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3142 for (int i = Half; i < NumElems; ++i)
3143 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3148 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3149 SmallVector<int, 8> M;
3151 return isCommutedSHUFPMask(M, N->getValueType(0));
3154 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3155 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3156 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3157 if (N->getValueType(0).getVectorNumElements() != 4)
3160 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3161 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3162 isUndefOrEqual(N->getMaskElt(1), 7) &&
3163 isUndefOrEqual(N->getMaskElt(2), 2) &&
3164 isUndefOrEqual(N->getMaskElt(3), 3);
3167 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3168 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3170 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3171 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3176 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3177 isUndefOrEqual(N->getMaskElt(1), 3) &&
3178 isUndefOrEqual(N->getMaskElt(2), 2) &&
3179 isUndefOrEqual(N->getMaskElt(3), 3);
3182 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3183 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3184 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3185 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3187 if (NumElems != 2 && NumElems != 4)
3190 for (unsigned i = 0; i < NumElems/2; ++i)
3191 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3194 for (unsigned i = NumElems/2; i < NumElems; ++i)
3195 if (!isUndefOrEqual(N->getMaskElt(i), i))
3201 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3202 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3203 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3204 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3206 if ((NumElems != 2 && NumElems != 4)
3207 || N->getValueType(0).getSizeInBits() > 128)
3210 for (unsigned i = 0; i < NumElems/2; ++i)
3211 if (!isUndefOrEqual(N->getMaskElt(i), i))
3214 for (unsigned i = 0; i < NumElems/2; ++i)
3215 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3221 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3222 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3223 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3224 bool V2IsSplat = false) {
3225 int NumElts = VT.getVectorNumElements();
3226 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3229 // Handle vector lengths > 128 bits. Define a "section" as a set of
3230 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3232 unsigned NumSections = VT.getSizeInBits() / 128;
3233 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3234 unsigned NumSectionElts = NumElts / NumSections;
3237 unsigned End = NumSectionElts;
3238 for (unsigned s = 0; s < NumSections; ++s) {
3239 for (unsigned i = Start, j = s * NumSectionElts;
3243 int BitI1 = Mask[i+1];
3244 if (!isUndefOrEqual(BitI, j))
3247 if (!isUndefOrEqual(BitI1, NumElts))
3250 if (!isUndefOrEqual(BitI1, j + NumElts))
3254 // Process the next 128 bits.
3255 Start += NumSectionElts;
3256 End += NumSectionElts;
3262 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3263 SmallVector<int, 8> M;
3265 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3268 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3269 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3270 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3271 bool V2IsSplat = false) {
3272 int NumElts = VT.getVectorNumElements();
3273 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3276 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3278 int BitI1 = Mask[i+1];
3279 if (!isUndefOrEqual(BitI, j + NumElts/2))
3282 if (isUndefOrEqual(BitI1, NumElts))
3285 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3292 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3293 SmallVector<int, 8> M;
3295 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3298 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3299 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3301 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3302 int NumElems = VT.getVectorNumElements();
3303 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3306 // Handle vector lengths > 128 bits. Define a "section" as a set of
3307 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3309 unsigned NumSections = VT.getSizeInBits() / 128;
3310 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3311 unsigned NumSectionElts = NumElems / NumSections;
3313 for (unsigned s = 0; s < NumSections; ++s) {
3314 for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3315 i != NumSectionElts * (s + 1);
3318 int BitI1 = Mask[i+1];
3320 if (!isUndefOrEqual(BitI, j))
3322 if (!isUndefOrEqual(BitI1, j))
3330 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3331 SmallVector<int, 8> M;
3333 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3336 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3337 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3339 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3340 int NumElems = VT.getVectorNumElements();
3341 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3344 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3346 int BitI1 = Mask[i+1];
3347 if (!isUndefOrEqual(BitI, j))
3349 if (!isUndefOrEqual(BitI1, j))
3355 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3356 SmallVector<int, 8> M;
3358 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3361 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3362 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3363 /// MOVSD, and MOVD, i.e. setting the lowest element.
3364 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3365 if (VT.getVectorElementType().getSizeInBits() < 32)
3368 int NumElts = VT.getVectorNumElements();
3370 if (!isUndefOrEqual(Mask[0], NumElts))
3373 for (int i = 1; i < NumElts; ++i)
3374 if (!isUndefOrEqual(Mask[i], i))
3380 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3381 SmallVector<int, 8> M;
3383 return ::isMOVLMask(M, N->getValueType(0));
3386 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3387 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3388 /// element of vector 2 and the other elements to come from vector 1 in order.
3389 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3390 bool V2IsSplat = false, bool V2IsUndef = false) {
3391 int NumOps = VT.getVectorNumElements();
3392 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3395 if (!isUndefOrEqual(Mask[0], 0))
3398 for (int i = 1; i < NumOps; ++i)
3399 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3400 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3401 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3407 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3408 bool V2IsUndef = false) {
3409 SmallVector<int, 8> M;
3411 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3414 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3415 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3416 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3417 if (N->getValueType(0).getVectorNumElements() != 4)
3420 // Expect 1, 1, 3, 3
3421 for (unsigned i = 0; i < 2; ++i) {
3422 int Elt = N->getMaskElt(i);
3423 if (Elt >= 0 && Elt != 1)
3428 for (unsigned i = 2; i < 4; ++i) {
3429 int Elt = N->getMaskElt(i);
3430 if (Elt >= 0 && Elt != 3)
3435 // Don't use movshdup if it can be done with a shufps.
3436 // FIXME: verify that matching u, u, 3, 3 is what we want.
3440 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3441 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3442 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3443 if (N->getValueType(0).getVectorNumElements() != 4)
3446 // Expect 0, 0, 2, 2
3447 for (unsigned i = 0; i < 2; ++i)
3448 if (N->getMaskElt(i) > 0)
3452 for (unsigned i = 2; i < 4; ++i) {
3453 int Elt = N->getMaskElt(i);
3454 if (Elt >= 0 && Elt != 2)
3459 // Don't use movsldup if it can be done with a shufps.
3463 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3464 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3465 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3466 int e = N->getValueType(0).getVectorNumElements() / 2;
3468 for (int i = 0; i < e; ++i)
3469 if (!isUndefOrEqual(N->getMaskElt(i), i))
3471 for (int i = 0; i < e; ++i)
3472 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3477 /// isVEXTRACTF128Index - Return true if the specified
3478 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3479 /// suitable for input to VEXTRACTF128.
3480 bool X86::isVEXTRACTF128Index(SDNode *N) {
3481 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3484 // The index should be aligned on a 128-bit boundary.
3486 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3488 unsigned VL = N->getValueType(0).getVectorNumElements();
3489 unsigned VBits = N->getValueType(0).getSizeInBits();
3490 unsigned ElSize = VBits / VL;
3491 bool Result = (Index * ElSize) % 128 == 0;
3496 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3497 /// operand specifies a subvector insert that is suitable for input to
3499 bool X86::isVINSERTF128Index(SDNode *N) {
3500 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3503 // The index should be aligned on a 128-bit boundary.
3505 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3507 unsigned VL = N->getValueType(0).getVectorNumElements();
3508 unsigned VBits = N->getValueType(0).getSizeInBits();
3509 unsigned ElSize = VBits / VL;
3510 bool Result = (Index * ElSize) % 128 == 0;
3515 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3516 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3517 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3518 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3519 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3521 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3523 for (int i = 0; i < NumOperands; ++i) {
3524 int Val = SVOp->getMaskElt(NumOperands-i-1);
3525 if (Val < 0) Val = 0;
3526 if (Val >= NumOperands) Val -= NumOperands;
3528 if (i != NumOperands - 1)
3534 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3535 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3536 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3537 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3539 // 8 nodes, but we only care about the last 4.
3540 for (unsigned i = 7; i >= 4; --i) {
3541 int Val = SVOp->getMaskElt(i);
3550 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3551 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3552 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3553 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3555 // 8 nodes, but we only care about the first 4.
3556 for (int i = 3; i >= 0; --i) {
3557 int Val = SVOp->getMaskElt(i);
3566 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3567 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3568 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3569 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3570 EVT VVT = N->getValueType(0);
3571 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3575 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3576 Val = SVOp->getMaskElt(i);
3580 return (Val - i) * EltSize;
3583 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3584 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3586 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3587 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3588 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3591 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3593 EVT VecVT = N->getOperand(0).getValueType();
3594 EVT ElVT = VecVT.getVectorElementType();
3596 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3598 return Index / NumElemsPerChunk;
3601 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3602 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3604 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3605 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3606 llvm_unreachable("Illegal insert subvector for VINSERTF128");
3609 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3611 EVT VecVT = N->getValueType(0);
3612 EVT ElVT = VecVT.getVectorElementType();
3614 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3616 return Index / NumElemsPerChunk;
3619 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3621 bool X86::isZeroNode(SDValue Elt) {
3622 return ((isa<ConstantSDNode>(Elt) &&
3623 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3624 (isa<ConstantFPSDNode>(Elt) &&
3625 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3628 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3629 /// their permute mask.
3630 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3631 SelectionDAG &DAG) {
3632 EVT VT = SVOp->getValueType(0);
3633 unsigned NumElems = VT.getVectorNumElements();
3634 SmallVector<int, 8> MaskVec;
3636 for (unsigned i = 0; i != NumElems; ++i) {
3637 int idx = SVOp->getMaskElt(i);
3639 MaskVec.push_back(idx);
3640 else if (idx < (int)NumElems)
3641 MaskVec.push_back(idx + NumElems);
3643 MaskVec.push_back(idx - NumElems);
3645 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3646 SVOp->getOperand(0), &MaskVec[0]);
3649 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3650 /// the two vector operands have swapped position.
3651 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3652 unsigned NumElems = VT.getVectorNumElements();
3653 for (unsigned i = 0; i != NumElems; ++i) {
3657 else if (idx < (int)NumElems)
3658 Mask[i] = idx + NumElems;
3660 Mask[i] = idx - NumElems;
3664 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3665 /// match movhlps. The lower half elements should come from upper half of
3666 /// V1 (and in order), and the upper half elements should come from the upper
3667 /// half of V2 (and in order).
3668 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3669 if (Op->getValueType(0).getVectorNumElements() != 4)
3671 for (unsigned i = 0, e = 2; i != e; ++i)
3672 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3674 for (unsigned i = 2; i != 4; ++i)
3675 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3680 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3681 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3683 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3684 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3686 N = N->getOperand(0).getNode();
3687 if (!ISD::isNON_EXTLoad(N))
3690 *LD = cast<LoadSDNode>(N);
3694 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3695 /// match movlp{s|d}. The lower half elements should come from lower half of
3696 /// V1 (and in order), and the upper half elements should come from the upper
3697 /// half of V2 (and in order). And since V1 will become the source of the
3698 /// MOVLP, it must be either a vector load or a scalar load to vector.
3699 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3700 ShuffleVectorSDNode *Op) {
3701 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3703 // Is V2 is a vector load, don't do this transformation. We will try to use
3704 // load folding shufps op.
3705 if (ISD::isNON_EXTLoad(V2))
3708 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3710 if (NumElems != 2 && NumElems != 4)
3712 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3713 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3715 for (unsigned i = NumElems/2; i != NumElems; ++i)
3716 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3721 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3723 static bool isSplatVector(SDNode *N) {
3724 if (N->getOpcode() != ISD::BUILD_VECTOR)
3727 SDValue SplatValue = N->getOperand(0);
3728 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3729 if (N->getOperand(i) != SplatValue)
3734 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3735 /// to an zero vector.
3736 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3737 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3738 SDValue V1 = N->getOperand(0);
3739 SDValue V2 = N->getOperand(1);
3740 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3741 for (unsigned i = 0; i != NumElems; ++i) {
3742 int Idx = N->getMaskElt(i);
3743 if (Idx >= (int)NumElems) {
3744 unsigned Opc = V2.getOpcode();
3745 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3747 if (Opc != ISD::BUILD_VECTOR ||
3748 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3750 } else if (Idx >= 0) {
3751 unsigned Opc = V1.getOpcode();
3752 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3754 if (Opc != ISD::BUILD_VECTOR ||
3755 !X86::isZeroNode(V1.getOperand(Idx)))
3762 /// getZeroVector - Returns a vector of specified type with all zero elements.
3764 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3766 assert(VT.isVector() && "Expected a vector type");
3768 // Always build SSE zero vectors as <4 x i32> bitcasted
3769 // to their dest type. This ensures they get CSE'd.
3771 if (VT.getSizeInBits() == 128) { // SSE
3772 if (HasSSE2) { // SSE2
3773 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3774 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3776 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3777 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3779 } else if (VT.getSizeInBits() == 256) { // AVX
3780 // 256-bit logic and arithmetic instructions in AVX are
3781 // all floating-point, no support for integer ops. Default
3782 // to emitting fp zeroed vectors then.
3783 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3784 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3785 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3787 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3790 /// getOnesVector - Returns a vector of specified type with all bits set.
3792 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3793 assert(VT.isVector() && "Expected a vector type");
3795 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3796 // type. This ensures they get CSE'd.
3797 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3799 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3800 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3804 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3805 /// that point to V2 points to its first element.
3806 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3807 EVT VT = SVOp->getValueType(0);
3808 unsigned NumElems = VT.getVectorNumElements();
3810 bool Changed = false;
3811 SmallVector<int, 8> MaskVec;
3812 SVOp->getMask(MaskVec);
3814 for (unsigned i = 0; i != NumElems; ++i) {
3815 if (MaskVec[i] > (int)NumElems) {
3816 MaskVec[i] = NumElems;
3821 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3822 SVOp->getOperand(1), &MaskVec[0]);
3823 return SDValue(SVOp, 0);
3826 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3827 /// operation of specified width.
3828 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3830 unsigned NumElems = VT.getVectorNumElements();
3831 SmallVector<int, 8> Mask;
3832 Mask.push_back(NumElems);
3833 for (unsigned i = 1; i != NumElems; ++i)
3835 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3838 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3839 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3841 unsigned NumElems = VT.getVectorNumElements();
3842 SmallVector<int, 8> Mask;
3843 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3845 Mask.push_back(i + NumElems);
3847 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3850 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3851 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3853 unsigned NumElems = VT.getVectorNumElements();
3854 unsigned Half = NumElems/2;
3855 SmallVector<int, 8> Mask;
3856 for (unsigned i = 0; i != Half; ++i) {
3857 Mask.push_back(i + Half);
3858 Mask.push_back(i + NumElems + Half);
3860 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3863 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3864 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3865 EVT PVT = MVT::v4f32;
3866 EVT VT = SV->getValueType(0);
3867 DebugLoc dl = SV->getDebugLoc();
3868 SDValue V1 = SV->getOperand(0);
3869 int NumElems = VT.getVectorNumElements();
3870 int EltNo = SV->getSplatIndex();
3872 // unpack elements to the correct location
3873 while (NumElems > 4) {
3874 if (EltNo < NumElems/2) {
3875 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3877 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3878 EltNo -= NumElems/2;
3883 // Perform the splat.
3884 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3885 V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3886 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3887 return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3890 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3891 /// vector of zero or undef vector. This produces a shuffle where the low
3892 /// element of V2 is swizzled into the zero/undef vector, landing at element
3893 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3894 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3895 bool isZero, bool HasSSE2,
3896 SelectionDAG &DAG) {
3897 EVT VT = V2.getValueType();
3899 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3900 unsigned NumElems = VT.getVectorNumElements();
3901 SmallVector<int, 16> MaskVec;
3902 for (unsigned i = 0; i != NumElems; ++i)
3903 // If this is the insertion idx, put the low elt of V2 here.
3904 MaskVec.push_back(i == Idx ? NumElems : i);
3905 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3908 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3909 /// element of the result of the vector shuffle.
3910 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3913 return SDValue(); // Limit search depth.
3915 SDValue V = SDValue(N, 0);
3916 EVT VT = V.getValueType();
3917 unsigned Opcode = V.getOpcode();
3919 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3920 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3921 Index = SV->getMaskElt(Index);
3924 return DAG.getUNDEF(VT.getVectorElementType());
3926 int NumElems = VT.getVectorNumElements();
3927 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3928 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3931 // Recurse into target specific vector shuffles to find scalars.
3932 if (isTargetShuffle(Opcode)) {
3933 int NumElems = VT.getVectorNumElements();
3934 SmallVector<unsigned, 16> ShuffleMask;
3938 case X86ISD::SHUFPS:
3939 case X86ISD::SHUFPD:
3940 ImmN = N->getOperand(N->getNumOperands()-1);
3941 DecodeSHUFPSMask(NumElems,
3942 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3945 case X86ISD::PUNPCKHBW:
3946 case X86ISD::PUNPCKHWD:
3947 case X86ISD::PUNPCKHDQ:
3948 case X86ISD::PUNPCKHQDQ:
3949 DecodePUNPCKHMask(NumElems, ShuffleMask);
3951 case X86ISD::UNPCKHPS:
3952 case X86ISD::UNPCKHPD:
3953 DecodeUNPCKHPMask(NumElems, ShuffleMask);
3955 case X86ISD::PUNPCKLBW:
3956 case X86ISD::PUNPCKLWD:
3957 case X86ISD::PUNPCKLDQ:
3958 case X86ISD::PUNPCKLQDQ:
3959 DecodePUNPCKLMask(VT, ShuffleMask);
3961 case X86ISD::UNPCKLPS:
3962 case X86ISD::UNPCKLPD:
3963 case X86ISD::VUNPCKLPS:
3964 case X86ISD::VUNPCKLPD:
3965 case X86ISD::VUNPCKLPSY:
3966 case X86ISD::VUNPCKLPDY:
3967 DecodeUNPCKLPMask(VT, ShuffleMask);
3969 case X86ISD::MOVHLPS:
3970 DecodeMOVHLPSMask(NumElems, ShuffleMask);
3972 case X86ISD::MOVLHPS:
3973 DecodeMOVLHPSMask(NumElems, ShuffleMask);
3975 case X86ISD::PSHUFD:
3976 ImmN = N->getOperand(N->getNumOperands()-1);
3977 DecodePSHUFMask(NumElems,
3978 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3981 case X86ISD::PSHUFHW:
3982 ImmN = N->getOperand(N->getNumOperands()-1);
3983 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3986 case X86ISD::PSHUFLW:
3987 ImmN = N->getOperand(N->getNumOperands()-1);
3988 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3992 case X86ISD::MOVSD: {
3993 // The index 0 always comes from the first element of the second source,
3994 // this is why MOVSS and MOVSD are used in the first place. The other
3995 // elements come from the other positions of the first source vector.
3996 unsigned OpNum = (Index == 0) ? 1 : 0;
3997 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4001 assert("not implemented for target shuffle node");
4005 Index = ShuffleMask[Index];
4007 return DAG.getUNDEF(VT.getVectorElementType());
4009 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4010 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4014 // Actual nodes that may contain scalar elements
4015 if (Opcode == ISD::BITCAST) {
4016 V = V.getOperand(0);
4017 EVT SrcVT = V.getValueType();
4018 unsigned NumElems = VT.getVectorNumElements();
4020 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4024 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4025 return (Index == 0) ? V.getOperand(0)
4026 : DAG.getUNDEF(VT.getVectorElementType());
4028 if (V.getOpcode() == ISD::BUILD_VECTOR)
4029 return V.getOperand(Index);
4034 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4035 /// shuffle operation which come from a consecutively from a zero. The
4036 /// search can start in two different directions, from left or right.
4038 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4039 bool ZerosFromLeft, SelectionDAG &DAG) {
4042 while (i < NumElems) {
4043 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4044 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4045 if (!(Elt.getNode() &&
4046 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4054 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4055 /// MaskE correspond consecutively to elements from one of the vector operands,
4056 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4058 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4059 int OpIdx, int NumElems, unsigned &OpNum) {
4060 bool SeenV1 = false;
4061 bool SeenV2 = false;
4063 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4064 int Idx = SVOp->getMaskElt(i);
4065 // Ignore undef indicies
4074 // Only accept consecutive elements from the same vector
4075 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4079 OpNum = SeenV1 ? 0 : 1;
4083 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4084 /// logical left shift of a vector.
4085 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4086 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4087 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4088 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4089 false /* check zeros from right */, DAG);
4095 // Considering the elements in the mask that are not consecutive zeros,
4096 // check if they consecutively come from only one of the source vectors.
4098 // V1 = {X, A, B, C} 0
4100 // vector_shuffle V1, V2 <1, 2, 3, X>
4102 if (!isShuffleMaskConsecutive(SVOp,
4103 0, // Mask Start Index
4104 NumElems-NumZeros-1, // Mask End Index
4105 NumZeros, // Where to start looking in the src vector
4106 NumElems, // Number of elements in vector
4107 OpSrc)) // Which source operand ?
4112 ShVal = SVOp->getOperand(OpSrc);
4116 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4117 /// logical left shift of a vector.
4118 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4119 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4120 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4121 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4122 true /* check zeros from left */, DAG);
4128 // Considering the elements in the mask that are not consecutive zeros,
4129 // check if they consecutively come from only one of the source vectors.
4131 // 0 { A, B, X, X } = V2
4133 // vector_shuffle V1, V2 <X, X, 4, 5>
4135 if (!isShuffleMaskConsecutive(SVOp,
4136 NumZeros, // Mask Start Index
4137 NumElems-1, // Mask End Index
4138 0, // Where to start looking in the src vector
4139 NumElems, // Number of elements in vector
4140 OpSrc)) // Which source operand ?
4145 ShVal = SVOp->getOperand(OpSrc);
4149 /// isVectorShift - Returns true if the shuffle can be implemented as a
4150 /// logical left or right shift of a vector.
4151 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4152 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4153 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4154 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4160 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4162 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4163 unsigned NumNonZero, unsigned NumZero,
4165 const TargetLowering &TLI) {
4169 DebugLoc dl = Op.getDebugLoc();
4172 for (unsigned i = 0; i < 16; ++i) {
4173 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4174 if (ThisIsNonZero && First) {
4176 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4178 V = DAG.getUNDEF(MVT::v8i16);
4183 SDValue ThisElt(0, 0), LastElt(0, 0);
4184 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4185 if (LastIsNonZero) {
4186 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4187 MVT::i16, Op.getOperand(i-1));
4189 if (ThisIsNonZero) {
4190 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4191 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4192 ThisElt, DAG.getConstant(8, MVT::i8));
4194 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4198 if (ThisElt.getNode())
4199 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4200 DAG.getIntPtrConstant(i/2));
4204 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4207 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4209 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4210 unsigned NumNonZero, unsigned NumZero,
4212 const TargetLowering &TLI) {
4216 DebugLoc dl = Op.getDebugLoc();
4219 for (unsigned i = 0; i < 8; ++i) {
4220 bool isNonZero = (NonZeros & (1 << i)) != 0;
4224 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4226 V = DAG.getUNDEF(MVT::v8i16);
4229 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4230 MVT::v8i16, V, Op.getOperand(i),
4231 DAG.getIntPtrConstant(i));
4238 /// getVShift - Return a vector logical shift node.
4240 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4241 unsigned NumBits, SelectionDAG &DAG,
4242 const TargetLowering &TLI, DebugLoc dl) {
4243 EVT ShVT = MVT::v2i64;
4244 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4245 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4246 return DAG.getNode(ISD::BITCAST, dl, VT,
4247 DAG.getNode(Opc, dl, ShVT, SrcOp,
4248 DAG.getConstant(NumBits,
4249 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4253 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4254 SelectionDAG &DAG) const {
4256 // Check if the scalar load can be widened into a vector load. And if
4257 // the address is "base + cst" see if the cst can be "absorbed" into
4258 // the shuffle mask.
4259 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4260 SDValue Ptr = LD->getBasePtr();
4261 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4263 EVT PVT = LD->getValueType(0);
4264 if (PVT != MVT::i32 && PVT != MVT::f32)
4269 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4270 FI = FINode->getIndex();
4272 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4273 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4274 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4275 Offset = Ptr.getConstantOperandVal(1);
4276 Ptr = Ptr.getOperand(0);
4281 SDValue Chain = LD->getChain();
4282 // Make sure the stack object alignment is at least 16.
4283 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4284 if (DAG.InferPtrAlignment(Ptr) < 16) {
4285 if (MFI->isFixedObjectIndex(FI)) {
4286 // Can't change the alignment. FIXME: It's possible to compute
4287 // the exact stack offset and reference FI + adjust offset instead.
4288 // If someone *really* cares about this. That's the way to implement it.
4291 MFI->setObjectAlignment(FI, 16);
4295 // (Offset % 16) must be multiple of 4. Then address is then
4296 // Ptr + (Offset & ~15).
4299 if ((Offset % 16) & 3)
4301 int64_t StartOffset = Offset & ~15;
4303 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4304 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4306 int EltNo = (Offset - StartOffset) >> 2;
4307 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4308 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4309 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4310 LD->getPointerInfo().getWithOffset(StartOffset),
4312 // Canonicalize it to a v4i32 shuffle.
4313 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4314 return DAG.getNode(ISD::BITCAST, dl, VT,
4315 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4316 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4322 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4323 /// vector of type 'VT', see if the elements can be replaced by a single large
4324 /// load which has the same value as a build_vector whose operands are 'elts'.
4326 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4328 /// FIXME: we'd also like to handle the case where the last elements are zero
4329 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4330 /// There's even a handy isZeroNode for that purpose.
4331 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4332 DebugLoc &DL, SelectionDAG &DAG) {
4333 EVT EltVT = VT.getVectorElementType();
4334 unsigned NumElems = Elts.size();
4336 LoadSDNode *LDBase = NULL;
4337 unsigned LastLoadedElt = -1U;
4339 // For each element in the initializer, see if we've found a load or an undef.
4340 // If we don't find an initial load element, or later load elements are
4341 // non-consecutive, bail out.
4342 for (unsigned i = 0; i < NumElems; ++i) {
4343 SDValue Elt = Elts[i];
4345 if (!Elt.getNode() ||
4346 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4349 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4351 LDBase = cast<LoadSDNode>(Elt.getNode());
4355 if (Elt.getOpcode() == ISD::UNDEF)
4358 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4359 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4364 // If we have found an entire vector of loads and undefs, then return a large
4365 // load of the entire vector width starting at the base pointer. If we found
4366 // consecutive loads for the low half, generate a vzext_load node.
4367 if (LastLoadedElt == NumElems - 1) {
4368 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4369 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4370 LDBase->getPointerInfo(),
4371 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4372 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4373 LDBase->getPointerInfo(),
4374 LDBase->isVolatile(), LDBase->isNonTemporal(),
4375 LDBase->getAlignment());
4376 } else if (NumElems == 4 && LastLoadedElt == 1) {
4377 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4378 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4379 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4381 LDBase->getMemOperand());
4382 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4388 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4389 DebugLoc dl = Op.getDebugLoc();
4391 EVT VT = Op.getValueType();
4392 EVT ExtVT = VT.getVectorElementType();
4394 unsigned NumElems = Op.getNumOperands();
4396 // For AVX-length vectors, build the individual 128-bit pieces and
4397 // use shuffles to put them in place.
4398 if (VT.getSizeInBits() > 256 &&
4399 Subtarget->hasAVX() &&
4400 !ISD::isBuildVectorAllZeros(Op.getNode())) {
4401 SmallVector<SDValue, 8> V;
4403 for (unsigned i = 0; i < NumElems; ++i) {
4404 V[i] = Op.getOperand(i);
4407 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4409 // Build the lower subvector.
4410 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4411 // Build the upper subvector.
4412 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4415 return ConcatVectors(Lower, Upper, DAG);
4418 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4419 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4420 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4421 // is present, so AllOnes is ignored.
4422 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4423 (Op.getValueType().getSizeInBits() != 256 &&
4424 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4425 // Canonicalize this to <4 x i32> (SSE) to
4426 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4427 // eliminated on x86-32 hosts.
4428 if (Op.getValueType() == MVT::v4i32)
4431 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4432 return getOnesVector(Op.getValueType(), DAG, dl);
4433 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4436 unsigned EVTBits = ExtVT.getSizeInBits();
4438 unsigned NumZero = 0;
4439 unsigned NumNonZero = 0;
4440 unsigned NonZeros = 0;
4441 bool IsAllConstants = true;
4442 SmallSet<SDValue, 8> Values;
4443 for (unsigned i = 0; i < NumElems; ++i) {
4444 SDValue Elt = Op.getOperand(i);
4445 if (Elt.getOpcode() == ISD::UNDEF)
4448 if (Elt.getOpcode() != ISD::Constant &&
4449 Elt.getOpcode() != ISD::ConstantFP)
4450 IsAllConstants = false;
4451 if (X86::isZeroNode(Elt))
4454 NonZeros |= (1 << i);
4459 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4460 if (NumNonZero == 0)
4461 return DAG.getUNDEF(VT);
4463 // Special case for single non-zero, non-undef, element.
4464 if (NumNonZero == 1) {
4465 unsigned Idx = CountTrailingZeros_32(NonZeros);
4466 SDValue Item = Op.getOperand(Idx);
4468 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4469 // the value are obviously zero, truncate the value to i32 and do the
4470 // insertion that way. Only do this if the value is non-constant or if the
4471 // value is a constant being inserted into element 0. It is cheaper to do
4472 // a constant pool load than it is to do a movd + shuffle.
4473 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4474 (!IsAllConstants || Idx == 0)) {
4475 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4477 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4478 EVT VecVT = MVT::v4i32;
4479 unsigned VecElts = 4;
4481 // Truncate the value (which may itself be a constant) to i32, and
4482 // convert it to a vector with movd (S2V+shuffle to zero extend).
4483 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4484 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4485 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4486 Subtarget->hasSSE2(), DAG);
4488 // Now we have our 32-bit value zero extended in the low element of
4489 // a vector. If Idx != 0, swizzle it into place.
4491 SmallVector<int, 4> Mask;
4492 Mask.push_back(Idx);
4493 for (unsigned i = 1; i != VecElts; ++i)
4495 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4496 DAG.getUNDEF(Item.getValueType()),
4499 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4503 // If we have a constant or non-constant insertion into the low element of
4504 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4505 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4506 // depending on what the source datatype is.
4509 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4510 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4511 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4512 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4513 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4514 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4516 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4517 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4518 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4519 EVT MiddleVT = MVT::v4i32;
4520 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4521 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4522 Subtarget->hasSSE2(), DAG);
4523 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4527 // Is it a vector logical left shift?
4528 if (NumElems == 2 && Idx == 1 &&
4529 X86::isZeroNode(Op.getOperand(0)) &&
4530 !X86::isZeroNode(Op.getOperand(1))) {
4531 unsigned NumBits = VT.getSizeInBits();
4532 return getVShift(true, VT,
4533 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4534 VT, Op.getOperand(1)),
4535 NumBits/2, DAG, *this, dl);
4538 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4541 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4542 // is a non-constant being inserted into an element other than the low one,
4543 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4544 // movd/movss) to move this into the low element, then shuffle it into
4546 if (EVTBits == 32) {
4547 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4549 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4550 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4551 Subtarget->hasSSE2(), DAG);
4552 SmallVector<int, 8> MaskVec;
4553 for (unsigned i = 0; i < NumElems; i++)
4554 MaskVec.push_back(i == Idx ? 0 : 1);
4555 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4559 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4560 if (Values.size() == 1) {
4561 if (EVTBits == 32) {
4562 // Instead of a shuffle like this:
4563 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4564 // Check if it's possible to issue this instead.
4565 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4566 unsigned Idx = CountTrailingZeros_32(NonZeros);
4567 SDValue Item = Op.getOperand(Idx);
4568 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4569 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4574 // A vector full of immediates; various special cases are already
4575 // handled, so this is best done with a single constant-pool load.
4579 // Let legalizer expand 2-wide build_vectors.
4580 if (EVTBits == 64) {
4581 if (NumNonZero == 1) {
4582 // One half is zero or undef.
4583 unsigned Idx = CountTrailingZeros_32(NonZeros);
4584 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4585 Op.getOperand(Idx));
4586 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4587 Subtarget->hasSSE2(), DAG);
4592 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4593 if (EVTBits == 8 && NumElems == 16) {
4594 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4596 if (V.getNode()) return V;
4599 if (EVTBits == 16 && NumElems == 8) {
4600 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4602 if (V.getNode()) return V;
4605 // If element VT is == 32 bits, turn it into a number of shuffles.
4606 SmallVector<SDValue, 8> V;
4608 if (NumElems == 4 && NumZero > 0) {
4609 for (unsigned i = 0; i < 4; ++i) {
4610 bool isZero = !(NonZeros & (1 << i));
4612 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4614 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4617 for (unsigned i = 0; i < 2; ++i) {
4618 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4621 V[i] = V[i*2]; // Must be a zero vector.
4624 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4627 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4630 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4635 SmallVector<int, 8> MaskVec;
4636 bool Reverse = (NonZeros & 0x3) == 2;
4637 for (unsigned i = 0; i < 2; ++i)
4638 MaskVec.push_back(Reverse ? 1-i : i);
4639 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4640 for (unsigned i = 0; i < 2; ++i)
4641 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4642 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4645 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4646 // Check for a build vector of consecutive loads.
4647 for (unsigned i = 0; i < NumElems; ++i)
4648 V[i] = Op.getOperand(i);
4650 // Check for elements which are consecutive loads.
4651 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4655 // For SSE 4.1, use insertps to put the high elements into the low element.
4656 if (getSubtarget()->hasSSE41()) {
4658 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4659 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4661 Result = DAG.getUNDEF(VT);
4663 for (unsigned i = 1; i < NumElems; ++i) {
4664 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4665 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4666 Op.getOperand(i), DAG.getIntPtrConstant(i));
4671 // Otherwise, expand into a number of unpckl*, start by extending each of
4672 // our (non-undef) elements to the full vector width with the element in the
4673 // bottom slot of the vector (which generates no code for SSE).
4674 for (unsigned i = 0; i < NumElems; ++i) {
4675 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4676 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4678 V[i] = DAG.getUNDEF(VT);
4681 // Next, we iteratively mix elements, e.g. for v4f32:
4682 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4683 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4684 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4685 unsigned EltStride = NumElems >> 1;
4686 while (EltStride != 0) {
4687 for (unsigned i = 0; i < EltStride; ++i) {
4688 // If V[i+EltStride] is undef and this is the first round of mixing,
4689 // then it is safe to just drop this shuffle: V[i] is already in the
4690 // right place, the one element (since it's the first round) being
4691 // inserted as undef can be dropped. This isn't safe for successive
4692 // rounds because they will permute elements within both vectors.
4693 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4694 EltStride == NumElems/2)
4697 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4707 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4708 // We support concatenate two MMX registers and place them in a MMX
4709 // register. This is better than doing a stack convert.
4710 DebugLoc dl = Op.getDebugLoc();
4711 EVT ResVT = Op.getValueType();
4712 assert(Op.getNumOperands() == 2);
4713 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4714 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4716 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4717 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4718 InVec = Op.getOperand(1);
4719 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4720 unsigned NumElts = ResVT.getVectorNumElements();
4721 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4722 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4723 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4725 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4726 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4727 Mask[0] = 0; Mask[1] = 2;
4728 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4730 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4733 // v8i16 shuffles - Prefer shuffles in the following order:
4734 // 1. [all] pshuflw, pshufhw, optional move
4735 // 2. [ssse3] 1 x pshufb
4736 // 3. [ssse3] 2 x pshufb + 1 x por
4737 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4739 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4740 SelectionDAG &DAG) const {
4741 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4742 SDValue V1 = SVOp->getOperand(0);
4743 SDValue V2 = SVOp->getOperand(1);
4744 DebugLoc dl = SVOp->getDebugLoc();
4745 SmallVector<int, 8> MaskVals;
4747 // Determine if more than 1 of the words in each of the low and high quadwords
4748 // of the result come from the same quadword of one of the two inputs. Undef
4749 // mask values count as coming from any quadword, for better codegen.
4750 SmallVector<unsigned, 4> LoQuad(4);
4751 SmallVector<unsigned, 4> HiQuad(4);
4752 BitVector InputQuads(4);
4753 for (unsigned i = 0; i < 8; ++i) {
4754 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4755 int EltIdx = SVOp->getMaskElt(i);
4756 MaskVals.push_back(EltIdx);
4765 InputQuads.set(EltIdx / 4);
4768 int BestLoQuad = -1;
4769 unsigned MaxQuad = 1;
4770 for (unsigned i = 0; i < 4; ++i) {
4771 if (LoQuad[i] > MaxQuad) {
4773 MaxQuad = LoQuad[i];
4777 int BestHiQuad = -1;
4779 for (unsigned i = 0; i < 4; ++i) {
4780 if (HiQuad[i] > MaxQuad) {
4782 MaxQuad = HiQuad[i];
4786 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4787 // of the two input vectors, shuffle them into one input vector so only a
4788 // single pshufb instruction is necessary. If There are more than 2 input
4789 // quads, disable the next transformation since it does not help SSSE3.
4790 bool V1Used = InputQuads[0] || InputQuads[1];
4791 bool V2Used = InputQuads[2] || InputQuads[3];
4792 if (Subtarget->hasSSSE3()) {
4793 if (InputQuads.count() == 2 && V1Used && V2Used) {
4794 BestLoQuad = InputQuads.find_first();
4795 BestHiQuad = InputQuads.find_next(BestLoQuad);
4797 if (InputQuads.count() > 2) {
4803 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4804 // the shuffle mask. If a quad is scored as -1, that means that it contains
4805 // words from all 4 input quadwords.
4807 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4808 SmallVector<int, 8> MaskV;
4809 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4810 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4811 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4812 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4813 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4814 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4816 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4817 // source words for the shuffle, to aid later transformations.
4818 bool AllWordsInNewV = true;
4819 bool InOrder[2] = { true, true };
4820 for (unsigned i = 0; i != 8; ++i) {
4821 int idx = MaskVals[i];
4823 InOrder[i/4] = false;
4824 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4826 AllWordsInNewV = false;
4830 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4831 if (AllWordsInNewV) {
4832 for (int i = 0; i != 8; ++i) {
4833 int idx = MaskVals[i];
4836 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4837 if ((idx != i) && idx < 4)
4839 if ((idx != i) && idx > 3)
4848 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4849 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4850 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4851 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4852 unsigned TargetMask = 0;
4853 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4854 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4855 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4856 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4857 V1 = NewV.getOperand(0);
4858 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4862 // If we have SSSE3, and all words of the result are from 1 input vector,
4863 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4864 // is present, fall back to case 4.
4865 if (Subtarget->hasSSSE3()) {
4866 SmallVector<SDValue,16> pshufbMask;
4868 // If we have elements from both input vectors, set the high bit of the
4869 // shuffle mask element to zero out elements that come from V2 in the V1
4870 // mask, and elements that come from V1 in the V2 mask, so that the two
4871 // results can be OR'd together.
4872 bool TwoInputs = V1Used && V2Used;
4873 for (unsigned i = 0; i != 8; ++i) {
4874 int EltIdx = MaskVals[i] * 2;
4875 if (TwoInputs && (EltIdx >= 16)) {
4876 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4877 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4880 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4881 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4883 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4884 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4885 DAG.getNode(ISD::BUILD_VECTOR, dl,
4886 MVT::v16i8, &pshufbMask[0], 16));
4888 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4890 // Calculate the shuffle mask for the second input, shuffle it, and
4891 // OR it with the first shuffled input.
4893 for (unsigned i = 0; i != 8; ++i) {
4894 int EltIdx = MaskVals[i] * 2;
4896 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4897 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4900 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4901 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4903 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4904 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4905 DAG.getNode(ISD::BUILD_VECTOR, dl,
4906 MVT::v16i8, &pshufbMask[0], 16));
4907 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4908 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4911 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4912 // and update MaskVals with new element order.
4913 BitVector InOrder(8);
4914 if (BestLoQuad >= 0) {
4915 SmallVector<int, 8> MaskV;
4916 for (int i = 0; i != 4; ++i) {
4917 int idx = MaskVals[i];
4919 MaskV.push_back(-1);
4921 } else if ((idx / 4) == BestLoQuad) {
4922 MaskV.push_back(idx & 3);
4925 MaskV.push_back(-1);
4928 for (unsigned i = 4; i != 8; ++i)
4930 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4933 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4934 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4936 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4940 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4941 // and update MaskVals with the new element order.
4942 if (BestHiQuad >= 0) {
4943 SmallVector<int, 8> MaskV;
4944 for (unsigned i = 0; i != 4; ++i)
4946 for (unsigned i = 4; i != 8; ++i) {
4947 int idx = MaskVals[i];
4949 MaskV.push_back(-1);
4951 } else if ((idx / 4) == BestHiQuad) {
4952 MaskV.push_back((idx & 3) + 4);
4955 MaskV.push_back(-1);
4958 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4961 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4962 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4964 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4968 // In case BestHi & BestLo were both -1, which means each quadword has a word
4969 // from each of the four input quadwords, calculate the InOrder bitvector now
4970 // before falling through to the insert/extract cleanup.
4971 if (BestLoQuad == -1 && BestHiQuad == -1) {
4973 for (int i = 0; i != 8; ++i)
4974 if (MaskVals[i] < 0 || MaskVals[i] == i)
4978 // The other elements are put in the right place using pextrw and pinsrw.
4979 for (unsigned i = 0; i != 8; ++i) {
4982 int EltIdx = MaskVals[i];
4985 SDValue ExtOp = (EltIdx < 8)
4986 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4987 DAG.getIntPtrConstant(EltIdx))
4988 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4989 DAG.getIntPtrConstant(EltIdx - 8));
4990 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4991 DAG.getIntPtrConstant(i));
4996 // v16i8 shuffles - Prefer shuffles in the following order:
4997 // 1. [ssse3] 1 x pshufb
4998 // 2. [ssse3] 2 x pshufb + 1 x por
4999 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5001 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5003 const X86TargetLowering &TLI) {
5004 SDValue V1 = SVOp->getOperand(0);
5005 SDValue V2 = SVOp->getOperand(1);
5006 DebugLoc dl = SVOp->getDebugLoc();
5007 SmallVector<int, 16> MaskVals;
5008 SVOp->getMask(MaskVals);
5010 // If we have SSSE3, case 1 is generated when all result bytes come from
5011 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5012 // present, fall back to case 3.
5013 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5016 for (unsigned i = 0; i < 16; ++i) {
5017 int EltIdx = MaskVals[i];
5026 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5027 if (TLI.getSubtarget()->hasSSSE3()) {
5028 SmallVector<SDValue,16> pshufbMask;
5030 // If all result elements are from one input vector, then only translate
5031 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5033 // Otherwise, we have elements from both input vectors, and must zero out
5034 // elements that come from V2 in the first mask, and V1 in the second mask
5035 // so that we can OR them together.
5036 bool TwoInputs = !(V1Only || V2Only);
5037 for (unsigned i = 0; i != 16; ++i) {
5038 int EltIdx = MaskVals[i];
5039 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5040 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5043 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5045 // If all the elements are from V2, assign it to V1 and return after
5046 // building the first pshufb.
5049 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5050 DAG.getNode(ISD::BUILD_VECTOR, dl,
5051 MVT::v16i8, &pshufbMask[0], 16));
5055 // Calculate the shuffle mask for the second input, shuffle it, and
5056 // OR it with the first shuffled input.
5058 for (unsigned i = 0; i != 16; ++i) {
5059 int EltIdx = MaskVals[i];
5061 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5064 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5066 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5067 DAG.getNode(ISD::BUILD_VECTOR, dl,
5068 MVT::v16i8, &pshufbMask[0], 16));
5069 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5072 // No SSSE3 - Calculate in place words and then fix all out of place words
5073 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5074 // the 16 different words that comprise the two doublequadword input vectors.
5075 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5076 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5077 SDValue NewV = V2Only ? V2 : V1;
5078 for (int i = 0; i != 8; ++i) {
5079 int Elt0 = MaskVals[i*2];
5080 int Elt1 = MaskVals[i*2+1];
5082 // This word of the result is all undef, skip it.
5083 if (Elt0 < 0 && Elt1 < 0)
5086 // This word of the result is already in the correct place, skip it.
5087 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5089 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5092 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5093 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5096 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5097 // using a single extract together, load it and store it.
5098 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5099 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5100 DAG.getIntPtrConstant(Elt1 / 2));
5101 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5102 DAG.getIntPtrConstant(i));
5106 // If Elt1 is defined, extract it from the appropriate source. If the
5107 // source byte is not also odd, shift the extracted word left 8 bits
5108 // otherwise clear the bottom 8 bits if we need to do an or.
5110 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5111 DAG.getIntPtrConstant(Elt1 / 2));
5112 if ((Elt1 & 1) == 0)
5113 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5115 TLI.getShiftAmountTy(InsElt.getValueType())));
5117 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5118 DAG.getConstant(0xFF00, MVT::i16));
5120 // If Elt0 is defined, extract it from the appropriate source. If the
5121 // source byte is not also even, shift the extracted word right 8 bits. If
5122 // Elt1 was also defined, OR the extracted values together before
5123 // inserting them in the result.
5125 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5126 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5127 if ((Elt0 & 1) != 0)
5128 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5130 TLI.getShiftAmountTy(InsElt0.getValueType())));
5132 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5133 DAG.getConstant(0x00FF, MVT::i16));
5134 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5137 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5138 DAG.getIntPtrConstant(i));
5140 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5143 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5144 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5145 /// done when every pair / quad of shuffle mask elements point to elements in
5146 /// the right sequence. e.g.
5147 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5149 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5150 SelectionDAG &DAG, DebugLoc dl) {
5151 EVT VT = SVOp->getValueType(0);
5152 SDValue V1 = SVOp->getOperand(0);
5153 SDValue V2 = SVOp->getOperand(1);
5154 unsigned NumElems = VT.getVectorNumElements();
5155 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5157 switch (VT.getSimpleVT().SimpleTy) {
5158 default: assert(false && "Unexpected!");
5159 case MVT::v4f32: NewVT = MVT::v2f64; break;
5160 case MVT::v4i32: NewVT = MVT::v2i64; break;
5161 case MVT::v8i16: NewVT = MVT::v4i32; break;
5162 case MVT::v16i8: NewVT = MVT::v4i32; break;
5165 int Scale = NumElems / NewWidth;
5166 SmallVector<int, 8> MaskVec;
5167 for (unsigned i = 0; i < NumElems; i += Scale) {
5169 for (int j = 0; j < Scale; ++j) {
5170 int EltIdx = SVOp->getMaskElt(i+j);
5174 StartIdx = EltIdx - (EltIdx % Scale);
5175 if (EltIdx != StartIdx + j)
5179 MaskVec.push_back(-1);
5181 MaskVec.push_back(StartIdx / Scale);
5184 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5185 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5186 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5189 /// getVZextMovL - Return a zero-extending vector move low node.
5191 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5192 SDValue SrcOp, SelectionDAG &DAG,
5193 const X86Subtarget *Subtarget, DebugLoc dl) {
5194 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5195 LoadSDNode *LD = NULL;
5196 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5197 LD = dyn_cast<LoadSDNode>(SrcOp);
5199 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5201 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5202 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5203 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5204 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5205 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5207 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5208 return DAG.getNode(ISD::BITCAST, dl, VT,
5209 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5210 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5218 return DAG.getNode(ISD::BITCAST, dl, VT,
5219 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5220 DAG.getNode(ISD::BITCAST, dl,
5224 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5227 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5228 SDValue V1 = SVOp->getOperand(0);
5229 SDValue V2 = SVOp->getOperand(1);
5230 DebugLoc dl = SVOp->getDebugLoc();
5231 EVT VT = SVOp->getValueType(0);
5233 SmallVector<std::pair<int, int>, 8> Locs;
5235 SmallVector<int, 8> Mask1(4U, -1);
5236 SmallVector<int, 8> PermMask;
5237 SVOp->getMask(PermMask);
5241 for (unsigned i = 0; i != 4; ++i) {
5242 int Idx = PermMask[i];
5244 Locs[i] = std::make_pair(-1, -1);
5246 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5248 Locs[i] = std::make_pair(0, NumLo);
5252 Locs[i] = std::make_pair(1, NumHi);
5254 Mask1[2+NumHi] = Idx;
5260 if (NumLo <= 2 && NumHi <= 2) {
5261 // If no more than two elements come from either vector. This can be
5262 // implemented with two shuffles. First shuffle gather the elements.
5263 // The second shuffle, which takes the first shuffle as both of its
5264 // vector operands, put the elements into the right order.
5265 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5267 SmallVector<int, 8> Mask2(4U, -1);
5269 for (unsigned i = 0; i != 4; ++i) {
5270 if (Locs[i].first == -1)
5273 unsigned Idx = (i < 2) ? 0 : 4;
5274 Idx += Locs[i].first * 2 + Locs[i].second;
5279 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5280 } else if (NumLo == 3 || NumHi == 3) {
5281 // Otherwise, we must have three elements from one vector, call it X, and
5282 // one element from the other, call it Y. First, use a shufps to build an
5283 // intermediate vector with the one element from Y and the element from X
5284 // that will be in the same half in the final destination (the indexes don't
5285 // matter). Then, use a shufps to build the final vector, taking the half
5286 // containing the element from Y from the intermediate, and the other half
5289 // Normalize it so the 3 elements come from V1.
5290 CommuteVectorShuffleMask(PermMask, VT);
5294 // Find the element from V2.
5296 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5297 int Val = PermMask[HiIndex];
5304 Mask1[0] = PermMask[HiIndex];
5306 Mask1[2] = PermMask[HiIndex^1];
5308 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5311 Mask1[0] = PermMask[0];
5312 Mask1[1] = PermMask[1];
5313 Mask1[2] = HiIndex & 1 ? 6 : 4;
5314 Mask1[3] = HiIndex & 1 ? 4 : 6;
5315 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5317 Mask1[0] = HiIndex & 1 ? 2 : 0;
5318 Mask1[1] = HiIndex & 1 ? 0 : 2;
5319 Mask1[2] = PermMask[2];
5320 Mask1[3] = PermMask[3];
5325 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5329 // Break it into (shuffle shuffle_hi, shuffle_lo).
5332 SmallVector<int,8> LoMask(4U, -1);
5333 SmallVector<int,8> HiMask(4U, -1);
5335 SmallVector<int,8> *MaskPtr = &LoMask;
5336 unsigned MaskIdx = 0;
5339 for (unsigned i = 0; i != 4; ++i) {
5346 int Idx = PermMask[i];
5348 Locs[i] = std::make_pair(-1, -1);
5349 } else if (Idx < 4) {
5350 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5351 (*MaskPtr)[LoIdx] = Idx;
5354 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5355 (*MaskPtr)[HiIdx] = Idx;
5360 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5361 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5362 SmallVector<int, 8> MaskOps;
5363 for (unsigned i = 0; i != 4; ++i) {
5364 if (Locs[i].first == -1) {
5365 MaskOps.push_back(-1);
5367 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5368 MaskOps.push_back(Idx);
5371 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5374 static bool MayFoldVectorLoad(SDValue V) {
5375 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5376 V = V.getOperand(0);
5377 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5378 V = V.getOperand(0);
5384 // FIXME: the version above should always be used. Since there's
5385 // a bug where several vector shuffles can't be folded because the
5386 // DAG is not updated during lowering and a node claims to have two
5387 // uses while it only has one, use this version, and let isel match
5388 // another instruction if the load really happens to have more than
5389 // one use. Remove this version after this bug get fixed.
5390 // rdar://8434668, PR8156
5391 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5392 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5393 V = V.getOperand(0);
5394 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5395 V = V.getOperand(0);
5396 if (ISD::isNormalLoad(V.getNode()))
5401 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5402 /// a vector extract, and if both can be later optimized into a single load.
5403 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5404 /// here because otherwise a target specific shuffle node is going to be
5405 /// emitted for this shuffle, and the optimization not done.
5406 /// FIXME: This is probably not the best approach, but fix the problem
5407 /// until the right path is decided.
5409 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5410 const TargetLowering &TLI) {
5411 EVT VT = V.getValueType();
5412 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5414 // Be sure that the vector shuffle is present in a pattern like this:
5415 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5419 SDNode *N = *V.getNode()->use_begin();
5420 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5423 SDValue EltNo = N->getOperand(1);
5424 if (!isa<ConstantSDNode>(EltNo))
5427 // If the bit convert changed the number of elements, it is unsafe
5428 // to examine the mask.
5429 bool HasShuffleIntoBitcast = false;
5430 if (V.getOpcode() == ISD::BITCAST) {
5431 EVT SrcVT = V.getOperand(0).getValueType();
5432 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5434 V = V.getOperand(0);
5435 HasShuffleIntoBitcast = true;
5438 // Select the input vector, guarding against out of range extract vector.
5439 unsigned NumElems = VT.getVectorNumElements();
5440 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5441 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5442 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5444 // Skip one more bit_convert if necessary
5445 if (V.getOpcode() == ISD::BITCAST)
5446 V = V.getOperand(0);
5448 if (ISD::isNormalLoad(V.getNode())) {
5449 // Is the original load suitable?
5450 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5452 // FIXME: avoid the multi-use bug that is preventing lots of
5453 // of foldings to be detected, this is still wrong of course, but
5454 // give the temporary desired behavior, and if it happens that
5455 // the load has real more uses, during isel it will not fold, and
5456 // will generate poor code.
5457 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5460 if (!HasShuffleIntoBitcast)
5463 // If there's a bitcast before the shuffle, check if the load type and
5464 // alignment is valid.
5465 unsigned Align = LN0->getAlignment();
5467 TLI.getTargetData()->getABITypeAlignment(
5468 VT.getTypeForEVT(*DAG.getContext()));
5470 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5478 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5479 EVT VT = Op.getValueType();
5481 // Canonizalize to v2f64.
5482 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5483 return DAG.getNode(ISD::BITCAST, dl, VT,
5484 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5489 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5491 SDValue V1 = Op.getOperand(0);
5492 SDValue V2 = Op.getOperand(1);
5493 EVT VT = Op.getValueType();
5495 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5497 if (HasSSE2 && VT == MVT::v2f64)
5498 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5501 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5505 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5506 SDValue V1 = Op.getOperand(0);
5507 SDValue V2 = Op.getOperand(1);
5508 EVT VT = Op.getValueType();
5510 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5511 "unsupported shuffle type");
5513 if (V2.getOpcode() == ISD::UNDEF)
5517 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5521 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5522 SDValue V1 = Op.getOperand(0);
5523 SDValue V2 = Op.getOperand(1);
5524 EVT VT = Op.getValueType();
5525 unsigned NumElems = VT.getVectorNumElements();
5527 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5528 // operand of these instructions is only memory, so check if there's a
5529 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5531 bool CanFoldLoad = false;
5533 // Trivial case, when V2 comes from a load.
5534 if (MayFoldVectorLoad(V2))
5537 // When V1 is a load, it can be folded later into a store in isel, example:
5538 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5540 // (MOVLPSmr addr:$src1, VR128:$src2)
5541 // So, recognize this potential and also use MOVLPS or MOVLPD
5542 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5545 // Both of them can't be memory operations though.
5546 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5547 CanFoldLoad = false;
5550 if (HasSSE2 && NumElems == 2)
5551 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5554 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5557 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5558 // movl and movlp will both match v2i64, but v2i64 is never matched by
5559 // movl earlier because we make it strict to avoid messing with the movlp load
5560 // folding logic (see the code above getMOVLP call). Match it here then,
5561 // this is horrible, but will stay like this until we move all shuffle
5562 // matching to x86 specific nodes. Note that for the 1st condition all
5563 // types are matched with movsd.
5564 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5565 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5567 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5570 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5572 // Invert the operand order and use SHUFPS to match it.
5573 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5574 X86::getShuffleSHUFImmediate(SVOp), DAG);
5577 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5578 switch(VT.getSimpleVT().SimpleTy) {
5579 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5580 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5582 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5584 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5585 case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5586 case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5587 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5588 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5590 llvm_unreachable("Unknown type for unpckl");
5595 static inline unsigned getUNPCKHOpcode(EVT VT) {
5596 switch(VT.getSimpleVT().SimpleTy) {
5597 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5598 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5599 case MVT::v4f32: return X86ISD::UNPCKHPS;
5600 case MVT::v2f64: return X86ISD::UNPCKHPD;
5601 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5602 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5604 llvm_unreachable("Unknown type for unpckh");
5610 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5611 const TargetLowering &TLI,
5612 const X86Subtarget *Subtarget) {
5613 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5614 EVT VT = Op.getValueType();
5615 DebugLoc dl = Op.getDebugLoc();
5616 SDValue V1 = Op.getOperand(0);
5617 SDValue V2 = Op.getOperand(1);
5619 if (isZeroShuffle(SVOp))
5620 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5622 // Handle splat operations
5623 if (SVOp->isSplat()) {
5624 // Special case, this is the only place now where it's
5625 // allowed to return a vector_shuffle operation without
5626 // using a target specific node, because *hopefully* it
5627 // will be optimized away by the dag combiner.
5628 if (VT.getVectorNumElements() <= 4 &&
5629 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5632 // Handle splats by matching through known masks
5633 if (VT.getVectorNumElements() <= 4)
5636 // Canonicalize all of the remaining to v4f32.
5637 return PromoteSplat(SVOp, DAG);
5640 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5642 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5643 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5644 if (NewOp.getNode())
5645 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5646 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5647 // FIXME: Figure out a cleaner way to do this.
5648 // Try to make use of movq to zero out the top part.
5649 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5650 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5651 if (NewOp.getNode()) {
5652 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5653 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5654 DAG, Subtarget, dl);
5656 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5657 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5658 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5659 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5660 DAG, Subtarget, dl);
5667 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5668 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5669 SDValue V1 = Op.getOperand(0);
5670 SDValue V2 = Op.getOperand(1);
5671 EVT VT = Op.getValueType();
5672 DebugLoc dl = Op.getDebugLoc();
5673 unsigned NumElems = VT.getVectorNumElements();
5674 bool isMMX = VT.getSizeInBits() == 64;
5675 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5676 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5677 bool V1IsSplat = false;
5678 bool V2IsSplat = false;
5679 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5680 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5681 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5682 MachineFunction &MF = DAG.getMachineFunction();
5683 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5685 // Shuffle operations on MMX not supported.
5689 // Vector shuffle lowering takes 3 steps:
5691 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5692 // narrowing and commutation of operands should be handled.
5693 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5695 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5696 // so the shuffle can be broken into other shuffles and the legalizer can
5697 // try the lowering again.
5699 // The general ideia is that no vector_shuffle operation should be left to
5700 // be matched during isel, all of them must be converted to a target specific
5703 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5704 // narrowing and commutation of operands should be handled. The actual code
5705 // doesn't include all of those, work in progress...
5706 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5707 if (NewOp.getNode())
5710 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5711 // unpckh_undef). Only use pshufd if speed is more important than size.
5712 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5713 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5714 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5715 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5716 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5717 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5719 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5720 RelaxedMayFoldVectorLoad(V1))
5721 return getMOVDDup(Op, dl, V1, DAG);
5723 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5724 return getMOVHighToLow(Op, dl, DAG);
5726 // Use to match splats
5727 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5728 (VT == MVT::v2f64 || VT == MVT::v2i64))
5729 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5731 if (X86::isPSHUFDMask(SVOp)) {
5732 // The actual implementation will match the mask in the if above and then
5733 // during isel it can match several different instructions, not only pshufd
5734 // as its name says, sad but true, emulate the behavior for now...
5735 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5736 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5738 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5740 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5741 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5743 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5744 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5747 if (VT == MVT::v4f32)
5748 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5752 // Check if this can be converted into a logical shift.
5753 bool isLeft = false;
5756 bool isShift = getSubtarget()->hasSSE2() &&
5757 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5758 if (isShift && ShVal.hasOneUse()) {
5759 // If the shifted value has multiple uses, it may be cheaper to use
5760 // v_set0 + movlhps or movhlps, etc.
5761 EVT EltVT = VT.getVectorElementType();
5762 ShAmt *= EltVT.getSizeInBits();
5763 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5766 if (X86::isMOVLMask(SVOp)) {
5769 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5770 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5771 if (!X86::isMOVLPMask(SVOp)) {
5772 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5773 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5775 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5776 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5780 // FIXME: fold these into legal mask.
5781 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5782 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5784 if (X86::isMOVHLPSMask(SVOp))
5785 return getMOVHighToLow(Op, dl, DAG);
5787 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5788 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5790 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5791 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5793 if (X86::isMOVLPMask(SVOp))
5794 return getMOVLP(Op, dl, DAG, HasSSE2);
5796 if (ShouldXformToMOVHLPS(SVOp) ||
5797 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5798 return CommuteVectorShuffle(SVOp, DAG);
5801 // No better options. Use a vshl / vsrl.
5802 EVT EltVT = VT.getVectorElementType();
5803 ShAmt *= EltVT.getSizeInBits();
5804 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5807 bool Commuted = false;
5808 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5809 // 1,1,1,1 -> v8i16 though.
5810 V1IsSplat = isSplatVector(V1.getNode());
5811 V2IsSplat = isSplatVector(V2.getNode());
5813 // Canonicalize the splat or undef, if present, to be on the RHS.
5814 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5815 Op = CommuteVectorShuffle(SVOp, DAG);
5816 SVOp = cast<ShuffleVectorSDNode>(Op);
5817 V1 = SVOp->getOperand(0);
5818 V2 = SVOp->getOperand(1);
5819 std::swap(V1IsSplat, V2IsSplat);
5820 std::swap(V1IsUndef, V2IsUndef);
5824 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5825 // Shuffling low element of v1 into undef, just return v1.
5828 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5829 // the instruction selector will not match, so get a canonical MOVL with
5830 // swapped operands to undo the commute.
5831 return getMOVL(DAG, dl, VT, V2, V1);
5834 if (X86::isUNPCKLMask(SVOp))
5835 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5836 dl, VT, V1, V2, DAG);
5838 if (X86::isUNPCKHMask(SVOp))
5839 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5842 // Normalize mask so all entries that point to V2 points to its first
5843 // element then try to match unpck{h|l} again. If match, return a
5844 // new vector_shuffle with the corrected mask.
5845 SDValue NewMask = NormalizeMask(SVOp, DAG);
5846 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5847 if (NSVOp != SVOp) {
5848 if (X86::isUNPCKLMask(NSVOp, true)) {
5850 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5857 // Commute is back and try unpck* again.
5858 // FIXME: this seems wrong.
5859 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5860 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5862 if (X86::isUNPCKLMask(NewSVOp))
5863 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5864 dl, VT, V2, V1, DAG);
5866 if (X86::isUNPCKHMask(NewSVOp))
5867 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5870 // Normalize the node to match x86 shuffle ops if needed
5871 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5872 return CommuteVectorShuffle(SVOp, DAG);
5874 // The checks below are all present in isShuffleMaskLegal, but they are
5875 // inlined here right now to enable us to directly emit target specific
5876 // nodes, and remove one by one until they don't return Op anymore.
5877 SmallVector<int, 16> M;
5880 if (isPALIGNRMask(M, VT, HasSSSE3))
5881 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5882 X86::getShufflePALIGNRImmediate(SVOp),
5885 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5886 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5887 if (VT == MVT::v2f64) {
5888 X86ISD::NodeType Opcode =
5889 getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5890 return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5892 if (VT == MVT::v2i64)
5893 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5896 if (isPSHUFHWMask(M, VT))
5897 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5898 X86::getShufflePSHUFHWImmediate(SVOp),
5901 if (isPSHUFLWMask(M, VT))
5902 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5903 X86::getShufflePSHUFLWImmediate(SVOp),
5906 if (isSHUFPMask(M, VT)) {
5907 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5908 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5909 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5911 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5912 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5916 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5917 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5918 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5919 dl, VT, V1, V1, DAG);
5920 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5921 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5922 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5924 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5925 if (VT == MVT::v8i16) {
5926 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5927 if (NewOp.getNode())
5931 if (VT == MVT::v16i8) {
5932 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5933 if (NewOp.getNode())
5937 // Handle all 4 wide cases with a number of shuffles.
5939 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5945 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5946 SelectionDAG &DAG) const {
5947 EVT VT = Op.getValueType();
5948 DebugLoc dl = Op.getDebugLoc();
5949 if (VT.getSizeInBits() == 8) {
5950 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5951 Op.getOperand(0), Op.getOperand(1));
5952 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5953 DAG.getValueType(VT));
5954 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5955 } else if (VT.getSizeInBits() == 16) {
5956 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5957 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5959 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5960 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5961 DAG.getNode(ISD::BITCAST, dl,
5965 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5966 Op.getOperand(0), Op.getOperand(1));
5967 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5968 DAG.getValueType(VT));
5969 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5970 } else if (VT == MVT::f32) {
5971 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5972 // the result back to FR32 register. It's only worth matching if the
5973 // result has a single use which is a store or a bitcast to i32. And in
5974 // the case of a store, it's not worth it if the index is a constant 0,
5975 // because a MOVSSmr can be used instead, which is smaller and faster.
5976 if (!Op.hasOneUse())
5978 SDNode *User = *Op.getNode()->use_begin();
5979 if ((User->getOpcode() != ISD::STORE ||
5980 (isa<ConstantSDNode>(Op.getOperand(1)) &&
5981 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5982 (User->getOpcode() != ISD::BITCAST ||
5983 User->getValueType(0) != MVT::i32))
5985 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5986 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5989 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5990 } else if (VT == MVT::i32) {
5991 // ExtractPS works with constant index.
5992 if (isa<ConstantSDNode>(Op.getOperand(1)))
6000 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6001 SelectionDAG &DAG) const {
6002 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6005 SDValue Vec = Op.getOperand(0);
6006 EVT VecVT = Vec.getValueType();
6008 // If this is a 256-bit vector result, first extract the 128-bit
6009 // vector and then extract from the 128-bit vector.
6010 if (VecVT.getSizeInBits() > 128) {
6011 DebugLoc dl = Op.getNode()->getDebugLoc();
6012 unsigned NumElems = VecVT.getVectorNumElements();
6013 SDValue Idx = Op.getOperand(1);
6015 if (!isa<ConstantSDNode>(Idx))
6018 unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6019 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6021 // Get the 128-bit vector.
6022 bool Upper = IdxVal >= ExtractNumElems;
6023 Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6026 SDValue ScaledIdx = Idx;
6028 ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6029 DAG.getConstant(ExtractNumElems,
6030 Idx.getValueType()));
6031 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6035 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6037 if (Subtarget->hasSSE41()) {
6038 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6043 EVT VT = Op.getValueType();
6044 DebugLoc dl = Op.getDebugLoc();
6045 // TODO: handle v16i8.
6046 if (VT.getSizeInBits() == 16) {
6047 SDValue Vec = Op.getOperand(0);
6048 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6050 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6051 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6052 DAG.getNode(ISD::BITCAST, dl,
6055 // Transform it so it match pextrw which produces a 32-bit result.
6056 EVT EltVT = MVT::i32;
6057 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6058 Op.getOperand(0), Op.getOperand(1));
6059 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6060 DAG.getValueType(VT));
6061 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6062 } else if (VT.getSizeInBits() == 32) {
6063 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6067 // SHUFPS the element to the lowest double word, then movss.
6068 int Mask[4] = { Idx, -1, -1, -1 };
6069 EVT VVT = Op.getOperand(0).getValueType();
6070 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6071 DAG.getUNDEF(VVT), Mask);
6072 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6073 DAG.getIntPtrConstant(0));
6074 } else if (VT.getSizeInBits() == 64) {
6075 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6076 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6077 // to match extract_elt for f64.
6078 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6082 // UNPCKHPD the element to the lowest double word, then movsd.
6083 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6084 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6085 int Mask[2] = { 1, -1 };
6086 EVT VVT = Op.getOperand(0).getValueType();
6087 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6088 DAG.getUNDEF(VVT), Mask);
6089 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6090 DAG.getIntPtrConstant(0));
6097 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6098 SelectionDAG &DAG) const {
6099 EVT VT = Op.getValueType();
6100 EVT EltVT = VT.getVectorElementType();
6101 DebugLoc dl = Op.getDebugLoc();
6103 SDValue N0 = Op.getOperand(0);
6104 SDValue N1 = Op.getOperand(1);
6105 SDValue N2 = Op.getOperand(2);
6107 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6108 isa<ConstantSDNode>(N2)) {
6110 if (VT == MVT::v8i16)
6111 Opc = X86ISD::PINSRW;
6112 else if (VT == MVT::v16i8)
6113 Opc = X86ISD::PINSRB;
6115 Opc = X86ISD::PINSRB;
6117 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6119 if (N1.getValueType() != MVT::i32)
6120 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6121 if (N2.getValueType() != MVT::i32)
6122 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6123 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6124 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6125 // Bits [7:6] of the constant are the source select. This will always be
6126 // zero here. The DAG Combiner may combine an extract_elt index into these
6127 // bits. For example (insert (extract, 3), 2) could be matched by putting
6128 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6129 // Bits [5:4] of the constant are the destination select. This is the
6130 // value of the incoming immediate.
6131 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6132 // combine either bitwise AND or insert of float 0.0 to set these bits.
6133 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6134 // Create this as a scalar to vector..
6135 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6136 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6137 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6138 // PINSR* works with constant index.
6145 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6146 EVT VT = Op.getValueType();
6147 EVT EltVT = VT.getVectorElementType();
6149 DebugLoc dl = Op.getDebugLoc();
6150 SDValue N0 = Op.getOperand(0);
6151 SDValue N1 = Op.getOperand(1);
6152 SDValue N2 = Op.getOperand(2);
6154 // If this is a 256-bit vector result, first insert into a 128-bit
6155 // vector and then insert into the 256-bit vector.
6156 if (VT.getSizeInBits() > 128) {
6157 if (!isa<ConstantSDNode>(N2))
6160 // Get the 128-bit vector.
6161 unsigned NumElems = VT.getVectorNumElements();
6162 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6163 bool Upper = IdxVal >= NumElems / 2;
6165 SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6168 SDValue ScaledN2 = N2;
6170 ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6171 DAG.getConstant(NumElems /
6172 (VT.getSizeInBits() / 128),
6173 N2.getValueType()));
6174 Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6177 // Insert the 128-bit vector
6178 // FIXME: Why UNDEF?
6179 return Insert128BitVector(N0, Op, N2, DAG, dl);
6182 if (Subtarget->hasSSE41())
6183 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6185 if (EltVT == MVT::i8)
6188 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6189 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6190 // as its second argument.
6191 if (N1.getValueType() != MVT::i32)
6192 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6193 if (N2.getValueType() != MVT::i32)
6194 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6195 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6201 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6202 LLVMContext *Context = DAG.getContext();
6203 DebugLoc dl = Op.getDebugLoc();
6204 EVT OpVT = Op.getValueType();
6206 // If this is a 256-bit vector result, first insert into a 128-bit
6207 // vector and then insert into the 256-bit vector.
6208 if (OpVT.getSizeInBits() > 128) {
6209 // Insert into a 128-bit vector.
6210 EVT VT128 = EVT::getVectorVT(*Context,
6211 OpVT.getVectorElementType(),
6212 OpVT.getVectorNumElements() / 2);
6214 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6216 // Insert the 128-bit vector.
6217 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6218 DAG.getConstant(0, MVT::i32),
6222 if (Op.getValueType() == MVT::v1i64 &&
6223 Op.getOperand(0).getValueType() == MVT::i64)
6224 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6226 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6227 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6228 "Expected an SSE type!");
6229 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6230 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6233 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
6234 // a simple subregister reference or explicit instructions to grab
6235 // upper bits of a vector.
6237 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6238 if (Subtarget->hasAVX()) {
6239 DebugLoc dl = Op.getNode()->getDebugLoc();
6240 SDValue Vec = Op.getNode()->getOperand(0);
6241 SDValue Idx = Op.getNode()->getOperand(1);
6243 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6244 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6245 return Extract128BitVector(Vec, Idx, DAG, dl);
6251 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
6252 // simple superregister reference or explicit instructions to insert
6253 // the upper bits of a vector.
6255 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6256 if (Subtarget->hasAVX()) {
6257 DebugLoc dl = Op.getNode()->getDebugLoc();
6258 SDValue Vec = Op.getNode()->getOperand(0);
6259 SDValue SubVec = Op.getNode()->getOperand(1);
6260 SDValue Idx = Op.getNode()->getOperand(2);
6262 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6263 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6264 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6270 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6271 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6272 // one of the above mentioned nodes. It has to be wrapped because otherwise
6273 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6274 // be used to form addressing mode. These wrapped nodes will be selected
6277 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6278 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6280 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6282 unsigned char OpFlag = 0;
6283 unsigned WrapperKind = X86ISD::Wrapper;
6284 CodeModel::Model M = getTargetMachine().getCodeModel();
6286 if (Subtarget->isPICStyleRIPRel() &&
6287 (M == CodeModel::Small || M == CodeModel::Kernel))
6288 WrapperKind = X86ISD::WrapperRIP;
6289 else if (Subtarget->isPICStyleGOT())
6290 OpFlag = X86II::MO_GOTOFF;
6291 else if (Subtarget->isPICStyleStubPIC())
6292 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6294 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6296 CP->getOffset(), OpFlag);
6297 DebugLoc DL = CP->getDebugLoc();
6298 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6299 // With PIC, the address is actually $g + Offset.
6301 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6302 DAG.getNode(X86ISD::GlobalBaseReg,
6303 DebugLoc(), getPointerTy()),
6310 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6311 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6313 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6315 unsigned char OpFlag = 0;
6316 unsigned WrapperKind = X86ISD::Wrapper;
6317 CodeModel::Model M = getTargetMachine().getCodeModel();
6319 if (Subtarget->isPICStyleRIPRel() &&
6320 (M == CodeModel::Small || M == CodeModel::Kernel))
6321 WrapperKind = X86ISD::WrapperRIP;
6322 else if (Subtarget->isPICStyleGOT())
6323 OpFlag = X86II::MO_GOTOFF;
6324 else if (Subtarget->isPICStyleStubPIC())
6325 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6327 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6329 DebugLoc DL = JT->getDebugLoc();
6330 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6332 // With PIC, the address is actually $g + Offset.
6334 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6335 DAG.getNode(X86ISD::GlobalBaseReg,
6336 DebugLoc(), getPointerTy()),
6343 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6344 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6346 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6348 unsigned char OpFlag = 0;
6349 unsigned WrapperKind = X86ISD::Wrapper;
6350 CodeModel::Model M = getTargetMachine().getCodeModel();
6352 if (Subtarget->isPICStyleRIPRel() &&
6353 (M == CodeModel::Small || M == CodeModel::Kernel))
6354 WrapperKind = X86ISD::WrapperRIP;
6355 else if (Subtarget->isPICStyleGOT())
6356 OpFlag = X86II::MO_GOTOFF;
6357 else if (Subtarget->isPICStyleStubPIC())
6358 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6360 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6362 DebugLoc DL = Op.getDebugLoc();
6363 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6366 // With PIC, the address is actually $g + Offset.
6367 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6368 !Subtarget->is64Bit()) {
6369 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6370 DAG.getNode(X86ISD::GlobalBaseReg,
6371 DebugLoc(), getPointerTy()),
6379 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6380 // Create the TargetBlockAddressAddress node.
6381 unsigned char OpFlags =
6382 Subtarget->ClassifyBlockAddressReference();
6383 CodeModel::Model M = getTargetMachine().getCodeModel();
6384 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6385 DebugLoc dl = Op.getDebugLoc();
6386 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6387 /*isTarget=*/true, OpFlags);
6389 if (Subtarget->isPICStyleRIPRel() &&
6390 (M == CodeModel::Small || M == CodeModel::Kernel))
6391 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6393 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6395 // With PIC, the address is actually $g + Offset.
6396 if (isGlobalRelativeToPICBase(OpFlags)) {
6397 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6398 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6406 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6408 SelectionDAG &DAG) const {
6409 // Create the TargetGlobalAddress node, folding in the constant
6410 // offset if it is legal.
6411 unsigned char OpFlags =
6412 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6413 CodeModel::Model M = getTargetMachine().getCodeModel();
6415 if (OpFlags == X86II::MO_NO_FLAG &&
6416 X86::isOffsetSuitableForCodeModel(Offset, M)) {
6417 // A direct static reference to a global.
6418 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6421 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6424 if (Subtarget->isPICStyleRIPRel() &&
6425 (M == CodeModel::Small || M == CodeModel::Kernel))
6426 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6428 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6430 // With PIC, the address is actually $g + Offset.
6431 if (isGlobalRelativeToPICBase(OpFlags)) {
6432 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6433 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6437 // For globals that require a load from a stub to get the address, emit the
6439 if (isGlobalStubReference(OpFlags))
6440 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6441 MachinePointerInfo::getGOT(), false, false, 0);
6443 // If there was a non-zero offset that we didn't fold, create an explicit
6446 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6447 DAG.getConstant(Offset, getPointerTy()));
6453 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6454 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6455 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6456 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6460 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6461 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6462 unsigned char OperandFlags) {
6463 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6464 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6465 DebugLoc dl = GA->getDebugLoc();
6466 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6467 GA->getValueType(0),
6471 SDValue Ops[] = { Chain, TGA, *InFlag };
6472 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6474 SDValue Ops[] = { Chain, TGA };
6475 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6478 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6479 MFI->setAdjustsStack(true);
6481 SDValue Flag = Chain.getValue(1);
6482 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6485 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6487 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6490 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6491 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6492 DAG.getNode(X86ISD::GlobalBaseReg,
6493 DebugLoc(), PtrVT), InFlag);
6494 InFlag = Chain.getValue(1);
6496 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6499 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6501 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6503 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6504 X86::RAX, X86II::MO_TLSGD);
6507 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6508 // "local exec" model.
6509 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6510 const EVT PtrVT, TLSModel::Model model,
6512 DebugLoc dl = GA->getDebugLoc();
6514 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6515 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6516 is64Bit ? 257 : 256));
6518 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6519 DAG.getIntPtrConstant(0),
6520 MachinePointerInfo(Ptr), false, false, 0);
6522 unsigned char OperandFlags = 0;
6523 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6525 unsigned WrapperKind = X86ISD::Wrapper;
6526 if (model == TLSModel::LocalExec) {
6527 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6528 } else if (is64Bit) {
6529 assert(model == TLSModel::InitialExec);
6530 OperandFlags = X86II::MO_GOTTPOFF;
6531 WrapperKind = X86ISD::WrapperRIP;
6533 assert(model == TLSModel::InitialExec);
6534 OperandFlags = X86II::MO_INDNTPOFF;
6537 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6539 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6540 GA->getValueType(0),
6541 GA->getOffset(), OperandFlags);
6542 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6544 if (model == TLSModel::InitialExec)
6545 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6546 MachinePointerInfo::getGOT(), false, false, 0);
6548 // The address of the thread local variable is the add of the thread
6549 // pointer with the offset of the variable.
6550 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6554 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6556 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6557 const GlobalValue *GV = GA->getGlobal();
6559 if (Subtarget->isTargetELF()) {
6560 // TODO: implement the "local dynamic" model
6561 // TODO: implement the "initial exec"model for pic executables
6563 // If GV is an alias then use the aliasee for determining
6564 // thread-localness.
6565 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6566 GV = GA->resolveAliasedGlobal(false);
6568 TLSModel::Model model
6569 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6572 case TLSModel::GeneralDynamic:
6573 case TLSModel::LocalDynamic: // not implemented
6574 if (Subtarget->is64Bit())
6575 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6576 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6578 case TLSModel::InitialExec:
6579 case TLSModel::LocalExec:
6580 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6581 Subtarget->is64Bit());
6583 } else if (Subtarget->isTargetDarwin()) {
6584 // Darwin only has one model of TLS. Lower to that.
6585 unsigned char OpFlag = 0;
6586 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6587 X86ISD::WrapperRIP : X86ISD::Wrapper;
6589 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6591 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6592 !Subtarget->is64Bit();
6594 OpFlag = X86II::MO_TLVP_PIC_BASE;
6596 OpFlag = X86II::MO_TLVP;
6597 DebugLoc DL = Op.getDebugLoc();
6598 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6599 GA->getValueType(0),
6600 GA->getOffset(), OpFlag);
6601 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6603 // With PIC32, the address is actually $g + Offset.
6605 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6606 DAG.getNode(X86ISD::GlobalBaseReg,
6607 DebugLoc(), getPointerTy()),
6610 // Lowering the machine isd will make sure everything is in the right
6612 SDValue Chain = DAG.getEntryNode();
6613 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6614 SDValue Args[] = { Chain, Offset };
6615 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6617 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6618 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6619 MFI->setAdjustsStack(true);
6621 // And our return value (tls address) is in the standard call return value
6623 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6624 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6628 "TLS not implemented for this target.");
6630 llvm_unreachable("Unreachable");
6635 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6636 /// take a 2 x i32 value to shift plus a shift amount.
6637 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6638 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6639 EVT VT = Op.getValueType();
6640 unsigned VTBits = VT.getSizeInBits();
6641 DebugLoc dl = Op.getDebugLoc();
6642 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6643 SDValue ShOpLo = Op.getOperand(0);
6644 SDValue ShOpHi = Op.getOperand(1);
6645 SDValue ShAmt = Op.getOperand(2);
6646 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6647 DAG.getConstant(VTBits - 1, MVT::i8))
6648 : DAG.getConstant(0, VT);
6651 if (Op.getOpcode() == ISD::SHL_PARTS) {
6652 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6653 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6655 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6656 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6659 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6660 DAG.getConstant(VTBits, MVT::i8));
6661 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6662 AndNode, DAG.getConstant(0, MVT::i8));
6665 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6666 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6667 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6669 if (Op.getOpcode() == ISD::SHL_PARTS) {
6670 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6671 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6673 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6674 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6677 SDValue Ops[2] = { Lo, Hi };
6678 return DAG.getMergeValues(Ops, 2, dl);
6681 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6682 SelectionDAG &DAG) const {
6683 EVT SrcVT = Op.getOperand(0).getValueType();
6685 if (SrcVT.isVector())
6688 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6689 "Unknown SINT_TO_FP to lower!");
6691 // These are really Legal; return the operand so the caller accepts it as
6693 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6695 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6696 Subtarget->is64Bit()) {
6700 DebugLoc dl = Op.getDebugLoc();
6701 unsigned Size = SrcVT.getSizeInBits()/8;
6702 MachineFunction &MF = DAG.getMachineFunction();
6704 SDValue Addr = Op.getOperand(0);
6705 if (Addr.getOpcode() == ISD::LOAD)
6706 return BuildFILD(Op, SrcVT, DAG.getEntryNode(), Addr, DAG);
6708 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6709 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6710 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6712 MachinePointerInfo::getFixedStack(SSFI),
6714 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6717 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6719 SelectionDAG &DAG) const {
6721 DebugLoc DL = Op.getDebugLoc();
6723 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6725 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6727 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6729 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6731 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
6732 MachineMemOperand *MMO;
6734 int SSFI = FI->getIndex();
6736 DAG.getMachineFunction()
6737 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6738 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6740 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
6741 StackSlot = StackSlot.getOperand(1);
6743 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6744 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6746 Tys, Ops, array_lengthof(Ops),
6750 Chain = Result.getValue(1);
6751 SDValue InFlag = Result.getValue(2);
6753 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6754 // shouldn't be necessary except that RFP cannot be live across
6755 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6756 MachineFunction &MF = DAG.getMachineFunction();
6757 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6758 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6759 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6760 Tys = DAG.getVTList(MVT::Other);
6762 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6764 MachineMemOperand *MMO =
6765 DAG.getMachineFunction()
6766 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6767 MachineMemOperand::MOStore, SSFISize, SSFISize);
6769 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6770 Ops, array_lengthof(Ops),
6771 Op.getValueType(), MMO);
6772 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6773 MachinePointerInfo::getFixedStack(SSFI),
6780 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6781 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6782 SelectionDAG &DAG) const {
6783 // This algorithm is not obvious. Here it is in C code, more or less:
6785 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6786 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6787 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6789 // Copy ints to xmm registers.
6790 __m128i xh = _mm_cvtsi32_si128( hi );
6791 __m128i xl = _mm_cvtsi32_si128( lo );
6793 // Combine into low half of a single xmm register.
6794 __m128i x = _mm_unpacklo_epi32( xh, xl );
6798 // Merge in appropriate exponents to give the integer bits the right
6800 x = _mm_unpacklo_epi32( x, exp );
6802 // Subtract away the biases to deal with the IEEE-754 double precision
6804 d = _mm_sub_pd( (__m128d) x, bias );
6806 // All conversions up to here are exact. The correctly rounded result is
6807 // calculated using the current rounding mode using the following
6809 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6810 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6811 // store doesn't really need to be here (except
6812 // maybe to zero the other double)
6817 DebugLoc dl = Op.getDebugLoc();
6818 LLVMContext *Context = DAG.getContext();
6820 // Build some magic constants.
6821 std::vector<Constant*> CV0;
6822 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6823 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6824 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6825 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6826 Constant *C0 = ConstantVector::get(CV0);
6827 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6829 std::vector<Constant*> CV1;
6831 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6833 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6834 Constant *C1 = ConstantVector::get(CV1);
6835 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6837 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6838 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6840 DAG.getIntPtrConstant(1)));
6841 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6842 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6844 DAG.getIntPtrConstant(0)));
6845 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6846 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6847 MachinePointerInfo::getConstantPool(),
6849 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6850 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6851 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6852 MachinePointerInfo::getConstantPool(),
6854 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6856 // Add the halves; easiest way is to swap them into another reg first.
6857 int ShufMask[2] = { 1, -1 };
6858 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6859 DAG.getUNDEF(MVT::v2f64), ShufMask);
6860 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6861 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6862 DAG.getIntPtrConstant(0));
6865 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6866 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6867 SelectionDAG &DAG) const {
6868 DebugLoc dl = Op.getDebugLoc();
6869 // FP constant to bias correct the final result.
6870 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6873 // Load the 32-bit value into an XMM register.
6874 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6875 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6877 DAG.getIntPtrConstant(0)));
6879 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6880 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6881 DAG.getIntPtrConstant(0));
6883 // Or the load with the bias.
6884 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6885 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6886 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6888 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6889 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6890 MVT::v2f64, Bias)));
6891 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6892 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6893 DAG.getIntPtrConstant(0));
6895 // Subtract the bias.
6896 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6898 // Handle final rounding.
6899 EVT DestVT = Op.getValueType();
6901 if (DestVT.bitsLT(MVT::f64)) {
6902 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6903 DAG.getIntPtrConstant(0));
6904 } else if (DestVT.bitsGT(MVT::f64)) {
6905 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6908 // Handle final rounding.
6912 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6913 SelectionDAG &DAG) const {
6914 SDValue N0 = Op.getOperand(0);
6915 DebugLoc dl = Op.getDebugLoc();
6917 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6918 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6919 // the optimization here.
6920 if (DAG.SignBitIsZero(N0))
6921 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6923 EVT SrcVT = N0.getValueType();
6924 EVT DstVT = Op.getValueType();
6925 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6926 return LowerUINT_TO_FP_i64(Op, DAG);
6927 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6928 return LowerUINT_TO_FP_i32(Op, DAG);
6930 // Make a 64-bit buffer, and use it to build an FILD.
6931 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6932 if (SrcVT == MVT::i32) {
6933 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6934 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6935 getPointerTy(), StackSlot, WordOff);
6936 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6937 StackSlot, MachinePointerInfo(),
6939 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6940 OffsetSlot, MachinePointerInfo(),
6942 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6946 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6947 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6948 StackSlot, MachinePointerInfo(),
6950 // For i64 source, we need to add the appropriate power of 2 if the input
6951 // was negative. This is the same as the optimization in
6952 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6953 // we must be careful to do the computation in x87 extended precision, not
6954 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6955 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6956 MachineMemOperand *MMO =
6957 DAG.getMachineFunction()
6958 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6959 MachineMemOperand::MOLoad, 8, 8);
6961 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6962 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6963 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6966 APInt FF(32, 0x5F800000ULL);
6968 // Check whether the sign bit is set.
6969 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6970 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6973 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6974 SDValue FudgePtr = DAG.getConstantPool(
6975 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6978 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6979 SDValue Zero = DAG.getIntPtrConstant(0);
6980 SDValue Four = DAG.getIntPtrConstant(4);
6981 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6983 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6985 // Load the value out, extending it from f32 to f80.
6986 // FIXME: Avoid the extend by constructing the right constant pool?
6987 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
6988 FudgePtr, MachinePointerInfo::getConstantPool(),
6989 MVT::f32, false, false, 4);
6990 // Extend everything to 80 bits to force it to be done on x87.
6991 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6992 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6995 std::pair<SDValue,SDValue> X86TargetLowering::
6996 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6997 DebugLoc DL = Op.getDebugLoc();
6999 EVT DstTy = Op.getValueType();
7002 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7006 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7007 DstTy.getSimpleVT() >= MVT::i16 &&
7008 "Unknown FP_TO_SINT to lower!");
7010 // These are really Legal.
7011 if (DstTy == MVT::i32 &&
7012 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7013 return std::make_pair(SDValue(), SDValue());
7014 if (Subtarget->is64Bit() &&
7015 DstTy == MVT::i64 &&
7016 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7017 return std::make_pair(SDValue(), SDValue());
7019 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7021 MachineFunction &MF = DAG.getMachineFunction();
7022 unsigned MemSize = DstTy.getSizeInBits()/8;
7023 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7024 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7029 switch (DstTy.getSimpleVT().SimpleTy) {
7030 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7031 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7032 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7033 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7036 SDValue Chain = DAG.getEntryNode();
7037 SDValue Value = Op.getOperand(0);
7038 EVT TheVT = Op.getOperand(0).getValueType();
7039 if (isScalarFPTypeInSSEReg(TheVT)) {
7040 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7041 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7042 MachinePointerInfo::getFixedStack(SSFI),
7044 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7046 Chain, StackSlot, DAG.getValueType(TheVT)
7049 MachineMemOperand *MMO =
7050 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7051 MachineMemOperand::MOLoad, MemSize, MemSize);
7052 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7054 Chain = Value.getValue(1);
7055 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7056 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7059 MachineMemOperand *MMO =
7060 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7061 MachineMemOperand::MOStore, MemSize, MemSize);
7063 // Build the FP_TO_INT*_IN_MEM
7064 SDValue Ops[] = { Chain, Value, StackSlot };
7065 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7066 Ops, 3, DstTy, MMO);
7068 return std::make_pair(FIST, StackSlot);
7071 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7072 SelectionDAG &DAG) const {
7073 if (Op.getValueType().isVector())
7076 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7077 SDValue FIST = Vals.first, StackSlot = Vals.second;
7078 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7079 if (FIST.getNode() == 0) return Op;
7082 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7083 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7086 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7087 SelectionDAG &DAG) const {
7088 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7089 SDValue FIST = Vals.first, StackSlot = Vals.second;
7090 assert(FIST.getNode() && "Unexpected failure");
7093 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7094 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7097 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7098 SelectionDAG &DAG) const {
7099 LLVMContext *Context = DAG.getContext();
7100 DebugLoc dl = Op.getDebugLoc();
7101 EVT VT = Op.getValueType();
7104 EltVT = VT.getVectorElementType();
7105 std::vector<Constant*> CV;
7106 if (EltVT == MVT::f64) {
7107 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7111 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7117 Constant *C = ConstantVector::get(CV);
7118 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7119 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7120 MachinePointerInfo::getConstantPool(),
7122 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7125 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7126 LLVMContext *Context = DAG.getContext();
7127 DebugLoc dl = Op.getDebugLoc();
7128 EVT VT = Op.getValueType();
7131 EltVT = VT.getVectorElementType();
7132 std::vector<Constant*> CV;
7133 if (EltVT == MVT::f64) {
7134 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7138 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7144 Constant *C = ConstantVector::get(CV);
7145 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7146 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7147 MachinePointerInfo::getConstantPool(),
7149 if (VT.isVector()) {
7150 return DAG.getNode(ISD::BITCAST, dl, VT,
7151 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7152 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7154 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7156 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7160 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7161 LLVMContext *Context = DAG.getContext();
7162 SDValue Op0 = Op.getOperand(0);
7163 SDValue Op1 = Op.getOperand(1);
7164 DebugLoc dl = Op.getDebugLoc();
7165 EVT VT = Op.getValueType();
7166 EVT SrcVT = Op1.getValueType();
7168 // If second operand is smaller, extend it first.
7169 if (SrcVT.bitsLT(VT)) {
7170 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7173 // And if it is bigger, shrink it first.
7174 if (SrcVT.bitsGT(VT)) {
7175 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7179 // At this point the operands and the result should have the same
7180 // type, and that won't be f80 since that is not custom lowered.
7182 // First get the sign bit of second operand.
7183 std::vector<Constant*> CV;
7184 if (SrcVT == MVT::f64) {
7185 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7186 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7188 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7189 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7190 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7191 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7193 Constant *C = ConstantVector::get(CV);
7194 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7195 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7196 MachinePointerInfo::getConstantPool(),
7198 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7200 // Shift sign bit right or left if the two operands have different types.
7201 if (SrcVT.bitsGT(VT)) {
7202 // Op0 is MVT::f32, Op1 is MVT::f64.
7203 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7204 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7205 DAG.getConstant(32, MVT::i32));
7206 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7207 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7208 DAG.getIntPtrConstant(0));
7211 // Clear first operand sign bit.
7213 if (VT == MVT::f64) {
7214 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7215 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7217 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7218 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7219 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7220 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7222 C = ConstantVector::get(CV);
7223 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7224 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7225 MachinePointerInfo::getConstantPool(),
7227 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7229 // Or the value with the sign bit.
7230 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7233 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7234 SDValue N0 = Op.getOperand(0);
7235 DebugLoc dl = Op.getDebugLoc();
7236 EVT VT = Op.getValueType();
7238 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7239 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7240 DAG.getConstant(1, VT));
7241 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7244 /// Emit nodes that will be selected as "test Op0,Op0", or something
7246 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7247 SelectionDAG &DAG) const {
7248 DebugLoc dl = Op.getDebugLoc();
7250 // CF and OF aren't always set the way we want. Determine which
7251 // of these we need.
7252 bool NeedCF = false;
7253 bool NeedOF = false;
7256 case X86::COND_A: case X86::COND_AE:
7257 case X86::COND_B: case X86::COND_BE:
7260 case X86::COND_G: case X86::COND_GE:
7261 case X86::COND_L: case X86::COND_LE:
7262 case X86::COND_O: case X86::COND_NO:
7267 // See if we can use the EFLAGS value from the operand instead of
7268 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7269 // we prove that the arithmetic won't overflow, we can't use OF or CF.
7270 if (Op.getResNo() != 0 || NeedOF || NeedCF)
7271 // Emit a CMP with 0, which is the TEST pattern.
7272 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7273 DAG.getConstant(0, Op.getValueType()));
7275 unsigned Opcode = 0;
7276 unsigned NumOperands = 0;
7277 switch (Op.getNode()->getOpcode()) {
7279 // Due to an isel shortcoming, be conservative if this add is likely to be
7280 // selected as part of a load-modify-store instruction. When the root node
7281 // in a match is a store, isel doesn't know how to remap non-chain non-flag
7282 // uses of other nodes in the match, such as the ADD in this case. This
7283 // leads to the ADD being left around and reselected, with the result being
7284 // two adds in the output. Alas, even if none our users are stores, that
7285 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
7286 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
7287 // climbing the DAG back to the root, and it doesn't seem to be worth the
7289 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7290 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7291 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7294 if (ConstantSDNode *C =
7295 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7296 // An add of one will be selected as an INC.
7297 if (C->getAPIntValue() == 1) {
7298 Opcode = X86ISD::INC;
7303 // An add of negative one (subtract of one) will be selected as a DEC.
7304 if (C->getAPIntValue().isAllOnesValue()) {
7305 Opcode = X86ISD::DEC;
7311 // Otherwise use a regular EFLAGS-setting add.
7312 Opcode = X86ISD::ADD;
7316 // If the primary and result isn't used, don't bother using X86ISD::AND,
7317 // because a TEST instruction will be better.
7318 bool NonFlagUse = false;
7319 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7320 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7322 unsigned UOpNo = UI.getOperandNo();
7323 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7324 // Look pass truncate.
7325 UOpNo = User->use_begin().getOperandNo();
7326 User = *User->use_begin();
7329 if (User->getOpcode() != ISD::BRCOND &&
7330 User->getOpcode() != ISD::SETCC &&
7331 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7344 // Due to the ISEL shortcoming noted above, be conservative if this op is
7345 // likely to be selected as part of a load-modify-store instruction.
7346 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7347 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7348 if (UI->getOpcode() == ISD::STORE)
7351 // Otherwise use a regular EFLAGS-setting instruction.
7352 switch (Op.getNode()->getOpcode()) {
7353 default: llvm_unreachable("unexpected operator!");
7354 case ISD::SUB: Opcode = X86ISD::SUB; break;
7355 case ISD::OR: Opcode = X86ISD::OR; break;
7356 case ISD::XOR: Opcode = X86ISD::XOR; break;
7357 case ISD::AND: Opcode = X86ISD::AND; break;
7369 return SDValue(Op.getNode(), 1);
7376 // Emit a CMP with 0, which is the TEST pattern.
7377 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7378 DAG.getConstant(0, Op.getValueType()));
7380 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7381 SmallVector<SDValue, 4> Ops;
7382 for (unsigned i = 0; i != NumOperands; ++i)
7383 Ops.push_back(Op.getOperand(i));
7385 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7386 DAG.ReplaceAllUsesWith(Op, New);
7387 return SDValue(New.getNode(), 1);
7390 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7392 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7393 SelectionDAG &DAG) const {
7394 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7395 if (C->getAPIntValue() == 0)
7396 return EmitTest(Op0, X86CC, DAG);
7398 DebugLoc dl = Op0.getDebugLoc();
7399 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7402 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7403 /// if it's possible.
7404 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7405 DebugLoc dl, SelectionDAG &DAG) const {
7406 SDValue Op0 = And.getOperand(0);
7407 SDValue Op1 = And.getOperand(1);
7408 if (Op0.getOpcode() == ISD::TRUNCATE)
7409 Op0 = Op0.getOperand(0);
7410 if (Op1.getOpcode() == ISD::TRUNCATE)
7411 Op1 = Op1.getOperand(0);
7414 if (Op1.getOpcode() == ISD::SHL)
7415 std::swap(Op0, Op1);
7416 if (Op0.getOpcode() == ISD::SHL) {
7417 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7418 if (And00C->getZExtValue() == 1) {
7419 // If we looked past a truncate, check that it's only truncating away
7421 unsigned BitWidth = Op0.getValueSizeInBits();
7422 unsigned AndBitWidth = And.getValueSizeInBits();
7423 if (BitWidth > AndBitWidth) {
7424 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7425 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7426 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7430 RHS = Op0.getOperand(1);
7432 } else if (Op1.getOpcode() == ISD::Constant) {
7433 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7434 SDValue AndLHS = Op0;
7435 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7436 LHS = AndLHS.getOperand(0);
7437 RHS = AndLHS.getOperand(1);
7441 if (LHS.getNode()) {
7442 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
7443 // instruction. Since the shift amount is in-range-or-undefined, we know
7444 // that doing a bittest on the i32 value is ok. We extend to i32 because
7445 // the encoding for the i16 version is larger than the i32 version.
7446 // Also promote i16 to i32 for performance / code size reason.
7447 if (LHS.getValueType() == MVT::i8 ||
7448 LHS.getValueType() == MVT::i16)
7449 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7451 // If the operand types disagree, extend the shift amount to match. Since
7452 // BT ignores high bits (like shifts) we can use anyextend.
7453 if (LHS.getValueType() != RHS.getValueType())
7454 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7456 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7457 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7458 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7459 DAG.getConstant(Cond, MVT::i8), BT);
7465 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7466 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7467 SDValue Op0 = Op.getOperand(0);
7468 SDValue Op1 = Op.getOperand(1);
7469 DebugLoc dl = Op.getDebugLoc();
7470 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7472 // Optimize to BT if possible.
7473 // Lower (X & (1 << N)) == 0 to BT(X, N).
7474 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7475 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7476 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7477 Op1.getOpcode() == ISD::Constant &&
7478 cast<ConstantSDNode>(Op1)->isNullValue() &&
7479 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7480 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7481 if (NewSetCC.getNode())
7485 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
7487 if (Op1.getOpcode() == ISD::Constant &&
7488 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7489 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7490 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7492 // If the input is a setcc, then reuse the input setcc or use a new one with
7493 // the inverted condition.
7494 if (Op0.getOpcode() == X86ISD::SETCC) {
7495 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7496 bool Invert = (CC == ISD::SETNE) ^
7497 cast<ConstantSDNode>(Op1)->isNullValue();
7498 if (!Invert) return Op0;
7500 CCode = X86::GetOppositeBranchCondition(CCode);
7501 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7502 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7506 bool isFP = Op1.getValueType().isFloatingPoint();
7507 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7508 if (X86CC == X86::COND_INVALID)
7511 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7512 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7513 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7516 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7518 SDValue Op0 = Op.getOperand(0);
7519 SDValue Op1 = Op.getOperand(1);
7520 SDValue CC = Op.getOperand(2);
7521 EVT VT = Op.getValueType();
7522 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7523 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7524 DebugLoc dl = Op.getDebugLoc();
7528 EVT VT0 = Op0.getValueType();
7529 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7530 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7533 switch (SetCCOpcode) {
7536 case ISD::SETEQ: SSECC = 0; break;
7538 case ISD::SETGT: Swap = true; // Fallthrough
7540 case ISD::SETOLT: SSECC = 1; break;
7542 case ISD::SETGE: Swap = true; // Fallthrough
7544 case ISD::SETOLE: SSECC = 2; break;
7545 case ISD::SETUO: SSECC = 3; break;
7547 case ISD::SETNE: SSECC = 4; break;
7548 case ISD::SETULE: Swap = true;
7549 case ISD::SETUGE: SSECC = 5; break;
7550 case ISD::SETULT: Swap = true;
7551 case ISD::SETUGT: SSECC = 6; break;
7552 case ISD::SETO: SSECC = 7; break;
7555 std::swap(Op0, Op1);
7557 // In the two special cases we can't handle, emit two comparisons.
7559 if (SetCCOpcode == ISD::SETUEQ) {
7561 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7562 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7563 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7565 else if (SetCCOpcode == ISD::SETONE) {
7567 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7568 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7569 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7571 llvm_unreachable("Illegal FP comparison");
7573 // Handle all other FP comparisons here.
7574 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7577 // We are handling one of the integer comparisons here. Since SSE only has
7578 // GT and EQ comparisons for integer, swapping operands and multiple
7579 // operations may be required for some comparisons.
7580 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7581 bool Swap = false, Invert = false, FlipSigns = false;
7583 switch (VT.getSimpleVT().SimpleTy) {
7585 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7586 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7587 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7588 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7591 switch (SetCCOpcode) {
7593 case ISD::SETNE: Invert = true;
7594 case ISD::SETEQ: Opc = EQOpc; break;
7595 case ISD::SETLT: Swap = true;
7596 case ISD::SETGT: Opc = GTOpc; break;
7597 case ISD::SETGE: Swap = true;
7598 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7599 case ISD::SETULT: Swap = true;
7600 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7601 case ISD::SETUGE: Swap = true;
7602 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7605 std::swap(Op0, Op1);
7607 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7608 // bits of the inputs before performing those operations.
7610 EVT EltVT = VT.getVectorElementType();
7611 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7613 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7614 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7616 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7617 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7620 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7622 // If the logical-not of the result is required, perform that now.
7624 Result = DAG.getNOT(dl, Result, VT);
7629 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7630 static bool isX86LogicalCmp(SDValue Op) {
7631 unsigned Opc = Op.getNode()->getOpcode();
7632 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7634 if (Op.getResNo() == 1 &&
7635 (Opc == X86ISD::ADD ||
7636 Opc == X86ISD::SUB ||
7637 Opc == X86ISD::ADC ||
7638 Opc == X86ISD::SBB ||
7639 Opc == X86ISD::SMUL ||
7640 Opc == X86ISD::UMUL ||
7641 Opc == X86ISD::INC ||
7642 Opc == X86ISD::DEC ||
7643 Opc == X86ISD::OR ||
7644 Opc == X86ISD::XOR ||
7645 Opc == X86ISD::AND))
7648 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7654 static bool isZero(SDValue V) {
7655 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7656 return C && C->isNullValue();
7659 static bool isAllOnes(SDValue V) {
7660 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7661 return C && C->isAllOnesValue();
7664 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7665 bool addTest = true;
7666 SDValue Cond = Op.getOperand(0);
7667 SDValue Op1 = Op.getOperand(1);
7668 SDValue Op2 = Op.getOperand(2);
7669 DebugLoc DL = Op.getDebugLoc();
7672 if (Cond.getOpcode() == ISD::SETCC) {
7673 SDValue NewCond = LowerSETCC(Cond, DAG);
7674 if (NewCond.getNode())
7678 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7679 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7680 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7681 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7682 if (Cond.getOpcode() == X86ISD::SETCC &&
7683 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7684 isZero(Cond.getOperand(1).getOperand(1))) {
7685 SDValue Cmp = Cond.getOperand(1);
7687 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7689 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7690 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7691 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7693 SDValue CmpOp0 = Cmp.getOperand(0);
7694 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7695 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7697 SDValue Res = // Res = 0 or -1.
7698 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7699 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7701 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7702 Res = DAG.getNOT(DL, Res, Res.getValueType());
7704 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7705 if (N2C == 0 || !N2C->isNullValue())
7706 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7711 // Look past (and (setcc_carry (cmp ...)), 1).
7712 if (Cond.getOpcode() == ISD::AND &&
7713 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7714 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7715 if (C && C->getAPIntValue() == 1)
7716 Cond = Cond.getOperand(0);
7719 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7720 // setting operand in place of the X86ISD::SETCC.
7721 if (Cond.getOpcode() == X86ISD::SETCC ||
7722 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7723 CC = Cond.getOperand(0);
7725 SDValue Cmp = Cond.getOperand(1);
7726 unsigned Opc = Cmp.getOpcode();
7727 EVT VT = Op.getValueType();
7729 bool IllegalFPCMov = false;
7730 if (VT.isFloatingPoint() && !VT.isVector() &&
7731 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7732 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7734 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7735 Opc == X86ISD::BT) { // FIXME
7742 // Look pass the truncate.
7743 if (Cond.getOpcode() == ISD::TRUNCATE)
7744 Cond = Cond.getOperand(0);
7746 // We know the result of AND is compared against zero. Try to match
7748 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7749 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7750 if (NewSetCC.getNode()) {
7751 CC = NewSetCC.getOperand(0);
7752 Cond = NewSetCC.getOperand(1);
7759 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7760 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7763 // a < b ? -1 : 0 -> RES = ~setcc_carry
7764 // a < b ? 0 : -1 -> RES = setcc_carry
7765 // a >= b ? -1 : 0 -> RES = setcc_carry
7766 // a >= b ? 0 : -1 -> RES = ~setcc_carry
7767 if (Cond.getOpcode() == X86ISD::CMP) {
7768 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7770 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7771 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7772 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7773 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7774 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7775 return DAG.getNOT(DL, Res, Res.getValueType());
7780 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7781 // condition is true.
7782 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7783 SDValue Ops[] = { Op2, Op1, CC, Cond };
7784 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7787 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7788 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7789 // from the AND / OR.
7790 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7791 Opc = Op.getOpcode();
7792 if (Opc != ISD::OR && Opc != ISD::AND)
7794 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7795 Op.getOperand(0).hasOneUse() &&
7796 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7797 Op.getOperand(1).hasOneUse());
7800 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7801 // 1 and that the SETCC node has a single use.
7802 static bool isXor1OfSetCC(SDValue Op) {
7803 if (Op.getOpcode() != ISD::XOR)
7805 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7806 if (N1C && N1C->getAPIntValue() == 1) {
7807 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7808 Op.getOperand(0).hasOneUse();
7813 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7814 bool addTest = true;
7815 SDValue Chain = Op.getOperand(0);
7816 SDValue Cond = Op.getOperand(1);
7817 SDValue Dest = Op.getOperand(2);
7818 DebugLoc dl = Op.getDebugLoc();
7821 if (Cond.getOpcode() == ISD::SETCC) {
7822 SDValue NewCond = LowerSETCC(Cond, DAG);
7823 if (NewCond.getNode())
7827 // FIXME: LowerXALUO doesn't handle these!!
7828 else if (Cond.getOpcode() == X86ISD::ADD ||
7829 Cond.getOpcode() == X86ISD::SUB ||
7830 Cond.getOpcode() == X86ISD::SMUL ||
7831 Cond.getOpcode() == X86ISD::UMUL)
7832 Cond = LowerXALUO(Cond, DAG);
7835 // Look pass (and (setcc_carry (cmp ...)), 1).
7836 if (Cond.getOpcode() == ISD::AND &&
7837 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7838 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7839 if (C && C->getAPIntValue() == 1)
7840 Cond = Cond.getOperand(0);
7843 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7844 // setting operand in place of the X86ISD::SETCC.
7845 if (Cond.getOpcode() == X86ISD::SETCC ||
7846 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7847 CC = Cond.getOperand(0);
7849 SDValue Cmp = Cond.getOperand(1);
7850 unsigned Opc = Cmp.getOpcode();
7851 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7852 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7856 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7860 // These can only come from an arithmetic instruction with overflow,
7861 // e.g. SADDO, UADDO.
7862 Cond = Cond.getNode()->getOperand(1);
7869 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7870 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7871 if (CondOpc == ISD::OR) {
7872 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7873 // two branches instead of an explicit OR instruction with a
7875 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7876 isX86LogicalCmp(Cmp)) {
7877 CC = Cond.getOperand(0).getOperand(0);
7878 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7879 Chain, Dest, CC, Cmp);
7880 CC = Cond.getOperand(1).getOperand(0);
7884 } else { // ISD::AND
7885 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7886 // two branches instead of an explicit AND instruction with a
7887 // separate test. However, we only do this if this block doesn't
7888 // have a fall-through edge, because this requires an explicit
7889 // jmp when the condition is false.
7890 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7891 isX86LogicalCmp(Cmp) &&
7892 Op.getNode()->hasOneUse()) {
7893 X86::CondCode CCode =
7894 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7895 CCode = X86::GetOppositeBranchCondition(CCode);
7896 CC = DAG.getConstant(CCode, MVT::i8);
7897 SDNode *User = *Op.getNode()->use_begin();
7898 // Look for an unconditional branch following this conditional branch.
7899 // We need this because we need to reverse the successors in order
7900 // to implement FCMP_OEQ.
7901 if (User->getOpcode() == ISD::BR) {
7902 SDValue FalseBB = User->getOperand(1);
7904 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7905 assert(NewBR == User);
7909 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7910 Chain, Dest, CC, Cmp);
7911 X86::CondCode CCode =
7912 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7913 CCode = X86::GetOppositeBranchCondition(CCode);
7914 CC = DAG.getConstant(CCode, MVT::i8);
7920 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7921 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7922 // It should be transformed during dag combiner except when the condition
7923 // is set by a arithmetics with overflow node.
7924 X86::CondCode CCode =
7925 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7926 CCode = X86::GetOppositeBranchCondition(CCode);
7927 CC = DAG.getConstant(CCode, MVT::i8);
7928 Cond = Cond.getOperand(0).getOperand(1);
7934 // Look pass the truncate.
7935 if (Cond.getOpcode() == ISD::TRUNCATE)
7936 Cond = Cond.getOperand(0);
7938 // We know the result of AND is compared against zero. Try to match
7940 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7941 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7942 if (NewSetCC.getNode()) {
7943 CC = NewSetCC.getOperand(0);
7944 Cond = NewSetCC.getOperand(1);
7951 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7952 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7954 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7955 Chain, Dest, CC, Cond);
7959 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7960 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7961 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7962 // that the guard pages used by the OS virtual memory manager are allocated in
7963 // correct sequence.
7965 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7966 SelectionDAG &DAG) const {
7967 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7968 "This should be used only on Windows targets");
7969 assert(!Subtarget->isTargetEnvMacho());
7970 DebugLoc dl = Op.getDebugLoc();
7973 SDValue Chain = Op.getOperand(0);
7974 SDValue Size = Op.getOperand(1);
7975 // FIXME: Ensure alignment here
7979 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7980 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
7982 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
7983 Flag = Chain.getValue(1);
7985 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7987 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7988 Flag = Chain.getValue(1);
7990 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7992 SDValue Ops1[2] = { Chain.getValue(0), Chain };
7993 return DAG.getMergeValues(Ops1, 2, dl);
7996 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7997 MachineFunction &MF = DAG.getMachineFunction();
7998 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8000 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8001 DebugLoc DL = Op.getDebugLoc();
8003 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8004 // vastart just stores the address of the VarArgsFrameIndex slot into the
8005 // memory location argument.
8006 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8008 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8009 MachinePointerInfo(SV), false, false, 0);
8013 // gp_offset (0 - 6 * 8)
8014 // fp_offset (48 - 48 + 8 * 16)
8015 // overflow_arg_area (point to parameters coming in memory).
8017 SmallVector<SDValue, 8> MemOps;
8018 SDValue FIN = Op.getOperand(1);
8020 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8021 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8023 FIN, MachinePointerInfo(SV), false, false, 0);
8024 MemOps.push_back(Store);
8027 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8028 FIN, DAG.getIntPtrConstant(4));
8029 Store = DAG.getStore(Op.getOperand(0), DL,
8030 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8032 FIN, MachinePointerInfo(SV, 4), false, false, 0);
8033 MemOps.push_back(Store);
8035 // Store ptr to overflow_arg_area
8036 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8037 FIN, DAG.getIntPtrConstant(4));
8038 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8040 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8041 MachinePointerInfo(SV, 8),
8043 MemOps.push_back(Store);
8045 // Store ptr to reg_save_area.
8046 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8047 FIN, DAG.getIntPtrConstant(8));
8048 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8050 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8051 MachinePointerInfo(SV, 16), false, false, 0);
8052 MemOps.push_back(Store);
8053 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8054 &MemOps[0], MemOps.size());
8057 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8058 assert(Subtarget->is64Bit() &&
8059 "LowerVAARG only handles 64-bit va_arg!");
8060 assert((Subtarget->isTargetLinux() ||
8061 Subtarget->isTargetDarwin()) &&
8062 "Unhandled target in LowerVAARG");
8063 assert(Op.getNode()->getNumOperands() == 4);
8064 SDValue Chain = Op.getOperand(0);
8065 SDValue SrcPtr = Op.getOperand(1);
8066 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8067 unsigned Align = Op.getConstantOperandVal(3);
8068 DebugLoc dl = Op.getDebugLoc();
8070 EVT ArgVT = Op.getNode()->getValueType(0);
8071 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8072 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8075 // Decide which area this value should be read from.
8076 // TODO: Implement the AMD64 ABI in its entirety. This simple
8077 // selection mechanism works only for the basic types.
8078 if (ArgVT == MVT::f80) {
8079 llvm_unreachable("va_arg for f80 not yet implemented");
8080 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8081 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
8082 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8083 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
8085 llvm_unreachable("Unhandled argument type in LowerVAARG");
8089 // Sanity Check: Make sure using fp_offset makes sense.
8090 assert(!UseSoftFloat &&
8091 !(DAG.getMachineFunction()
8092 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8093 Subtarget->hasXMM());
8096 // Insert VAARG_64 node into the DAG
8097 // VAARG_64 returns two values: Variable Argument Address, Chain
8098 SmallVector<SDValue, 11> InstOps;
8099 InstOps.push_back(Chain);
8100 InstOps.push_back(SrcPtr);
8101 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8102 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8103 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8104 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8105 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8106 VTs, &InstOps[0], InstOps.size(),
8108 MachinePointerInfo(SV),
8113 Chain = VAARG.getValue(1);
8115 // Load the next argument and return it
8116 return DAG.getLoad(ArgVT, dl,
8119 MachinePointerInfo(),
8123 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8124 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8125 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8126 SDValue Chain = Op.getOperand(0);
8127 SDValue DstPtr = Op.getOperand(1);
8128 SDValue SrcPtr = Op.getOperand(2);
8129 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8130 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8131 DebugLoc DL = Op.getDebugLoc();
8133 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8134 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8136 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8140 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8141 DebugLoc dl = Op.getDebugLoc();
8142 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8144 default: return SDValue(); // Don't custom lower most intrinsics.
8145 // Comparison intrinsics.
8146 case Intrinsic::x86_sse_comieq_ss:
8147 case Intrinsic::x86_sse_comilt_ss:
8148 case Intrinsic::x86_sse_comile_ss:
8149 case Intrinsic::x86_sse_comigt_ss:
8150 case Intrinsic::x86_sse_comige_ss:
8151 case Intrinsic::x86_sse_comineq_ss:
8152 case Intrinsic::x86_sse_ucomieq_ss:
8153 case Intrinsic::x86_sse_ucomilt_ss:
8154 case Intrinsic::x86_sse_ucomile_ss:
8155 case Intrinsic::x86_sse_ucomigt_ss:
8156 case Intrinsic::x86_sse_ucomige_ss:
8157 case Intrinsic::x86_sse_ucomineq_ss:
8158 case Intrinsic::x86_sse2_comieq_sd:
8159 case Intrinsic::x86_sse2_comilt_sd:
8160 case Intrinsic::x86_sse2_comile_sd:
8161 case Intrinsic::x86_sse2_comigt_sd:
8162 case Intrinsic::x86_sse2_comige_sd:
8163 case Intrinsic::x86_sse2_comineq_sd:
8164 case Intrinsic::x86_sse2_ucomieq_sd:
8165 case Intrinsic::x86_sse2_ucomilt_sd:
8166 case Intrinsic::x86_sse2_ucomile_sd:
8167 case Intrinsic::x86_sse2_ucomigt_sd:
8168 case Intrinsic::x86_sse2_ucomige_sd:
8169 case Intrinsic::x86_sse2_ucomineq_sd: {
8171 ISD::CondCode CC = ISD::SETCC_INVALID;
8174 case Intrinsic::x86_sse_comieq_ss:
8175 case Intrinsic::x86_sse2_comieq_sd:
8179 case Intrinsic::x86_sse_comilt_ss:
8180 case Intrinsic::x86_sse2_comilt_sd:
8184 case Intrinsic::x86_sse_comile_ss:
8185 case Intrinsic::x86_sse2_comile_sd:
8189 case Intrinsic::x86_sse_comigt_ss:
8190 case Intrinsic::x86_sse2_comigt_sd:
8194 case Intrinsic::x86_sse_comige_ss:
8195 case Intrinsic::x86_sse2_comige_sd:
8199 case Intrinsic::x86_sse_comineq_ss:
8200 case Intrinsic::x86_sse2_comineq_sd:
8204 case Intrinsic::x86_sse_ucomieq_ss:
8205 case Intrinsic::x86_sse2_ucomieq_sd:
8206 Opc = X86ISD::UCOMI;
8209 case Intrinsic::x86_sse_ucomilt_ss:
8210 case Intrinsic::x86_sse2_ucomilt_sd:
8211 Opc = X86ISD::UCOMI;
8214 case Intrinsic::x86_sse_ucomile_ss:
8215 case Intrinsic::x86_sse2_ucomile_sd:
8216 Opc = X86ISD::UCOMI;
8219 case Intrinsic::x86_sse_ucomigt_ss:
8220 case Intrinsic::x86_sse2_ucomigt_sd:
8221 Opc = X86ISD::UCOMI;
8224 case Intrinsic::x86_sse_ucomige_ss:
8225 case Intrinsic::x86_sse2_ucomige_sd:
8226 Opc = X86ISD::UCOMI;
8229 case Intrinsic::x86_sse_ucomineq_ss:
8230 case Intrinsic::x86_sse2_ucomineq_sd:
8231 Opc = X86ISD::UCOMI;
8236 SDValue LHS = Op.getOperand(1);
8237 SDValue RHS = Op.getOperand(2);
8238 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8239 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8240 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8241 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8242 DAG.getConstant(X86CC, MVT::i8), Cond);
8243 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8245 // ptest and testp intrinsics. The intrinsic these come from are designed to
8246 // return an integer value, not just an instruction so lower it to the ptest
8247 // or testp pattern and a setcc for the result.
8248 case Intrinsic::x86_sse41_ptestz:
8249 case Intrinsic::x86_sse41_ptestc:
8250 case Intrinsic::x86_sse41_ptestnzc:
8251 case Intrinsic::x86_avx_ptestz_256:
8252 case Intrinsic::x86_avx_ptestc_256:
8253 case Intrinsic::x86_avx_ptestnzc_256:
8254 case Intrinsic::x86_avx_vtestz_ps:
8255 case Intrinsic::x86_avx_vtestc_ps:
8256 case Intrinsic::x86_avx_vtestnzc_ps:
8257 case Intrinsic::x86_avx_vtestz_pd:
8258 case Intrinsic::x86_avx_vtestc_pd:
8259 case Intrinsic::x86_avx_vtestnzc_pd:
8260 case Intrinsic::x86_avx_vtestz_ps_256:
8261 case Intrinsic::x86_avx_vtestc_ps_256:
8262 case Intrinsic::x86_avx_vtestnzc_ps_256:
8263 case Intrinsic::x86_avx_vtestz_pd_256:
8264 case Intrinsic::x86_avx_vtestc_pd_256:
8265 case Intrinsic::x86_avx_vtestnzc_pd_256: {
8266 bool IsTestPacked = false;
8269 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8270 case Intrinsic::x86_avx_vtestz_ps:
8271 case Intrinsic::x86_avx_vtestz_pd:
8272 case Intrinsic::x86_avx_vtestz_ps_256:
8273 case Intrinsic::x86_avx_vtestz_pd_256:
8274 IsTestPacked = true; // Fallthrough
8275 case Intrinsic::x86_sse41_ptestz:
8276 case Intrinsic::x86_avx_ptestz_256:
8278 X86CC = X86::COND_E;
8280 case Intrinsic::x86_avx_vtestc_ps:
8281 case Intrinsic::x86_avx_vtestc_pd:
8282 case Intrinsic::x86_avx_vtestc_ps_256:
8283 case Intrinsic::x86_avx_vtestc_pd_256:
8284 IsTestPacked = true; // Fallthrough
8285 case Intrinsic::x86_sse41_ptestc:
8286 case Intrinsic::x86_avx_ptestc_256:
8288 X86CC = X86::COND_B;
8290 case Intrinsic::x86_avx_vtestnzc_ps:
8291 case Intrinsic::x86_avx_vtestnzc_pd:
8292 case Intrinsic::x86_avx_vtestnzc_ps_256:
8293 case Intrinsic::x86_avx_vtestnzc_pd_256:
8294 IsTestPacked = true; // Fallthrough
8295 case Intrinsic::x86_sse41_ptestnzc:
8296 case Intrinsic::x86_avx_ptestnzc_256:
8298 X86CC = X86::COND_A;
8302 SDValue LHS = Op.getOperand(1);
8303 SDValue RHS = Op.getOperand(2);
8304 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8305 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8306 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8307 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8308 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8311 // Fix vector shift instructions where the last operand is a non-immediate
8313 case Intrinsic::x86_sse2_pslli_w:
8314 case Intrinsic::x86_sse2_pslli_d:
8315 case Intrinsic::x86_sse2_pslli_q:
8316 case Intrinsic::x86_sse2_psrli_w:
8317 case Intrinsic::x86_sse2_psrli_d:
8318 case Intrinsic::x86_sse2_psrli_q:
8319 case Intrinsic::x86_sse2_psrai_w:
8320 case Intrinsic::x86_sse2_psrai_d:
8321 case Intrinsic::x86_mmx_pslli_w:
8322 case Intrinsic::x86_mmx_pslli_d:
8323 case Intrinsic::x86_mmx_pslli_q:
8324 case Intrinsic::x86_mmx_psrli_w:
8325 case Intrinsic::x86_mmx_psrli_d:
8326 case Intrinsic::x86_mmx_psrli_q:
8327 case Intrinsic::x86_mmx_psrai_w:
8328 case Intrinsic::x86_mmx_psrai_d: {
8329 SDValue ShAmt = Op.getOperand(2);
8330 if (isa<ConstantSDNode>(ShAmt))
8333 unsigned NewIntNo = 0;
8334 EVT ShAmtVT = MVT::v4i32;
8336 case Intrinsic::x86_sse2_pslli_w:
8337 NewIntNo = Intrinsic::x86_sse2_psll_w;
8339 case Intrinsic::x86_sse2_pslli_d:
8340 NewIntNo = Intrinsic::x86_sse2_psll_d;
8342 case Intrinsic::x86_sse2_pslli_q:
8343 NewIntNo = Intrinsic::x86_sse2_psll_q;
8345 case Intrinsic::x86_sse2_psrli_w:
8346 NewIntNo = Intrinsic::x86_sse2_psrl_w;
8348 case Intrinsic::x86_sse2_psrli_d:
8349 NewIntNo = Intrinsic::x86_sse2_psrl_d;
8351 case Intrinsic::x86_sse2_psrli_q:
8352 NewIntNo = Intrinsic::x86_sse2_psrl_q;
8354 case Intrinsic::x86_sse2_psrai_w:
8355 NewIntNo = Intrinsic::x86_sse2_psra_w;
8357 case Intrinsic::x86_sse2_psrai_d:
8358 NewIntNo = Intrinsic::x86_sse2_psra_d;
8361 ShAmtVT = MVT::v2i32;
8363 case Intrinsic::x86_mmx_pslli_w:
8364 NewIntNo = Intrinsic::x86_mmx_psll_w;
8366 case Intrinsic::x86_mmx_pslli_d:
8367 NewIntNo = Intrinsic::x86_mmx_psll_d;
8369 case Intrinsic::x86_mmx_pslli_q:
8370 NewIntNo = Intrinsic::x86_mmx_psll_q;
8372 case Intrinsic::x86_mmx_psrli_w:
8373 NewIntNo = Intrinsic::x86_mmx_psrl_w;
8375 case Intrinsic::x86_mmx_psrli_d:
8376 NewIntNo = Intrinsic::x86_mmx_psrl_d;
8378 case Intrinsic::x86_mmx_psrli_q:
8379 NewIntNo = Intrinsic::x86_mmx_psrl_q;
8381 case Intrinsic::x86_mmx_psrai_w:
8382 NewIntNo = Intrinsic::x86_mmx_psra_w;
8384 case Intrinsic::x86_mmx_psrai_d:
8385 NewIntNo = Intrinsic::x86_mmx_psra_d;
8387 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8393 // The vector shift intrinsics with scalars uses 32b shift amounts but
8394 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8398 ShOps[1] = DAG.getConstant(0, MVT::i32);
8399 if (ShAmtVT == MVT::v4i32) {
8400 ShOps[2] = DAG.getUNDEF(MVT::i32);
8401 ShOps[3] = DAG.getUNDEF(MVT::i32);
8402 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8404 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8405 // FIXME this must be lowered to get rid of the invalid type.
8408 EVT VT = Op.getValueType();
8409 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8410 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8411 DAG.getConstant(NewIntNo, MVT::i32),
8412 Op.getOperand(1), ShAmt);
8417 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8418 SelectionDAG &DAG) const {
8419 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8420 MFI->setReturnAddressIsTaken(true);
8422 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8423 DebugLoc dl = Op.getDebugLoc();
8426 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8428 DAG.getConstant(TD->getPointerSize(),
8429 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8430 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8431 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8433 MachinePointerInfo(), false, false, 0);
8436 // Just load the return address.
8437 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8438 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8439 RetAddrFI, MachinePointerInfo(), false, false, 0);
8442 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8443 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8444 MFI->setFrameAddressIsTaken(true);
8446 EVT VT = Op.getValueType();
8447 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
8448 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8449 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8450 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8452 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8453 MachinePointerInfo(),
8458 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8459 SelectionDAG &DAG) const {
8460 return DAG.getIntPtrConstant(2*TD->getPointerSize());
8463 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8464 MachineFunction &MF = DAG.getMachineFunction();
8465 SDValue Chain = Op.getOperand(0);
8466 SDValue Offset = Op.getOperand(1);
8467 SDValue Handler = Op.getOperand(2);
8468 DebugLoc dl = Op.getDebugLoc();
8470 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8471 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8473 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8475 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8476 DAG.getIntPtrConstant(TD->getPointerSize()));
8477 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8478 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8480 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8481 MF.getRegInfo().addLiveOut(StoreAddrReg);
8483 return DAG.getNode(X86ISD::EH_RETURN, dl,
8485 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8488 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8489 SelectionDAG &DAG) const {
8490 SDValue Root = Op.getOperand(0);
8491 SDValue Trmp = Op.getOperand(1); // trampoline
8492 SDValue FPtr = Op.getOperand(2); // nested function
8493 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8494 DebugLoc dl = Op.getDebugLoc();
8496 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8498 if (Subtarget->is64Bit()) {
8499 SDValue OutChains[6];
8501 // Large code-model.
8502 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8503 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8505 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8506 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8508 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8510 // Load the pointer to the nested function into R11.
8511 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8512 SDValue Addr = Trmp;
8513 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8514 Addr, MachinePointerInfo(TrmpAddr),
8517 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8518 DAG.getConstant(2, MVT::i64));
8519 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8520 MachinePointerInfo(TrmpAddr, 2),
8523 // Load the 'nest' parameter value into R10.
8524 // R10 is specified in X86CallingConv.td
8525 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8526 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8527 DAG.getConstant(10, MVT::i64));
8528 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8529 Addr, MachinePointerInfo(TrmpAddr, 10),
8532 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8533 DAG.getConstant(12, MVT::i64));
8534 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8535 MachinePointerInfo(TrmpAddr, 12),
8538 // Jump to the nested function.
8539 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8540 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8541 DAG.getConstant(20, MVT::i64));
8542 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8543 Addr, MachinePointerInfo(TrmpAddr, 20),
8546 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8547 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8548 DAG.getConstant(22, MVT::i64));
8549 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8550 MachinePointerInfo(TrmpAddr, 22),
8554 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8555 return DAG.getMergeValues(Ops, 2, dl);
8557 const Function *Func =
8558 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8559 CallingConv::ID CC = Func->getCallingConv();
8564 llvm_unreachable("Unsupported calling convention");
8565 case CallingConv::C:
8566 case CallingConv::X86_StdCall: {
8567 // Pass 'nest' parameter in ECX.
8568 // Must be kept in sync with X86CallingConv.td
8571 // Check that ECX wasn't needed by an 'inreg' parameter.
8572 const FunctionType *FTy = Func->getFunctionType();
8573 const AttrListPtr &Attrs = Func->getAttributes();
8575 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8576 unsigned InRegCount = 0;
8579 for (FunctionType::param_iterator I = FTy->param_begin(),
8580 E = FTy->param_end(); I != E; ++I, ++Idx)
8581 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8582 // FIXME: should only count parameters that are lowered to integers.
8583 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8585 if (InRegCount > 2) {
8586 report_fatal_error("Nest register in use - reduce number of inreg"
8592 case CallingConv::X86_FastCall:
8593 case CallingConv::X86_ThisCall:
8594 case CallingConv::Fast:
8595 // Pass 'nest' parameter in EAX.
8596 // Must be kept in sync with X86CallingConv.td
8601 SDValue OutChains[4];
8604 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8605 DAG.getConstant(10, MVT::i32));
8606 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8608 // This is storing the opcode for MOV32ri.
8609 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8610 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8611 OutChains[0] = DAG.getStore(Root, dl,
8612 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8613 Trmp, MachinePointerInfo(TrmpAddr),
8616 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8617 DAG.getConstant(1, MVT::i32));
8618 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8619 MachinePointerInfo(TrmpAddr, 1),
8622 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8623 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8624 DAG.getConstant(5, MVT::i32));
8625 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8626 MachinePointerInfo(TrmpAddr, 5),
8629 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8630 DAG.getConstant(6, MVT::i32));
8631 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8632 MachinePointerInfo(TrmpAddr, 6),
8636 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8637 return DAG.getMergeValues(Ops, 2, dl);
8641 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8642 SelectionDAG &DAG) const {
8644 The rounding mode is in bits 11:10 of FPSR, and has the following
8651 FLT_ROUNDS, on the other hand, expects the following:
8658 To perform the conversion, we do:
8659 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8662 MachineFunction &MF = DAG.getMachineFunction();
8663 const TargetMachine &TM = MF.getTarget();
8664 const TargetFrameLowering &TFI = *TM.getFrameLowering();
8665 unsigned StackAlignment = TFI.getStackAlignment();
8666 EVT VT = Op.getValueType();
8667 DebugLoc DL = Op.getDebugLoc();
8669 // Save FP Control Word to stack slot
8670 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8671 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8674 MachineMemOperand *MMO =
8675 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8676 MachineMemOperand::MOStore, 2, 2);
8678 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8679 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8680 DAG.getVTList(MVT::Other),
8681 Ops, 2, MVT::i16, MMO);
8683 // Load FP Control Word from stack slot
8684 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8685 MachinePointerInfo(), false, false, 0);
8687 // Transform as necessary
8689 DAG.getNode(ISD::SRL, DL, MVT::i16,
8690 DAG.getNode(ISD::AND, DL, MVT::i16,
8691 CWD, DAG.getConstant(0x800, MVT::i16)),
8692 DAG.getConstant(11, MVT::i8));
8694 DAG.getNode(ISD::SRL, DL, MVT::i16,
8695 DAG.getNode(ISD::AND, DL, MVT::i16,
8696 CWD, DAG.getConstant(0x400, MVT::i16)),
8697 DAG.getConstant(9, MVT::i8));
8700 DAG.getNode(ISD::AND, DL, MVT::i16,
8701 DAG.getNode(ISD::ADD, DL, MVT::i16,
8702 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8703 DAG.getConstant(1, MVT::i16)),
8704 DAG.getConstant(3, MVT::i16));
8707 return DAG.getNode((VT.getSizeInBits() < 16 ?
8708 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8711 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8712 EVT VT = Op.getValueType();
8714 unsigned NumBits = VT.getSizeInBits();
8715 DebugLoc dl = Op.getDebugLoc();
8717 Op = Op.getOperand(0);
8718 if (VT == MVT::i8) {
8719 // Zero extend to i32 since there is not an i8 bsr.
8721 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8724 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8725 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8726 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8728 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8731 DAG.getConstant(NumBits+NumBits-1, OpVT),
8732 DAG.getConstant(X86::COND_E, MVT::i8),
8735 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8737 // Finally xor with NumBits-1.
8738 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8741 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8745 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8746 EVT VT = Op.getValueType();
8748 unsigned NumBits = VT.getSizeInBits();
8749 DebugLoc dl = Op.getDebugLoc();
8751 Op = Op.getOperand(0);
8752 if (VT == MVT::i8) {
8754 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8757 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8758 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8759 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8761 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8764 DAG.getConstant(NumBits, OpVT),
8765 DAG.getConstant(X86::COND_E, MVT::i8),
8768 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8771 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8775 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8776 EVT VT = Op.getValueType();
8777 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8778 DebugLoc dl = Op.getDebugLoc();
8780 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8781 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8782 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8783 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8784 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8786 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8787 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8788 // return AloBlo + AloBhi + AhiBlo;
8790 SDValue A = Op.getOperand(0);
8791 SDValue B = Op.getOperand(1);
8793 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8794 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8795 A, DAG.getConstant(32, MVT::i32));
8796 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8797 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8798 B, DAG.getConstant(32, MVT::i32));
8799 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8800 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8802 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8803 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8805 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8806 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8808 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8809 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8810 AloBhi, DAG.getConstant(32, MVT::i32));
8811 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8812 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8813 AhiBlo, DAG.getConstant(32, MVT::i32));
8814 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8815 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8819 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8821 EVT VT = Op.getValueType();
8822 DebugLoc dl = Op.getDebugLoc();
8823 SDValue R = Op.getOperand(0);
8824 SDValue Amt = Op.getOperand(1);
8826 LLVMContext *Context = DAG.getContext();
8829 if (!Subtarget->hasSSE2()) return SDValue();
8831 // Optimize shl/srl/sra with constant shift amount.
8832 if (isSplatVector(Amt.getNode())) {
8833 SDValue SclrAmt = Amt->getOperand(0);
8834 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8835 uint64_t ShiftAmt = C->getZExtValue();
8837 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8838 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8839 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8840 R, DAG.getConstant(ShiftAmt, MVT::i32));
8842 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
8843 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8844 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8845 R, DAG.getConstant(ShiftAmt, MVT::i32));
8847 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
8848 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8849 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8850 R, DAG.getConstant(ShiftAmt, MVT::i32));
8852 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
8853 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8854 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8855 R, DAG.getConstant(ShiftAmt, MVT::i32));
8857 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
8858 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8859 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8860 R, DAG.getConstant(ShiftAmt, MVT::i32));
8862 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
8863 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8864 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8865 R, DAG.getConstant(ShiftAmt, MVT::i32));
8867 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
8868 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8869 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8870 R, DAG.getConstant(ShiftAmt, MVT::i32));
8872 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
8873 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8874 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8875 R, DAG.getConstant(ShiftAmt, MVT::i32));
8879 // Lower SHL with variable shift amount.
8880 // Cannot lower SHL without SSE4.1 or later.
8881 if (!Subtarget->hasSSE41()) return SDValue();
8883 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
8884 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8885 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8886 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8888 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8890 std::vector<Constant*> CV(4, CI);
8891 Constant *C = ConstantVector::get(CV);
8892 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8893 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8894 MachinePointerInfo::getConstantPool(),
8897 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8898 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8899 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8900 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8902 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
8904 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8905 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8906 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8908 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8909 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8911 std::vector<Constant*> CVM1(16, CM1);
8912 std::vector<Constant*> CVM2(16, CM2);
8913 Constant *C = ConstantVector::get(CVM1);
8914 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8915 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8916 MachinePointerInfo::getConstantPool(),
8919 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8920 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8921 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8922 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8923 DAG.getConstant(4, MVT::i32));
8924 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8926 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8928 C = ConstantVector::get(CVM2);
8929 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8930 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8931 MachinePointerInfo::getConstantPool(),
8934 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8935 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8936 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8937 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8938 DAG.getConstant(2, MVT::i32));
8939 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8941 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8943 // return pblendv(r, r+r, a);
8944 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8945 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8951 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8952 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8953 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8954 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8955 // has only one use.
8956 SDNode *N = Op.getNode();
8957 SDValue LHS = N->getOperand(0);
8958 SDValue RHS = N->getOperand(1);
8959 unsigned BaseOp = 0;
8961 DebugLoc DL = Op.getDebugLoc();
8962 switch (Op.getOpcode()) {
8963 default: llvm_unreachable("Unknown ovf instruction!");
8965 // A subtract of one will be selected as a INC. Note that INC doesn't
8966 // set CF, so we can't do this for UADDO.
8967 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8969 BaseOp = X86ISD::INC;
8973 BaseOp = X86ISD::ADD;
8977 BaseOp = X86ISD::ADD;
8981 // A subtract of one will be selected as a DEC. Note that DEC doesn't
8982 // set CF, so we can't do this for USUBO.
8983 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8985 BaseOp = X86ISD::DEC;
8989 BaseOp = X86ISD::SUB;
8993 BaseOp = X86ISD::SUB;
8997 BaseOp = X86ISD::SMUL;
9000 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9001 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9003 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9006 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9007 DAG.getConstant(X86::COND_O, MVT::i32),
9008 SDValue(Sum.getNode(), 2));
9010 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9015 // Also sets EFLAGS.
9016 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9017 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9020 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9021 DAG.getConstant(Cond, MVT::i32),
9022 SDValue(Sum.getNode(), 1));
9024 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9028 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9029 DebugLoc dl = Op.getDebugLoc();
9031 if (!Subtarget->hasSSE2()) {
9032 SDValue Chain = Op.getOperand(0);
9033 SDValue Zero = DAG.getConstant(0,
9034 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9036 DAG.getRegister(X86::ESP, MVT::i32), // Base
9037 DAG.getTargetConstant(1, MVT::i8), // Scale
9038 DAG.getRegister(0, MVT::i32), // Index
9039 DAG.getTargetConstant(0, MVT::i32), // Disp
9040 DAG.getRegister(0, MVT::i32), // Segment.
9045 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9046 array_lengthof(Ops));
9047 return SDValue(Res, 0);
9050 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9052 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9054 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9055 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9056 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9057 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9059 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9060 if (!Op1 && !Op2 && !Op3 && Op4)
9061 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9063 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9064 if (Op1 && !Op2 && !Op3 && !Op4)
9065 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9067 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9069 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9072 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9073 EVT T = Op.getValueType();
9074 DebugLoc DL = Op.getDebugLoc();
9077 switch(T.getSimpleVT().SimpleTy) {
9079 assert(false && "Invalid value type!");
9080 case MVT::i8: Reg = X86::AL; size = 1; break;
9081 case MVT::i16: Reg = X86::AX; size = 2; break;
9082 case MVT::i32: Reg = X86::EAX; size = 4; break;
9084 assert(Subtarget->is64Bit() && "Node not type legal!");
9085 Reg = X86::RAX; size = 8;
9088 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9089 Op.getOperand(2), SDValue());
9090 SDValue Ops[] = { cpIn.getValue(0),
9093 DAG.getTargetConstant(size, MVT::i8),
9095 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9096 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9097 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9100 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9104 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9105 SelectionDAG &DAG) const {
9106 assert(Subtarget->is64Bit() && "Result not type legalized?");
9107 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9108 SDValue TheChain = Op.getOperand(0);
9109 DebugLoc dl = Op.getDebugLoc();
9110 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9111 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9112 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9114 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9115 DAG.getConstant(32, MVT::i8));
9117 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9120 return DAG.getMergeValues(Ops, 2, dl);
9123 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9124 SelectionDAG &DAG) const {
9125 EVT SrcVT = Op.getOperand(0).getValueType();
9126 EVT DstVT = Op.getValueType();
9127 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9128 Subtarget->hasMMX() && "Unexpected custom BITCAST");
9129 assert((DstVT == MVT::i64 ||
9130 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9131 "Unexpected custom BITCAST");
9132 // i64 <=> MMX conversions are Legal.
9133 if (SrcVT==MVT::i64 && DstVT.isVector())
9135 if (DstVT==MVT::i64 && SrcVT.isVector())
9137 // MMX <=> MMX conversions are Legal.
9138 if (SrcVT.isVector() && DstVT.isVector())
9140 // All other conversions need to be expanded.
9144 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9145 SDNode *Node = Op.getNode();
9146 DebugLoc dl = Node->getDebugLoc();
9147 EVT T = Node->getValueType(0);
9148 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9149 DAG.getConstant(0, T), Node->getOperand(2));
9150 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9151 cast<AtomicSDNode>(Node)->getMemoryVT(),
9152 Node->getOperand(0),
9153 Node->getOperand(1), negOp,
9154 cast<AtomicSDNode>(Node)->getSrcValue(),
9155 cast<AtomicSDNode>(Node)->getAlignment());
9158 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9159 EVT VT = Op.getNode()->getValueType(0);
9161 // Let legalize expand this if it isn't a legal type yet.
9162 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9165 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9168 bool ExtraOp = false;
9169 switch (Op.getOpcode()) {
9170 default: assert(0 && "Invalid code");
9171 case ISD::ADDC: Opc = X86ISD::ADD; break;
9172 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9173 case ISD::SUBC: Opc = X86ISD::SUB; break;
9174 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9178 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9180 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9181 Op.getOperand(1), Op.getOperand(2));
9184 /// LowerOperation - Provide custom lowering hooks for some operations.
9186 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9187 switch (Op.getOpcode()) {
9188 default: llvm_unreachable("Should not custom lower this!");
9189 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
9190 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
9191 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
9192 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
9193 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
9194 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
9195 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9196 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9197 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
9198 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
9199 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
9200 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9201 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9202 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9203 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
9204 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
9205 case ISD::SHL_PARTS:
9206 case ISD::SRA_PARTS:
9207 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
9208 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
9209 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
9210 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
9211 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
9212 case ISD::FABS: return LowerFABS(Op, DAG);
9213 case ISD::FNEG: return LowerFNEG(Op, DAG);
9214 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
9215 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
9216 case ISD::SETCC: return LowerSETCC(Op, DAG);
9217 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
9218 case ISD::SELECT: return LowerSELECT(Op, DAG);
9219 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
9220 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
9221 case ISD::VASTART: return LowerVASTART(Op, DAG);
9222 case ISD::VAARG: return LowerVAARG(Op, DAG);
9223 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
9224 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9225 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9226 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9227 case ISD::FRAME_TO_ARGS_OFFSET:
9228 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9229 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9230 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
9231 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
9232 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9233 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
9234 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
9235 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
9238 case ISD::SHL: return LowerShift(Op, DAG);
9244 case ISD::UMULO: return LowerXALUO(Op, DAG);
9245 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
9246 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
9250 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9254 void X86TargetLowering::
9255 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9256 SelectionDAG &DAG, unsigned NewOp) const {
9257 EVT T = Node->getValueType(0);
9258 DebugLoc dl = Node->getDebugLoc();
9259 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9261 SDValue Chain = Node->getOperand(0);
9262 SDValue In1 = Node->getOperand(1);
9263 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9264 Node->getOperand(2), DAG.getIntPtrConstant(0));
9265 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9266 Node->getOperand(2), DAG.getIntPtrConstant(1));
9267 SDValue Ops[] = { Chain, In1, In2L, In2H };
9268 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9270 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9271 cast<MemSDNode>(Node)->getMemOperand());
9272 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9273 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9274 Results.push_back(Result.getValue(2));
9277 /// ReplaceNodeResults - Replace a node with an illegal result type
9278 /// with a new node built out of custom code.
9279 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9280 SmallVectorImpl<SDValue>&Results,
9281 SelectionDAG &DAG) const {
9282 DebugLoc dl = N->getDebugLoc();
9283 switch (N->getOpcode()) {
9285 assert(false && "Do not know how to custom type legalize this operation!");
9291 // We don't want to expand or promote these.
9293 case ISD::FP_TO_SINT: {
9294 std::pair<SDValue,SDValue> Vals =
9295 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9296 SDValue FIST = Vals.first, StackSlot = Vals.second;
9297 if (FIST.getNode() != 0) {
9298 EVT VT = N->getValueType(0);
9299 // Return a load from the stack slot.
9300 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9301 MachinePointerInfo(), false, false, 0));
9305 case ISD::READCYCLECOUNTER: {
9306 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9307 SDValue TheChain = N->getOperand(0);
9308 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9309 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9311 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9313 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9314 SDValue Ops[] = { eax, edx };
9315 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9316 Results.push_back(edx.getValue(1));
9319 case ISD::ATOMIC_CMP_SWAP: {
9320 EVT T = N->getValueType(0);
9321 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9322 SDValue cpInL, cpInH;
9323 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9324 DAG.getConstant(0, MVT::i32));
9325 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9326 DAG.getConstant(1, MVT::i32));
9327 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9328 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9330 SDValue swapInL, swapInH;
9331 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9332 DAG.getConstant(0, MVT::i32));
9333 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9334 DAG.getConstant(1, MVT::i32));
9335 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9337 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9338 swapInL.getValue(1));
9339 SDValue Ops[] = { swapInH.getValue(0),
9341 swapInH.getValue(1) };
9342 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9343 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9344 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9346 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9347 MVT::i32, Result.getValue(1));
9348 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9349 MVT::i32, cpOutL.getValue(2));
9350 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9351 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9352 Results.push_back(cpOutH.getValue(1));
9355 case ISD::ATOMIC_LOAD_ADD:
9356 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9358 case ISD::ATOMIC_LOAD_AND:
9359 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9361 case ISD::ATOMIC_LOAD_NAND:
9362 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9364 case ISD::ATOMIC_LOAD_OR:
9365 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9367 case ISD::ATOMIC_LOAD_SUB:
9368 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9370 case ISD::ATOMIC_LOAD_XOR:
9371 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9373 case ISD::ATOMIC_SWAP:
9374 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9379 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9381 default: return NULL;
9382 case X86ISD::BSF: return "X86ISD::BSF";
9383 case X86ISD::BSR: return "X86ISD::BSR";
9384 case X86ISD::SHLD: return "X86ISD::SHLD";
9385 case X86ISD::SHRD: return "X86ISD::SHRD";
9386 case X86ISD::FAND: return "X86ISD::FAND";
9387 case X86ISD::FOR: return "X86ISD::FOR";
9388 case X86ISD::FXOR: return "X86ISD::FXOR";
9389 case X86ISD::FSRL: return "X86ISD::FSRL";
9390 case X86ISD::FILD: return "X86ISD::FILD";
9391 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
9392 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9393 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9394 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9395 case X86ISD::FLD: return "X86ISD::FLD";
9396 case X86ISD::FST: return "X86ISD::FST";
9397 case X86ISD::CALL: return "X86ISD::CALL";
9398 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
9399 case X86ISD::BT: return "X86ISD::BT";
9400 case X86ISD::CMP: return "X86ISD::CMP";
9401 case X86ISD::COMI: return "X86ISD::COMI";
9402 case X86ISD::UCOMI: return "X86ISD::UCOMI";
9403 case X86ISD::SETCC: return "X86ISD::SETCC";
9404 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
9405 case X86ISD::CMOV: return "X86ISD::CMOV";
9406 case X86ISD::BRCOND: return "X86ISD::BRCOND";
9407 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
9408 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
9409 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
9410 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
9411 case X86ISD::Wrapper: return "X86ISD::Wrapper";
9412 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
9413 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
9414 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
9415 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
9416 case X86ISD::PINSRB: return "X86ISD::PINSRB";
9417 case X86ISD::PINSRW: return "X86ISD::PINSRW";
9418 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
9419 case X86ISD::PANDN: return "X86ISD::PANDN";
9420 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
9421 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
9422 case X86ISD::PSIGND: return "X86ISD::PSIGND";
9423 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB";
9424 case X86ISD::FMAX: return "X86ISD::FMAX";
9425 case X86ISD::FMIN: return "X86ISD::FMIN";
9426 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
9427 case X86ISD::FRCP: return "X86ISD::FRCP";
9428 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
9429 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
9430 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
9431 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
9432 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
9433 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
9434 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
9435 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
9436 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
9437 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
9438 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
9439 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
9440 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
9441 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
9442 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
9443 case X86ISD::VSHL: return "X86ISD::VSHL";
9444 case X86ISD::VSRL: return "X86ISD::VSRL";
9445 case X86ISD::CMPPD: return "X86ISD::CMPPD";
9446 case X86ISD::CMPPS: return "X86ISD::CMPPS";
9447 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
9448 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
9449 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
9450 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
9451 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
9452 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
9453 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
9454 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
9455 case X86ISD::ADD: return "X86ISD::ADD";
9456 case X86ISD::SUB: return "X86ISD::SUB";
9457 case X86ISD::ADC: return "X86ISD::ADC";
9458 case X86ISD::SBB: return "X86ISD::SBB";
9459 case X86ISD::SMUL: return "X86ISD::SMUL";
9460 case X86ISD::UMUL: return "X86ISD::UMUL";
9461 case X86ISD::INC: return "X86ISD::INC";
9462 case X86ISD::DEC: return "X86ISD::DEC";
9463 case X86ISD::OR: return "X86ISD::OR";
9464 case X86ISD::XOR: return "X86ISD::XOR";
9465 case X86ISD::AND: return "X86ISD::AND";
9466 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
9467 case X86ISD::PTEST: return "X86ISD::PTEST";
9468 case X86ISD::TESTP: return "X86ISD::TESTP";
9469 case X86ISD::PALIGN: return "X86ISD::PALIGN";
9470 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
9471 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
9472 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
9473 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
9474 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
9475 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
9476 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
9477 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
9478 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
9479 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
9480 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
9481 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
9482 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
9483 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
9484 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
9485 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
9486 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
9487 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
9488 case X86ISD::MOVSD: return "X86ISD::MOVSD";
9489 case X86ISD::MOVSS: return "X86ISD::MOVSS";
9490 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
9491 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
9492 case X86ISD::VUNPCKLPS: return "X86ISD::VUNPCKLPS";
9493 case X86ISD::VUNPCKLPD: return "X86ISD::VUNPCKLPD";
9494 case X86ISD::VUNPCKLPSY: return "X86ISD::VUNPCKLPSY";
9495 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
9496 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
9497 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
9498 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
9499 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
9500 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
9501 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
9502 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
9503 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
9504 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
9505 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
9506 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9507 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
9508 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
9512 // isLegalAddressingMode - Return true if the addressing mode represented
9513 // by AM is legal for this target, for a load/store of the specified type.
9514 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9515 const Type *Ty) const {
9516 // X86 supports extremely general addressing modes.
9517 CodeModel::Model M = getTargetMachine().getCodeModel();
9518 Reloc::Model R = getTargetMachine().getRelocationModel();
9520 // X86 allows a sign-extended 32-bit immediate field as a displacement.
9521 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9526 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9528 // If a reference to this global requires an extra load, we can't fold it.
9529 if (isGlobalStubReference(GVFlags))
9532 // If BaseGV requires a register for the PIC base, we cannot also have a
9533 // BaseReg specified.
9534 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9537 // If lower 4G is not available, then we must use rip-relative addressing.
9538 if ((M != CodeModel::Small || R != Reloc::Static) &&
9539 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9549 // These scales always work.
9554 // These scales are formed with basereg+scalereg. Only accept if there is
9559 default: // Other stuff never works.
9567 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9568 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9570 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9571 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9572 if (NumBits1 <= NumBits2)
9577 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9578 if (!VT1.isInteger() || !VT2.isInteger())
9580 unsigned NumBits1 = VT1.getSizeInBits();
9581 unsigned NumBits2 = VT2.getSizeInBits();
9582 if (NumBits1 <= NumBits2)
9587 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9588 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9589 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9592 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9593 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9594 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9597 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9598 // i16 instructions are longer (0x66 prefix) and potentially slower.
9599 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9602 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9603 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9604 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9605 /// are assumed to be legal.
9607 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9609 // Very little shuffling can be done for 64-bit vectors right now.
9610 if (VT.getSizeInBits() == 64)
9611 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9613 // FIXME: pshufb, blends, shifts.
9614 return (VT.getVectorNumElements() == 2 ||
9615 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9616 isMOVLMask(M, VT) ||
9617 isSHUFPMask(M, VT) ||
9618 isPSHUFDMask(M, VT) ||
9619 isPSHUFHWMask(M, VT) ||
9620 isPSHUFLWMask(M, VT) ||
9621 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9622 isUNPCKLMask(M, VT) ||
9623 isUNPCKHMask(M, VT) ||
9624 isUNPCKL_v_undef_Mask(M, VT) ||
9625 isUNPCKH_v_undef_Mask(M, VT));
9629 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9631 unsigned NumElts = VT.getVectorNumElements();
9632 // FIXME: This collection of masks seems suspect.
9635 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9636 return (isMOVLMask(Mask, VT) ||
9637 isCommutedMOVLMask(Mask, VT, true) ||
9638 isSHUFPMask(Mask, VT) ||
9639 isCommutedSHUFPMask(Mask, VT));
9644 //===----------------------------------------------------------------------===//
9645 // X86 Scheduler Hooks
9646 //===----------------------------------------------------------------------===//
9648 // private utility function
9650 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9651 MachineBasicBlock *MBB,
9658 TargetRegisterClass *RC,
9659 bool invSrc) const {
9660 // For the atomic bitwise operator, we generate
9663 // ld t1 = [bitinstr.addr]
9664 // op t2 = t1, [bitinstr.val]
9666 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9668 // fallthrough -->nextMBB
9669 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9670 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9671 MachineFunction::iterator MBBIter = MBB;
9674 /// First build the CFG
9675 MachineFunction *F = MBB->getParent();
9676 MachineBasicBlock *thisMBB = MBB;
9677 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9678 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9679 F->insert(MBBIter, newMBB);
9680 F->insert(MBBIter, nextMBB);
9682 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9683 nextMBB->splice(nextMBB->begin(), thisMBB,
9684 llvm::next(MachineBasicBlock::iterator(bInstr)),
9686 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9688 // Update thisMBB to fall through to newMBB
9689 thisMBB->addSuccessor(newMBB);
9691 // newMBB jumps to itself and fall through to nextMBB
9692 newMBB->addSuccessor(nextMBB);
9693 newMBB->addSuccessor(newMBB);
9695 // Insert instructions into newMBB based on incoming instruction
9696 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9697 "unexpected number of operands");
9698 DebugLoc dl = bInstr->getDebugLoc();
9699 MachineOperand& destOper = bInstr->getOperand(0);
9700 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9701 int numArgs = bInstr->getNumOperands() - 1;
9702 for (int i=0; i < numArgs; ++i)
9703 argOpers[i] = &bInstr->getOperand(i+1);
9705 // x86 address has 4 operands: base, index, scale, and displacement
9706 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9707 int valArgIndx = lastAddrIndx + 1;
9709 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9710 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9711 for (int i=0; i <= lastAddrIndx; ++i)
9712 (*MIB).addOperand(*argOpers[i]);
9714 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9716 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9721 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9722 assert((argOpers[valArgIndx]->isReg() ||
9723 argOpers[valArgIndx]->isImm()) &&
9725 if (argOpers[valArgIndx]->isReg())
9726 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9728 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9730 (*MIB).addOperand(*argOpers[valArgIndx]);
9732 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9735 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9736 for (int i=0; i <= lastAddrIndx; ++i)
9737 (*MIB).addOperand(*argOpers[i]);
9739 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9740 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9741 bInstr->memoperands_end());
9743 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9747 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9749 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9753 // private utility function: 64 bit atomics on 32 bit host.
9755 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9756 MachineBasicBlock *MBB,
9761 bool invSrc) const {
9762 // For the atomic bitwise operator, we generate
9763 // thisMBB (instructions are in pairs, except cmpxchg8b)
9764 // ld t1,t2 = [bitinstr.addr]
9766 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9767 // op t5, t6 <- out1, out2, [bitinstr.val]
9768 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9769 // mov ECX, EBX <- t5, t6
9770 // mov EAX, EDX <- t1, t2
9771 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9772 // mov t3, t4 <- EAX, EDX
9774 // result in out1, out2
9775 // fallthrough -->nextMBB
9777 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9778 const unsigned LoadOpc = X86::MOV32rm;
9779 const unsigned NotOpc = X86::NOT32r;
9780 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9781 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9782 MachineFunction::iterator MBBIter = MBB;
9785 /// First build the CFG
9786 MachineFunction *F = MBB->getParent();
9787 MachineBasicBlock *thisMBB = MBB;
9788 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9789 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9790 F->insert(MBBIter, newMBB);
9791 F->insert(MBBIter, nextMBB);
9793 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9794 nextMBB->splice(nextMBB->begin(), thisMBB,
9795 llvm::next(MachineBasicBlock::iterator(bInstr)),
9797 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9799 // Update thisMBB to fall through to newMBB
9800 thisMBB->addSuccessor(newMBB);
9802 // newMBB jumps to itself and fall through to nextMBB
9803 newMBB->addSuccessor(nextMBB);
9804 newMBB->addSuccessor(newMBB);
9806 DebugLoc dl = bInstr->getDebugLoc();
9807 // Insert instructions into newMBB based on incoming instruction
9808 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9809 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9810 "unexpected number of operands");
9811 MachineOperand& dest1Oper = bInstr->getOperand(0);
9812 MachineOperand& dest2Oper = bInstr->getOperand(1);
9813 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9814 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9815 argOpers[i] = &bInstr->getOperand(i+2);
9817 // We use some of the operands multiple times, so conservatively just
9818 // clear any kill flags that might be present.
9819 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9820 argOpers[i]->setIsKill(false);
9823 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9824 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9826 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9827 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9828 for (int i=0; i <= lastAddrIndx; ++i)
9829 (*MIB).addOperand(*argOpers[i]);
9830 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9831 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9832 // add 4 to displacement.
9833 for (int i=0; i <= lastAddrIndx-2; ++i)
9834 (*MIB).addOperand(*argOpers[i]);
9835 MachineOperand newOp3 = *(argOpers[3]);
9837 newOp3.setImm(newOp3.getImm()+4);
9839 newOp3.setOffset(newOp3.getOffset()+4);
9840 (*MIB).addOperand(newOp3);
9841 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9843 // t3/4 are defined later, at the bottom of the loop
9844 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9845 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9846 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9847 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9848 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9849 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9851 // The subsequent operations should be using the destination registers of
9852 //the PHI instructions.
9854 t1 = F->getRegInfo().createVirtualRegister(RC);
9855 t2 = F->getRegInfo().createVirtualRegister(RC);
9856 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9857 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9859 t1 = dest1Oper.getReg();
9860 t2 = dest2Oper.getReg();
9863 int valArgIndx = lastAddrIndx + 1;
9864 assert((argOpers[valArgIndx]->isReg() ||
9865 argOpers[valArgIndx]->isImm()) &&
9867 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9868 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9869 if (argOpers[valArgIndx]->isReg())
9870 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9872 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9873 if (regOpcL != X86::MOV32rr)
9875 (*MIB).addOperand(*argOpers[valArgIndx]);
9876 assert(argOpers[valArgIndx + 1]->isReg() ==
9877 argOpers[valArgIndx]->isReg());
9878 assert(argOpers[valArgIndx + 1]->isImm() ==
9879 argOpers[valArgIndx]->isImm());
9880 if (argOpers[valArgIndx + 1]->isReg())
9881 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9883 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9884 if (regOpcH != X86::MOV32rr)
9886 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9888 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9890 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9893 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9895 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9898 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9899 for (int i=0; i <= lastAddrIndx; ++i)
9900 (*MIB).addOperand(*argOpers[i]);
9902 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9903 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9904 bInstr->memoperands_end());
9906 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9907 MIB.addReg(X86::EAX);
9908 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9909 MIB.addReg(X86::EDX);
9912 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9914 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9918 // private utility function
9920 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9921 MachineBasicBlock *MBB,
9922 unsigned cmovOpc) const {
9923 // For the atomic min/max operator, we generate
9926 // ld t1 = [min/max.addr]
9927 // mov t2 = [min/max.val]
9929 // cmov[cond] t2 = t1
9931 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9933 // fallthrough -->nextMBB
9935 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9936 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9937 MachineFunction::iterator MBBIter = MBB;
9940 /// First build the CFG
9941 MachineFunction *F = MBB->getParent();
9942 MachineBasicBlock *thisMBB = MBB;
9943 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9944 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9945 F->insert(MBBIter, newMBB);
9946 F->insert(MBBIter, nextMBB);
9948 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9949 nextMBB->splice(nextMBB->begin(), thisMBB,
9950 llvm::next(MachineBasicBlock::iterator(mInstr)),
9952 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9954 // Update thisMBB to fall through to newMBB
9955 thisMBB->addSuccessor(newMBB);
9957 // newMBB jumps to newMBB and fall through to nextMBB
9958 newMBB->addSuccessor(nextMBB);
9959 newMBB->addSuccessor(newMBB);
9961 DebugLoc dl = mInstr->getDebugLoc();
9962 // Insert instructions into newMBB based on incoming instruction
9963 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9964 "unexpected number of operands");
9965 MachineOperand& destOper = mInstr->getOperand(0);
9966 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9967 int numArgs = mInstr->getNumOperands() - 1;
9968 for (int i=0; i < numArgs; ++i)
9969 argOpers[i] = &mInstr->getOperand(i+1);
9971 // x86 address has 4 operands: base, index, scale, and displacement
9972 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9973 int valArgIndx = lastAddrIndx + 1;
9975 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9976 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9977 for (int i=0; i <= lastAddrIndx; ++i)
9978 (*MIB).addOperand(*argOpers[i]);
9980 // We only support register and immediate values
9981 assert((argOpers[valArgIndx]->isReg() ||
9982 argOpers[valArgIndx]->isImm()) &&
9985 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9986 if (argOpers[valArgIndx]->isReg())
9987 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9989 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9990 (*MIB).addOperand(*argOpers[valArgIndx]);
9992 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9995 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10000 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10001 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10005 // Cmp and exchange if none has modified the memory location
10006 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10007 for (int i=0; i <= lastAddrIndx; ++i)
10008 (*MIB).addOperand(*argOpers[i]);
10010 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10011 (*MIB).setMemRefs(mInstr->memoperands_begin(),
10012 mInstr->memoperands_end());
10014 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10015 MIB.addReg(X86::EAX);
10018 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10020 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
10024 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10025 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10026 // in the .td file.
10027 MachineBasicBlock *
10028 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10029 unsigned numArgs, bool memArg) const {
10030 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10031 "Target must have SSE4.2 or AVX features enabled");
10033 DebugLoc dl = MI->getDebugLoc();
10034 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10036 if (!Subtarget->hasAVX()) {
10038 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10040 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10043 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10045 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10048 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10049 for (unsigned i = 0; i < numArgs; ++i) {
10050 MachineOperand &Op = MI->getOperand(i+1);
10051 if (!(Op.isReg() && Op.isImplicit()))
10052 MIB.addOperand(Op);
10054 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10055 .addReg(X86::XMM0);
10057 MI->eraseFromParent();
10061 MachineBasicBlock *
10062 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10063 DebugLoc dl = MI->getDebugLoc();
10064 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10066 // Address into RAX/EAX, other two args into ECX, EDX.
10067 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10068 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10069 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10070 for (int i = 0; i < X86::AddrNumOperands; ++i)
10071 MIB.addOperand(MI->getOperand(i));
10073 unsigned ValOps = X86::AddrNumOperands;
10074 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10075 .addReg(MI->getOperand(ValOps).getReg());
10076 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10077 .addReg(MI->getOperand(ValOps+1).getReg());
10079 // The instruction doesn't actually take any operands though.
10080 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10082 MI->eraseFromParent(); // The pseudo is gone now.
10086 MachineBasicBlock *
10087 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10088 DebugLoc dl = MI->getDebugLoc();
10089 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10091 // First arg in ECX, the second in EAX.
10092 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10093 .addReg(MI->getOperand(0).getReg());
10094 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10095 .addReg(MI->getOperand(1).getReg());
10097 // The instruction doesn't actually take any operands though.
10098 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10100 MI->eraseFromParent(); // The pseudo is gone now.
10104 MachineBasicBlock *
10105 X86TargetLowering::EmitVAARG64WithCustomInserter(
10107 MachineBasicBlock *MBB) const {
10108 // Emit va_arg instruction on X86-64.
10110 // Operands to this pseudo-instruction:
10111 // 0 ) Output : destination address (reg)
10112 // 1-5) Input : va_list address (addr, i64mem)
10113 // 6 ) ArgSize : Size (in bytes) of vararg type
10114 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10115 // 8 ) Align : Alignment of type
10116 // 9 ) EFLAGS (implicit-def)
10118 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10119 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10121 unsigned DestReg = MI->getOperand(0).getReg();
10122 MachineOperand &Base = MI->getOperand(1);
10123 MachineOperand &Scale = MI->getOperand(2);
10124 MachineOperand &Index = MI->getOperand(3);
10125 MachineOperand &Disp = MI->getOperand(4);
10126 MachineOperand &Segment = MI->getOperand(5);
10127 unsigned ArgSize = MI->getOperand(6).getImm();
10128 unsigned ArgMode = MI->getOperand(7).getImm();
10129 unsigned Align = MI->getOperand(8).getImm();
10131 // Memory Reference
10132 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10133 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10134 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10136 // Machine Information
10137 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10138 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10139 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10140 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10141 DebugLoc DL = MI->getDebugLoc();
10143 // struct va_list {
10146 // i64 overflow_area (address)
10147 // i64 reg_save_area (address)
10149 // sizeof(va_list) = 24
10150 // alignment(va_list) = 8
10152 unsigned TotalNumIntRegs = 6;
10153 unsigned TotalNumXMMRegs = 8;
10154 bool UseGPOffset = (ArgMode == 1);
10155 bool UseFPOffset = (ArgMode == 2);
10156 unsigned MaxOffset = TotalNumIntRegs * 8 +
10157 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10159 /* Align ArgSize to a multiple of 8 */
10160 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10161 bool NeedsAlign = (Align > 8);
10163 MachineBasicBlock *thisMBB = MBB;
10164 MachineBasicBlock *overflowMBB;
10165 MachineBasicBlock *offsetMBB;
10166 MachineBasicBlock *endMBB;
10168 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
10169 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
10170 unsigned OffsetReg = 0;
10172 if (!UseGPOffset && !UseFPOffset) {
10173 // If we only pull from the overflow region, we don't create a branch.
10174 // We don't need to alter control flow.
10175 OffsetDestReg = 0; // unused
10176 OverflowDestReg = DestReg;
10179 overflowMBB = thisMBB;
10182 // First emit code to check if gp_offset (or fp_offset) is below the bound.
10183 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10184 // If not, pull from overflow_area. (branch to overflowMBB)
10189 // offsetMBB overflowMBB
10194 // Registers for the PHI in endMBB
10195 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10196 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10198 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10199 MachineFunction *MF = MBB->getParent();
10200 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10201 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10202 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10204 MachineFunction::iterator MBBIter = MBB;
10207 // Insert the new basic blocks
10208 MF->insert(MBBIter, offsetMBB);
10209 MF->insert(MBBIter, overflowMBB);
10210 MF->insert(MBBIter, endMBB);
10212 // Transfer the remainder of MBB and its successor edges to endMBB.
10213 endMBB->splice(endMBB->begin(), thisMBB,
10214 llvm::next(MachineBasicBlock::iterator(MI)),
10216 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10218 // Make offsetMBB and overflowMBB successors of thisMBB
10219 thisMBB->addSuccessor(offsetMBB);
10220 thisMBB->addSuccessor(overflowMBB);
10222 // endMBB is a successor of both offsetMBB and overflowMBB
10223 offsetMBB->addSuccessor(endMBB);
10224 overflowMBB->addSuccessor(endMBB);
10226 // Load the offset value into a register
10227 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10228 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10232 .addDisp(Disp, UseFPOffset ? 4 : 0)
10233 .addOperand(Segment)
10234 .setMemRefs(MMOBegin, MMOEnd);
10236 // Check if there is enough room left to pull this argument.
10237 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10239 .addImm(MaxOffset + 8 - ArgSizeA8);
10241 // Branch to "overflowMBB" if offset >= max
10242 // Fall through to "offsetMBB" otherwise
10243 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10244 .addMBB(overflowMBB);
10247 // In offsetMBB, emit code to use the reg_save_area.
10249 assert(OffsetReg != 0);
10251 // Read the reg_save_area address.
10252 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10253 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10258 .addOperand(Segment)
10259 .setMemRefs(MMOBegin, MMOEnd);
10261 // Zero-extend the offset
10262 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10263 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10266 .addImm(X86::sub_32bit);
10268 // Add the offset to the reg_save_area to get the final address.
10269 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10270 .addReg(OffsetReg64)
10271 .addReg(RegSaveReg);
10273 // Compute the offset for the next argument
10274 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10275 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10277 .addImm(UseFPOffset ? 16 : 8);
10279 // Store it back into the va_list.
10280 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10284 .addDisp(Disp, UseFPOffset ? 4 : 0)
10285 .addOperand(Segment)
10286 .addReg(NextOffsetReg)
10287 .setMemRefs(MMOBegin, MMOEnd);
10290 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10295 // Emit code to use overflow area
10298 // Load the overflow_area address into a register.
10299 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10300 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10305 .addOperand(Segment)
10306 .setMemRefs(MMOBegin, MMOEnd);
10308 // If we need to align it, do so. Otherwise, just copy the address
10309 // to OverflowDestReg.
10311 // Align the overflow address
10312 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10313 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10315 // aligned_addr = (addr + (align-1)) & ~(align-1)
10316 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10317 .addReg(OverflowAddrReg)
10320 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10322 .addImm(~(uint64_t)(Align-1));
10324 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10325 .addReg(OverflowAddrReg);
10328 // Compute the next overflow address after this argument.
10329 // (the overflow address should be kept 8-byte aligned)
10330 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10331 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10332 .addReg(OverflowDestReg)
10333 .addImm(ArgSizeA8);
10335 // Store the new overflow address.
10336 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10341 .addOperand(Segment)
10342 .addReg(NextAddrReg)
10343 .setMemRefs(MMOBegin, MMOEnd);
10345 // If we branched, emit the PHI to the front of endMBB.
10347 BuildMI(*endMBB, endMBB->begin(), DL,
10348 TII->get(X86::PHI), DestReg)
10349 .addReg(OffsetDestReg).addMBB(offsetMBB)
10350 .addReg(OverflowDestReg).addMBB(overflowMBB);
10353 // Erase the pseudo instruction
10354 MI->eraseFromParent();
10359 MachineBasicBlock *
10360 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10362 MachineBasicBlock *MBB) const {
10363 // Emit code to save XMM registers to the stack. The ABI says that the
10364 // number of registers to save is given in %al, so it's theoretically
10365 // possible to do an indirect jump trick to avoid saving all of them,
10366 // however this code takes a simpler approach and just executes all
10367 // of the stores if %al is non-zero. It's less code, and it's probably
10368 // easier on the hardware branch predictor, and stores aren't all that
10369 // expensive anyway.
10371 // Create the new basic blocks. One block contains all the XMM stores,
10372 // and one block is the final destination regardless of whether any
10373 // stores were performed.
10374 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10375 MachineFunction *F = MBB->getParent();
10376 MachineFunction::iterator MBBIter = MBB;
10378 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10379 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10380 F->insert(MBBIter, XMMSaveMBB);
10381 F->insert(MBBIter, EndMBB);
10383 // Transfer the remainder of MBB and its successor edges to EndMBB.
10384 EndMBB->splice(EndMBB->begin(), MBB,
10385 llvm::next(MachineBasicBlock::iterator(MI)),
10387 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10389 // The original block will now fall through to the XMM save block.
10390 MBB->addSuccessor(XMMSaveMBB);
10391 // The XMMSaveMBB will fall through to the end block.
10392 XMMSaveMBB->addSuccessor(EndMBB);
10394 // Now add the instructions.
10395 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10396 DebugLoc DL = MI->getDebugLoc();
10398 unsigned CountReg = MI->getOperand(0).getReg();
10399 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10400 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10402 if (!Subtarget->isTargetWin64()) {
10403 // If %al is 0, branch around the XMM save block.
10404 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10405 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10406 MBB->addSuccessor(EndMBB);
10409 // In the XMM save block, save all the XMM argument registers.
10410 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10411 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10412 MachineMemOperand *MMO =
10413 F->getMachineMemOperand(
10414 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10415 MachineMemOperand::MOStore,
10416 /*Size=*/16, /*Align=*/16);
10417 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10418 .addFrameIndex(RegSaveFrameIndex)
10419 .addImm(/*Scale=*/1)
10420 .addReg(/*IndexReg=*/0)
10421 .addImm(/*Disp=*/Offset)
10422 .addReg(/*Segment=*/0)
10423 .addReg(MI->getOperand(i).getReg())
10424 .addMemOperand(MMO);
10427 MI->eraseFromParent(); // The pseudo instruction is gone now.
10432 MachineBasicBlock *
10433 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10434 MachineBasicBlock *BB) const {
10435 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10436 DebugLoc DL = MI->getDebugLoc();
10438 // To "insert" a SELECT_CC instruction, we actually have to insert the
10439 // diamond control-flow pattern. The incoming instruction knows the
10440 // destination vreg to set, the condition code register to branch on, the
10441 // true/false values to select between, and a branch opcode to use.
10442 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10443 MachineFunction::iterator It = BB;
10449 // cmpTY ccX, r1, r2
10451 // fallthrough --> copy0MBB
10452 MachineBasicBlock *thisMBB = BB;
10453 MachineFunction *F = BB->getParent();
10454 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10455 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10456 F->insert(It, copy0MBB);
10457 F->insert(It, sinkMBB);
10459 // If the EFLAGS register isn't dead in the terminator, then claim that it's
10460 // live into the sink and copy blocks.
10461 const MachineFunction *MF = BB->getParent();
10462 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10463 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10465 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10466 const MachineOperand &MO = MI->getOperand(I);
10467 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10468 unsigned Reg = MO.getReg();
10469 if (Reg != X86::EFLAGS) continue;
10470 copy0MBB->addLiveIn(Reg);
10471 sinkMBB->addLiveIn(Reg);
10474 // Transfer the remainder of BB and its successor edges to sinkMBB.
10475 sinkMBB->splice(sinkMBB->begin(), BB,
10476 llvm::next(MachineBasicBlock::iterator(MI)),
10478 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10480 // Add the true and fallthrough blocks as its successors.
10481 BB->addSuccessor(copy0MBB);
10482 BB->addSuccessor(sinkMBB);
10484 // Create the conditional branch instruction.
10486 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10487 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10490 // %FalseValue = ...
10491 // # fallthrough to sinkMBB
10492 copy0MBB->addSuccessor(sinkMBB);
10495 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10497 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10498 TII->get(X86::PHI), MI->getOperand(0).getReg())
10499 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10500 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10502 MI->eraseFromParent(); // The pseudo instruction is gone now.
10506 MachineBasicBlock *
10507 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10508 MachineBasicBlock *BB) const {
10509 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10510 DebugLoc DL = MI->getDebugLoc();
10512 assert(!Subtarget->isTargetEnvMacho());
10514 // The lowering is pretty easy: we're just emitting the call to _alloca. The
10515 // non-trivial part is impdef of ESP.
10517 if (Subtarget->isTargetWin64()) {
10518 if (Subtarget->isTargetCygMing()) {
10519 // ___chkstk(Mingw64):
10520 // Clobbers R10, R11, RAX and EFLAGS.
10522 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10523 .addExternalSymbol("___chkstk")
10524 .addReg(X86::RAX, RegState::Implicit)
10525 .addReg(X86::RSP, RegState::Implicit)
10526 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10527 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10528 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10530 // __chkstk(MSVCRT): does not update stack pointer.
10531 // Clobbers R10, R11 and EFLAGS.
10532 // FIXME: RAX(allocated size) might be reused and not killed.
10533 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10534 .addExternalSymbol("__chkstk")
10535 .addReg(X86::RAX, RegState::Implicit)
10536 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10537 // RAX has the offset to subtracted from RSP.
10538 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10543 const char *StackProbeSymbol =
10544 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10546 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10547 .addExternalSymbol(StackProbeSymbol)
10548 .addReg(X86::EAX, RegState::Implicit)
10549 .addReg(X86::ESP, RegState::Implicit)
10550 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10551 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10552 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10555 MI->eraseFromParent(); // The pseudo instruction is gone now.
10559 MachineBasicBlock *
10560 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10561 MachineBasicBlock *BB) const {
10562 // This is pretty easy. We're taking the value that we received from
10563 // our load from the relocation, sticking it in either RDI (x86-64)
10564 // or EAX and doing an indirect call. The return value will then
10565 // be in the normal return register.
10566 const X86InstrInfo *TII
10567 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10568 DebugLoc DL = MI->getDebugLoc();
10569 MachineFunction *F = BB->getParent();
10571 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10572 assert(MI->getOperand(3).isGlobal() && "This should be a global");
10574 if (Subtarget->is64Bit()) {
10575 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10576 TII->get(X86::MOV64rm), X86::RDI)
10578 .addImm(0).addReg(0)
10579 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10580 MI->getOperand(3).getTargetFlags())
10582 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10583 addDirectMem(MIB, X86::RDI);
10584 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10585 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10586 TII->get(X86::MOV32rm), X86::EAX)
10588 .addImm(0).addReg(0)
10589 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10590 MI->getOperand(3).getTargetFlags())
10592 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10593 addDirectMem(MIB, X86::EAX);
10595 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10596 TII->get(X86::MOV32rm), X86::EAX)
10597 .addReg(TII->getGlobalBaseReg(F))
10598 .addImm(0).addReg(0)
10599 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10600 MI->getOperand(3).getTargetFlags())
10602 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10603 addDirectMem(MIB, X86::EAX);
10606 MI->eraseFromParent(); // The pseudo instruction is gone now.
10610 MachineBasicBlock *
10611 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10612 MachineBasicBlock *BB) const {
10613 switch (MI->getOpcode()) {
10614 default: assert(false && "Unexpected instr type to insert");
10615 case X86::TAILJMPd64:
10616 case X86::TAILJMPr64:
10617 case X86::TAILJMPm64:
10618 assert(!"TAILJMP64 would not be touched here.");
10619 case X86::TCRETURNdi64:
10620 case X86::TCRETURNri64:
10621 case X86::TCRETURNmi64:
10622 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10623 // On AMD64, additional defs should be added before register allocation.
10624 if (!Subtarget->isTargetWin64()) {
10625 MI->addRegisterDefined(X86::RSI);
10626 MI->addRegisterDefined(X86::RDI);
10627 MI->addRegisterDefined(X86::XMM6);
10628 MI->addRegisterDefined(X86::XMM7);
10629 MI->addRegisterDefined(X86::XMM8);
10630 MI->addRegisterDefined(X86::XMM9);
10631 MI->addRegisterDefined(X86::XMM10);
10632 MI->addRegisterDefined(X86::XMM11);
10633 MI->addRegisterDefined(X86::XMM12);
10634 MI->addRegisterDefined(X86::XMM13);
10635 MI->addRegisterDefined(X86::XMM14);
10636 MI->addRegisterDefined(X86::XMM15);
10639 case X86::WIN_ALLOCA:
10640 return EmitLoweredWinAlloca(MI, BB);
10641 case X86::TLSCall_32:
10642 case X86::TLSCall_64:
10643 return EmitLoweredTLSCall(MI, BB);
10644 case X86::CMOV_GR8:
10645 case X86::CMOV_FR32:
10646 case X86::CMOV_FR64:
10647 case X86::CMOV_V4F32:
10648 case X86::CMOV_V2F64:
10649 case X86::CMOV_V2I64:
10650 case X86::CMOV_GR16:
10651 case X86::CMOV_GR32:
10652 case X86::CMOV_RFP32:
10653 case X86::CMOV_RFP64:
10654 case X86::CMOV_RFP80:
10655 return EmitLoweredSelect(MI, BB);
10657 case X86::FP32_TO_INT16_IN_MEM:
10658 case X86::FP32_TO_INT32_IN_MEM:
10659 case X86::FP32_TO_INT64_IN_MEM:
10660 case X86::FP64_TO_INT16_IN_MEM:
10661 case X86::FP64_TO_INT32_IN_MEM:
10662 case X86::FP64_TO_INT64_IN_MEM:
10663 case X86::FP80_TO_INT16_IN_MEM:
10664 case X86::FP80_TO_INT32_IN_MEM:
10665 case X86::FP80_TO_INT64_IN_MEM: {
10666 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10667 DebugLoc DL = MI->getDebugLoc();
10669 // Change the floating point control register to use "round towards zero"
10670 // mode when truncating to an integer value.
10671 MachineFunction *F = BB->getParent();
10672 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10673 addFrameReference(BuildMI(*BB, MI, DL,
10674 TII->get(X86::FNSTCW16m)), CWFrameIdx);
10676 // Load the old value of the high byte of the control word...
10678 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10679 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10682 // Set the high part to be round to zero...
10683 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10686 // Reload the modified control word now...
10687 addFrameReference(BuildMI(*BB, MI, DL,
10688 TII->get(X86::FLDCW16m)), CWFrameIdx);
10690 // Restore the memory image of control word to original value
10691 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10694 // Get the X86 opcode to use.
10696 switch (MI->getOpcode()) {
10697 default: llvm_unreachable("illegal opcode!");
10698 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10699 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10700 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10701 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10702 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10703 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10704 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10705 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10706 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10710 MachineOperand &Op = MI->getOperand(0);
10712 AM.BaseType = X86AddressMode::RegBase;
10713 AM.Base.Reg = Op.getReg();
10715 AM.BaseType = X86AddressMode::FrameIndexBase;
10716 AM.Base.FrameIndex = Op.getIndex();
10718 Op = MI->getOperand(1);
10720 AM.Scale = Op.getImm();
10721 Op = MI->getOperand(2);
10723 AM.IndexReg = Op.getImm();
10724 Op = MI->getOperand(3);
10725 if (Op.isGlobal()) {
10726 AM.GV = Op.getGlobal();
10728 AM.Disp = Op.getImm();
10730 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10731 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10733 // Reload the original control word now.
10734 addFrameReference(BuildMI(*BB, MI, DL,
10735 TII->get(X86::FLDCW16m)), CWFrameIdx);
10737 MI->eraseFromParent(); // The pseudo instruction is gone now.
10740 // String/text processing lowering.
10741 case X86::PCMPISTRM128REG:
10742 case X86::VPCMPISTRM128REG:
10743 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10744 case X86::PCMPISTRM128MEM:
10745 case X86::VPCMPISTRM128MEM:
10746 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10747 case X86::PCMPESTRM128REG:
10748 case X86::VPCMPESTRM128REG:
10749 return EmitPCMP(MI, BB, 5, false /* in mem */);
10750 case X86::PCMPESTRM128MEM:
10751 case X86::VPCMPESTRM128MEM:
10752 return EmitPCMP(MI, BB, 5, true /* in mem */);
10754 // Thread synchronization.
10756 return EmitMonitor(MI, BB);
10758 return EmitMwait(MI, BB);
10760 // Atomic Lowering.
10761 case X86::ATOMAND32:
10762 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10763 X86::AND32ri, X86::MOV32rm,
10765 X86::NOT32r, X86::EAX,
10766 X86::GR32RegisterClass);
10767 case X86::ATOMOR32:
10768 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10769 X86::OR32ri, X86::MOV32rm,
10771 X86::NOT32r, X86::EAX,
10772 X86::GR32RegisterClass);
10773 case X86::ATOMXOR32:
10774 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10775 X86::XOR32ri, X86::MOV32rm,
10777 X86::NOT32r, X86::EAX,
10778 X86::GR32RegisterClass);
10779 case X86::ATOMNAND32:
10780 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10781 X86::AND32ri, X86::MOV32rm,
10783 X86::NOT32r, X86::EAX,
10784 X86::GR32RegisterClass, true);
10785 case X86::ATOMMIN32:
10786 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10787 case X86::ATOMMAX32:
10788 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10789 case X86::ATOMUMIN32:
10790 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10791 case X86::ATOMUMAX32:
10792 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10794 case X86::ATOMAND16:
10795 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10796 X86::AND16ri, X86::MOV16rm,
10798 X86::NOT16r, X86::AX,
10799 X86::GR16RegisterClass);
10800 case X86::ATOMOR16:
10801 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10802 X86::OR16ri, X86::MOV16rm,
10804 X86::NOT16r, X86::AX,
10805 X86::GR16RegisterClass);
10806 case X86::ATOMXOR16:
10807 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10808 X86::XOR16ri, X86::MOV16rm,
10810 X86::NOT16r, X86::AX,
10811 X86::GR16RegisterClass);
10812 case X86::ATOMNAND16:
10813 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10814 X86::AND16ri, X86::MOV16rm,
10816 X86::NOT16r, X86::AX,
10817 X86::GR16RegisterClass, true);
10818 case X86::ATOMMIN16:
10819 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10820 case X86::ATOMMAX16:
10821 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10822 case X86::ATOMUMIN16:
10823 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10824 case X86::ATOMUMAX16:
10825 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10827 case X86::ATOMAND8:
10828 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10829 X86::AND8ri, X86::MOV8rm,
10831 X86::NOT8r, X86::AL,
10832 X86::GR8RegisterClass);
10834 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10835 X86::OR8ri, X86::MOV8rm,
10837 X86::NOT8r, X86::AL,
10838 X86::GR8RegisterClass);
10839 case X86::ATOMXOR8:
10840 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10841 X86::XOR8ri, X86::MOV8rm,
10843 X86::NOT8r, X86::AL,
10844 X86::GR8RegisterClass);
10845 case X86::ATOMNAND8:
10846 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10847 X86::AND8ri, X86::MOV8rm,
10849 X86::NOT8r, X86::AL,
10850 X86::GR8RegisterClass, true);
10851 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10852 // This group is for 64-bit host.
10853 case X86::ATOMAND64:
10854 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10855 X86::AND64ri32, X86::MOV64rm,
10857 X86::NOT64r, X86::RAX,
10858 X86::GR64RegisterClass);
10859 case X86::ATOMOR64:
10860 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10861 X86::OR64ri32, X86::MOV64rm,
10863 X86::NOT64r, X86::RAX,
10864 X86::GR64RegisterClass);
10865 case X86::ATOMXOR64:
10866 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10867 X86::XOR64ri32, X86::MOV64rm,
10869 X86::NOT64r, X86::RAX,
10870 X86::GR64RegisterClass);
10871 case X86::ATOMNAND64:
10872 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10873 X86::AND64ri32, X86::MOV64rm,
10875 X86::NOT64r, X86::RAX,
10876 X86::GR64RegisterClass, true);
10877 case X86::ATOMMIN64:
10878 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10879 case X86::ATOMMAX64:
10880 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10881 case X86::ATOMUMIN64:
10882 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10883 case X86::ATOMUMAX64:
10884 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10886 // This group does 64-bit operations on a 32-bit host.
10887 case X86::ATOMAND6432:
10888 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10889 X86::AND32rr, X86::AND32rr,
10890 X86::AND32ri, X86::AND32ri,
10892 case X86::ATOMOR6432:
10893 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10894 X86::OR32rr, X86::OR32rr,
10895 X86::OR32ri, X86::OR32ri,
10897 case X86::ATOMXOR6432:
10898 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10899 X86::XOR32rr, X86::XOR32rr,
10900 X86::XOR32ri, X86::XOR32ri,
10902 case X86::ATOMNAND6432:
10903 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10904 X86::AND32rr, X86::AND32rr,
10905 X86::AND32ri, X86::AND32ri,
10907 case X86::ATOMADD6432:
10908 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10909 X86::ADD32rr, X86::ADC32rr,
10910 X86::ADD32ri, X86::ADC32ri,
10912 case X86::ATOMSUB6432:
10913 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10914 X86::SUB32rr, X86::SBB32rr,
10915 X86::SUB32ri, X86::SBB32ri,
10917 case X86::ATOMSWAP6432:
10918 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10919 X86::MOV32rr, X86::MOV32rr,
10920 X86::MOV32ri, X86::MOV32ri,
10922 case X86::VASTART_SAVE_XMM_REGS:
10923 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10925 case X86::VAARG_64:
10926 return EmitVAARG64WithCustomInserter(MI, BB);
10930 //===----------------------------------------------------------------------===//
10931 // X86 Optimization Hooks
10932 //===----------------------------------------------------------------------===//
10934 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10938 const SelectionDAG &DAG,
10939 unsigned Depth) const {
10940 unsigned Opc = Op.getOpcode();
10941 assert((Opc >= ISD::BUILTIN_OP_END ||
10942 Opc == ISD::INTRINSIC_WO_CHAIN ||
10943 Opc == ISD::INTRINSIC_W_CHAIN ||
10944 Opc == ISD::INTRINSIC_VOID) &&
10945 "Should use MaskedValueIsZero if you don't know whether Op"
10946 " is a target node!");
10948 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
10962 // These nodes' second result is a boolean.
10963 if (Op.getResNo() == 0)
10966 case X86ISD::SETCC:
10967 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10968 Mask.getBitWidth() - 1);
10973 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10974 unsigned Depth) const {
10975 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10976 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10977 return Op.getValueType().getScalarType().getSizeInBits();
10983 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10984 /// node is a GlobalAddress + offset.
10985 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10986 const GlobalValue* &GA,
10987 int64_t &Offset) const {
10988 if (N->getOpcode() == X86ISD::Wrapper) {
10989 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10990 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10991 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10995 return TargetLowering::isGAPlusOffset(N, GA, Offset);
10998 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10999 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
11000 /// if the load addresses are consecutive, non-overlapping, and in the right
11002 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11003 TargetLowering::DAGCombinerInfo &DCI) {
11004 DebugLoc dl = N->getDebugLoc();
11005 EVT VT = N->getValueType(0);
11007 if (VT.getSizeInBits() != 128)
11010 // Don't create instructions with illegal types after legalize types has run.
11011 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11012 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11015 SmallVector<SDValue, 16> Elts;
11016 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11017 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11019 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11022 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11023 /// generation and convert it from being a bunch of shuffles and extracts
11024 /// to a simple store and scalar loads to extract the elements.
11025 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11026 const TargetLowering &TLI) {
11027 SDValue InputVector = N->getOperand(0);
11029 // Only operate on vectors of 4 elements, where the alternative shuffling
11030 // gets to be more expensive.
11031 if (InputVector.getValueType() != MVT::v4i32)
11034 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11035 // single use which is a sign-extend or zero-extend, and all elements are
11037 SmallVector<SDNode *, 4> Uses;
11038 unsigned ExtractedElements = 0;
11039 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11040 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11041 if (UI.getUse().getResNo() != InputVector.getResNo())
11044 SDNode *Extract = *UI;
11045 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11048 if (Extract->getValueType(0) != MVT::i32)
11050 if (!Extract->hasOneUse())
11052 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11053 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11055 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11058 // Record which element was extracted.
11059 ExtractedElements |=
11060 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11062 Uses.push_back(Extract);
11065 // If not all the elements were used, this may not be worthwhile.
11066 if (ExtractedElements != 15)
11069 // Ok, we've now decided to do the transformation.
11070 DebugLoc dl = InputVector.getDebugLoc();
11072 // Store the value to a temporary stack slot.
11073 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11074 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11075 MachinePointerInfo(), false, false, 0);
11077 // Replace each use (extract) with a load of the appropriate element.
11078 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11079 UE = Uses.end(); UI != UE; ++UI) {
11080 SDNode *Extract = *UI;
11082 // cOMpute the element's address.
11083 SDValue Idx = Extract->getOperand(1);
11085 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11086 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11087 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11089 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11090 StackPtr, OffsetVal);
11092 // Load the scalar.
11093 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11094 ScalarAddr, MachinePointerInfo(),
11097 // Replace the exact with the load.
11098 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11101 // The replacement was made in place; don't return anything.
11105 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11106 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11107 const X86Subtarget *Subtarget) {
11108 DebugLoc DL = N->getDebugLoc();
11109 SDValue Cond = N->getOperand(0);
11110 // Get the LHS/RHS of the select.
11111 SDValue LHS = N->getOperand(1);
11112 SDValue RHS = N->getOperand(2);
11114 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11115 // instructions match the semantics of the common C idiom x<y?x:y but not
11116 // x<=y?x:y, because of how they handle negative zero (which can be
11117 // ignored in unsafe-math mode).
11118 if (Subtarget->hasSSE2() &&
11119 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11120 Cond.getOpcode() == ISD::SETCC) {
11121 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11123 unsigned Opcode = 0;
11124 // Check for x CC y ? x : y.
11125 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11126 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11130 // Converting this to a min would handle NaNs incorrectly, and swapping
11131 // the operands would cause it to handle comparisons between positive
11132 // and negative zero incorrectly.
11133 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11134 if (!UnsafeFPMath &&
11135 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11137 std::swap(LHS, RHS);
11139 Opcode = X86ISD::FMIN;
11142 // Converting this to a min would handle comparisons between positive
11143 // and negative zero incorrectly.
11144 if (!UnsafeFPMath &&
11145 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11147 Opcode = X86ISD::FMIN;
11150 // Converting this to a min would handle both negative zeros and NaNs
11151 // incorrectly, but we can swap the operands to fix both.
11152 std::swap(LHS, RHS);
11156 Opcode = X86ISD::FMIN;
11160 // Converting this to a max would handle comparisons between positive
11161 // and negative zero incorrectly.
11162 if (!UnsafeFPMath &&
11163 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11165 Opcode = X86ISD::FMAX;
11168 // Converting this to a max would handle NaNs incorrectly, and swapping
11169 // the operands would cause it to handle comparisons between positive
11170 // and negative zero incorrectly.
11171 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11172 if (!UnsafeFPMath &&
11173 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11175 std::swap(LHS, RHS);
11177 Opcode = X86ISD::FMAX;
11180 // Converting this to a max would handle both negative zeros and NaNs
11181 // incorrectly, but we can swap the operands to fix both.
11182 std::swap(LHS, RHS);
11186 Opcode = X86ISD::FMAX;
11189 // Check for x CC y ? y : x -- a min/max with reversed arms.
11190 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11191 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11195 // Converting this to a min would handle comparisons between positive
11196 // and negative zero incorrectly, and swapping the operands would
11197 // cause it to handle NaNs incorrectly.
11198 if (!UnsafeFPMath &&
11199 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11200 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11202 std::swap(LHS, RHS);
11204 Opcode = X86ISD::FMIN;
11207 // Converting this to a min would handle NaNs incorrectly.
11208 if (!UnsafeFPMath &&
11209 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11211 Opcode = X86ISD::FMIN;
11214 // Converting this to a min would handle both negative zeros and NaNs
11215 // incorrectly, but we can swap the operands to fix both.
11216 std::swap(LHS, RHS);
11220 Opcode = X86ISD::FMIN;
11224 // Converting this to a max would handle NaNs incorrectly.
11225 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11227 Opcode = X86ISD::FMAX;
11230 // Converting this to a max would handle comparisons between positive
11231 // and negative zero incorrectly, and swapping the operands would
11232 // cause it to handle NaNs incorrectly.
11233 if (!UnsafeFPMath &&
11234 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11235 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11237 std::swap(LHS, RHS);
11239 Opcode = X86ISD::FMAX;
11242 // Converting this to a max would handle both negative zeros and NaNs
11243 // incorrectly, but we can swap the operands to fix both.
11244 std::swap(LHS, RHS);
11248 Opcode = X86ISD::FMAX;
11254 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11257 // If this is a select between two integer constants, try to do some
11259 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11260 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11261 // Don't do this for crazy integer types.
11262 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11263 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11264 // so that TrueC (the true value) is larger than FalseC.
11265 bool NeedsCondInvert = false;
11267 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11268 // Efficiently invertible.
11269 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
11270 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
11271 isa<ConstantSDNode>(Cond.getOperand(1))))) {
11272 NeedsCondInvert = true;
11273 std::swap(TrueC, FalseC);
11276 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
11277 if (FalseC->getAPIntValue() == 0 &&
11278 TrueC->getAPIntValue().isPowerOf2()) {
11279 if (NeedsCondInvert) // Invert the condition if needed.
11280 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11281 DAG.getConstant(1, Cond.getValueType()));
11283 // Zero extend the condition if needed.
11284 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11286 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11287 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11288 DAG.getConstant(ShAmt, MVT::i8));
11291 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11292 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11293 if (NeedsCondInvert) // Invert the condition if needed.
11294 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11295 DAG.getConstant(1, Cond.getValueType()));
11297 // Zero extend the condition if needed.
11298 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11299 FalseC->getValueType(0), Cond);
11300 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11301 SDValue(FalseC, 0));
11304 // Optimize cases that will turn into an LEA instruction. This requires
11305 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11306 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11307 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11308 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11310 bool isFastMultiplier = false;
11312 switch ((unsigned char)Diff) {
11314 case 1: // result = add base, cond
11315 case 2: // result = lea base( , cond*2)
11316 case 3: // result = lea base(cond, cond*2)
11317 case 4: // result = lea base( , cond*4)
11318 case 5: // result = lea base(cond, cond*4)
11319 case 8: // result = lea base( , cond*8)
11320 case 9: // result = lea base(cond, cond*8)
11321 isFastMultiplier = true;
11326 if (isFastMultiplier) {
11327 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11328 if (NeedsCondInvert) // Invert the condition if needed.
11329 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11330 DAG.getConstant(1, Cond.getValueType()));
11332 // Zero extend the condition if needed.
11333 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11335 // Scale the condition by the difference.
11337 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11338 DAG.getConstant(Diff, Cond.getValueType()));
11340 // Add the base if non-zero.
11341 if (FalseC->getAPIntValue() != 0)
11342 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11343 SDValue(FalseC, 0));
11353 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11354 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11355 TargetLowering::DAGCombinerInfo &DCI) {
11356 DebugLoc DL = N->getDebugLoc();
11358 // If the flag operand isn't dead, don't touch this CMOV.
11359 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11362 SDValue FalseOp = N->getOperand(0);
11363 SDValue TrueOp = N->getOperand(1);
11364 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11365 SDValue Cond = N->getOperand(3);
11366 if (CC == X86::COND_E || CC == X86::COND_NE) {
11367 switch (Cond.getOpcode()) {
11371 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11372 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11373 return (CC == X86::COND_E) ? FalseOp : TrueOp;
11377 // If this is a select between two integer constants, try to do some
11378 // optimizations. Note that the operands are ordered the opposite of SELECT
11380 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11381 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11382 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11383 // larger than FalseC (the false value).
11384 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11385 CC = X86::GetOppositeBranchCondition(CC);
11386 std::swap(TrueC, FalseC);
11389 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
11390 // This is efficient for any integer data type (including i8/i16) and
11392 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11393 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11394 DAG.getConstant(CC, MVT::i8), Cond);
11396 // Zero extend the condition if needed.
11397 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11399 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11400 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11401 DAG.getConstant(ShAmt, MVT::i8));
11402 if (N->getNumValues() == 2) // Dead flag value?
11403 return DCI.CombineTo(N, Cond, SDValue());
11407 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
11408 // for any integer data type, including i8/i16.
11409 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11410 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11411 DAG.getConstant(CC, MVT::i8), Cond);
11413 // Zero extend the condition if needed.
11414 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11415 FalseC->getValueType(0), Cond);
11416 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11417 SDValue(FalseC, 0));
11419 if (N->getNumValues() == 2) // Dead flag value?
11420 return DCI.CombineTo(N, Cond, SDValue());
11424 // Optimize cases that will turn into an LEA instruction. This requires
11425 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11426 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11427 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11428 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11430 bool isFastMultiplier = false;
11432 switch ((unsigned char)Diff) {
11434 case 1: // result = add base, cond
11435 case 2: // result = lea base( , cond*2)
11436 case 3: // result = lea base(cond, cond*2)
11437 case 4: // result = lea base( , cond*4)
11438 case 5: // result = lea base(cond, cond*4)
11439 case 8: // result = lea base( , cond*8)
11440 case 9: // result = lea base(cond, cond*8)
11441 isFastMultiplier = true;
11446 if (isFastMultiplier) {
11447 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11448 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11449 DAG.getConstant(CC, MVT::i8), Cond);
11450 // Zero extend the condition if needed.
11451 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11453 // Scale the condition by the difference.
11455 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11456 DAG.getConstant(Diff, Cond.getValueType()));
11458 // Add the base if non-zero.
11459 if (FalseC->getAPIntValue() != 0)
11460 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11461 SDValue(FalseC, 0));
11462 if (N->getNumValues() == 2) // Dead flag value?
11463 return DCI.CombineTo(N, Cond, SDValue());
11473 /// PerformMulCombine - Optimize a single multiply with constant into two
11474 /// in order to implement it with two cheaper instructions, e.g.
11475 /// LEA + SHL, LEA + LEA.
11476 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11477 TargetLowering::DAGCombinerInfo &DCI) {
11478 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11481 EVT VT = N->getValueType(0);
11482 if (VT != MVT::i64)
11485 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11488 uint64_t MulAmt = C->getZExtValue();
11489 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11492 uint64_t MulAmt1 = 0;
11493 uint64_t MulAmt2 = 0;
11494 if ((MulAmt % 9) == 0) {
11496 MulAmt2 = MulAmt / 9;
11497 } else if ((MulAmt % 5) == 0) {
11499 MulAmt2 = MulAmt / 5;
11500 } else if ((MulAmt % 3) == 0) {
11502 MulAmt2 = MulAmt / 3;
11505 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11506 DebugLoc DL = N->getDebugLoc();
11508 if (isPowerOf2_64(MulAmt2) &&
11509 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11510 // If second multiplifer is pow2, issue it first. We want the multiply by
11511 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11513 std::swap(MulAmt1, MulAmt2);
11516 if (isPowerOf2_64(MulAmt1))
11517 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11518 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11520 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11521 DAG.getConstant(MulAmt1, VT));
11523 if (isPowerOf2_64(MulAmt2))
11524 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11525 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11527 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11528 DAG.getConstant(MulAmt2, VT));
11530 // Do not add new nodes to DAG combiner worklist.
11531 DCI.CombineTo(N, NewMul, false);
11536 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11537 SDValue N0 = N->getOperand(0);
11538 SDValue N1 = N->getOperand(1);
11539 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11540 EVT VT = N0.getValueType();
11542 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11543 // since the result of setcc_c is all zero's or all ones.
11544 if (N1C && N0.getOpcode() == ISD::AND &&
11545 N0.getOperand(1).getOpcode() == ISD::Constant) {
11546 SDValue N00 = N0.getOperand(0);
11547 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11548 ((N00.getOpcode() == ISD::ANY_EXTEND ||
11549 N00.getOpcode() == ISD::ZERO_EXTEND) &&
11550 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11551 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11552 APInt ShAmt = N1C->getAPIntValue();
11553 Mask = Mask.shl(ShAmt);
11555 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11556 N00, DAG.getConstant(Mask, VT));
11563 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11565 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11566 const X86Subtarget *Subtarget) {
11567 EVT VT = N->getValueType(0);
11568 if (!VT.isVector() && VT.isInteger() &&
11569 N->getOpcode() == ISD::SHL)
11570 return PerformSHLCombine(N, DAG);
11572 // On X86 with SSE2 support, we can transform this to a vector shift if
11573 // all elements are shifted by the same amount. We can't do this in legalize
11574 // because the a constant vector is typically transformed to a constant pool
11575 // so we have no knowledge of the shift amount.
11576 if (!Subtarget->hasSSE2())
11579 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11582 SDValue ShAmtOp = N->getOperand(1);
11583 EVT EltVT = VT.getVectorElementType();
11584 DebugLoc DL = N->getDebugLoc();
11585 SDValue BaseShAmt = SDValue();
11586 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11587 unsigned NumElts = VT.getVectorNumElements();
11589 for (; i != NumElts; ++i) {
11590 SDValue Arg = ShAmtOp.getOperand(i);
11591 if (Arg.getOpcode() == ISD::UNDEF) continue;
11595 for (; i != NumElts; ++i) {
11596 SDValue Arg = ShAmtOp.getOperand(i);
11597 if (Arg.getOpcode() == ISD::UNDEF) continue;
11598 if (Arg != BaseShAmt) {
11602 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11603 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11604 SDValue InVec = ShAmtOp.getOperand(0);
11605 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11606 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11608 for (; i != NumElts; ++i) {
11609 SDValue Arg = InVec.getOperand(i);
11610 if (Arg.getOpcode() == ISD::UNDEF) continue;
11614 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11615 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11616 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11617 if (C->getZExtValue() == SplatIdx)
11618 BaseShAmt = InVec.getOperand(1);
11621 if (BaseShAmt.getNode() == 0)
11622 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11623 DAG.getIntPtrConstant(0));
11627 // The shift amount is an i32.
11628 if (EltVT.bitsGT(MVT::i32))
11629 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11630 else if (EltVT.bitsLT(MVT::i32))
11631 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11633 // The shift amount is identical so we can do a vector shift.
11634 SDValue ValOp = N->getOperand(0);
11635 switch (N->getOpcode()) {
11637 llvm_unreachable("Unknown shift opcode!");
11640 if (VT == MVT::v2i64)
11641 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11642 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11644 if (VT == MVT::v4i32)
11645 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11646 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11648 if (VT == MVT::v8i16)
11649 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11650 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11654 if (VT == MVT::v4i32)
11655 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11656 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11658 if (VT == MVT::v8i16)
11659 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11660 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11664 if (VT == MVT::v2i64)
11665 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11666 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11668 if (VT == MVT::v4i32)
11669 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11670 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11672 if (VT == MVT::v8i16)
11673 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11674 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11682 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11683 TargetLowering::DAGCombinerInfo &DCI,
11684 const X86Subtarget *Subtarget) {
11685 if (DCI.isBeforeLegalizeOps())
11688 // Want to form PANDN nodes, in the hopes of then easily combining them with
11689 // OR and AND nodes to form PBLEND/PSIGN.
11690 EVT VT = N->getValueType(0);
11691 if (VT != MVT::v2i64)
11694 SDValue N0 = N->getOperand(0);
11695 SDValue N1 = N->getOperand(1);
11696 DebugLoc DL = N->getDebugLoc();
11698 // Check LHS for vnot
11699 if (N0.getOpcode() == ISD::XOR &&
11700 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11701 return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11703 // Check RHS for vnot
11704 if (N1.getOpcode() == ISD::XOR &&
11705 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11706 return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11711 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11712 TargetLowering::DAGCombinerInfo &DCI,
11713 const X86Subtarget *Subtarget) {
11714 if (DCI.isBeforeLegalizeOps())
11717 EVT VT = N->getValueType(0);
11718 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11721 SDValue N0 = N->getOperand(0);
11722 SDValue N1 = N->getOperand(1);
11724 // look for psign/blend
11725 if (Subtarget->hasSSSE3()) {
11726 if (VT == MVT::v2i64) {
11727 // Canonicalize pandn to RHS
11728 if (N0.getOpcode() == X86ISD::PANDN)
11730 // or (and (m, x), (pandn m, y))
11731 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11732 SDValue Mask = N1.getOperand(0);
11733 SDValue X = N1.getOperand(1);
11735 if (N0.getOperand(0) == Mask)
11736 Y = N0.getOperand(1);
11737 if (N0.getOperand(1) == Mask)
11738 Y = N0.getOperand(0);
11740 // Check to see if the mask appeared in both the AND and PANDN and
11744 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11745 if (Mask.getOpcode() != ISD::BITCAST ||
11746 X.getOpcode() != ISD::BITCAST ||
11747 Y.getOpcode() != ISD::BITCAST)
11750 // Look through mask bitcast.
11751 Mask = Mask.getOperand(0);
11752 EVT MaskVT = Mask.getValueType();
11754 // Validate that the Mask operand is a vector sra node. The sra node
11755 // will be an intrinsic.
11756 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11759 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11760 // there is no psrai.b
11761 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11762 case Intrinsic::x86_sse2_psrai_w:
11763 case Intrinsic::x86_sse2_psrai_d:
11765 default: return SDValue();
11768 // Check that the SRA is all signbits.
11769 SDValue SraC = Mask.getOperand(2);
11770 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
11771 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11772 if ((SraAmt + 1) != EltBits)
11775 DebugLoc DL = N->getDebugLoc();
11777 // Now we know we at least have a plendvb with the mask val. See if
11778 // we can form a psignb/w/d.
11779 // psign = x.type == y.type == mask.type && y = sub(0, x);
11780 X = X.getOperand(0);
11781 Y = Y.getOperand(0);
11782 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11783 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11784 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11787 case 8: Opc = X86ISD::PSIGNB; break;
11788 case 16: Opc = X86ISD::PSIGNW; break;
11789 case 32: Opc = X86ISD::PSIGND; break;
11793 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11794 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11797 // PBLENDVB only available on SSE 4.1
11798 if (!Subtarget->hasSSE41())
11801 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11802 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11803 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11804 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11805 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11810 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11811 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11813 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11815 if (!N0.hasOneUse() || !N1.hasOneUse())
11818 SDValue ShAmt0 = N0.getOperand(1);
11819 if (ShAmt0.getValueType() != MVT::i8)
11821 SDValue ShAmt1 = N1.getOperand(1);
11822 if (ShAmt1.getValueType() != MVT::i8)
11824 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11825 ShAmt0 = ShAmt0.getOperand(0);
11826 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11827 ShAmt1 = ShAmt1.getOperand(0);
11829 DebugLoc DL = N->getDebugLoc();
11830 unsigned Opc = X86ISD::SHLD;
11831 SDValue Op0 = N0.getOperand(0);
11832 SDValue Op1 = N1.getOperand(0);
11833 if (ShAmt0.getOpcode() == ISD::SUB) {
11834 Opc = X86ISD::SHRD;
11835 std::swap(Op0, Op1);
11836 std::swap(ShAmt0, ShAmt1);
11839 unsigned Bits = VT.getSizeInBits();
11840 if (ShAmt1.getOpcode() == ISD::SUB) {
11841 SDValue Sum = ShAmt1.getOperand(0);
11842 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11843 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11844 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11845 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11846 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11847 return DAG.getNode(Opc, DL, VT,
11849 DAG.getNode(ISD::TRUNCATE, DL,
11852 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11853 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11855 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11856 return DAG.getNode(Opc, DL, VT,
11857 N0.getOperand(0), N1.getOperand(0),
11858 DAG.getNode(ISD::TRUNCATE, DL,
11865 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11866 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11867 const X86Subtarget *Subtarget) {
11868 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
11869 // the FP state in cases where an emms may be missing.
11870 // A preferable solution to the general problem is to figure out the right
11871 // places to insert EMMS. This qualifies as a quick hack.
11873 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11874 StoreSDNode *St = cast<StoreSDNode>(N);
11875 EVT VT = St->getValue().getValueType();
11876 if (VT.getSizeInBits() != 64)
11879 const Function *F = DAG.getMachineFunction().getFunction();
11880 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11881 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11882 && Subtarget->hasSSE2();
11883 if ((VT.isVector() ||
11884 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11885 isa<LoadSDNode>(St->getValue()) &&
11886 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11887 St->getChain().hasOneUse() && !St->isVolatile()) {
11888 SDNode* LdVal = St->getValue().getNode();
11889 LoadSDNode *Ld = 0;
11890 int TokenFactorIndex = -1;
11891 SmallVector<SDValue, 8> Ops;
11892 SDNode* ChainVal = St->getChain().getNode();
11893 // Must be a store of a load. We currently handle two cases: the load
11894 // is a direct child, and it's under an intervening TokenFactor. It is
11895 // possible to dig deeper under nested TokenFactors.
11896 if (ChainVal == LdVal)
11897 Ld = cast<LoadSDNode>(St->getChain());
11898 else if (St->getValue().hasOneUse() &&
11899 ChainVal->getOpcode() == ISD::TokenFactor) {
11900 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11901 if (ChainVal->getOperand(i).getNode() == LdVal) {
11902 TokenFactorIndex = i;
11903 Ld = cast<LoadSDNode>(St->getValue());
11905 Ops.push_back(ChainVal->getOperand(i));
11909 if (!Ld || !ISD::isNormalLoad(Ld))
11912 // If this is not the MMX case, i.e. we are just turning i64 load/store
11913 // into f64 load/store, avoid the transformation if there are multiple
11914 // uses of the loaded value.
11915 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11918 DebugLoc LdDL = Ld->getDebugLoc();
11919 DebugLoc StDL = N->getDebugLoc();
11920 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11921 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11923 if (Subtarget->is64Bit() || F64IsLegal) {
11924 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11925 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11926 Ld->getPointerInfo(), Ld->isVolatile(),
11927 Ld->isNonTemporal(), Ld->getAlignment());
11928 SDValue NewChain = NewLd.getValue(1);
11929 if (TokenFactorIndex != -1) {
11930 Ops.push_back(NewChain);
11931 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11934 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11935 St->getPointerInfo(),
11936 St->isVolatile(), St->isNonTemporal(),
11937 St->getAlignment());
11940 // Otherwise, lower to two pairs of 32-bit loads / stores.
11941 SDValue LoAddr = Ld->getBasePtr();
11942 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11943 DAG.getConstant(4, MVT::i32));
11945 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11946 Ld->getPointerInfo(),
11947 Ld->isVolatile(), Ld->isNonTemporal(),
11948 Ld->getAlignment());
11949 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11950 Ld->getPointerInfo().getWithOffset(4),
11951 Ld->isVolatile(), Ld->isNonTemporal(),
11952 MinAlign(Ld->getAlignment(), 4));
11954 SDValue NewChain = LoLd.getValue(1);
11955 if (TokenFactorIndex != -1) {
11956 Ops.push_back(LoLd);
11957 Ops.push_back(HiLd);
11958 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11962 LoAddr = St->getBasePtr();
11963 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11964 DAG.getConstant(4, MVT::i32));
11966 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11967 St->getPointerInfo(),
11968 St->isVolatile(), St->isNonTemporal(),
11969 St->getAlignment());
11970 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11971 St->getPointerInfo().getWithOffset(4),
11973 St->isNonTemporal(),
11974 MinAlign(St->getAlignment(), 4));
11975 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11980 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11981 /// X86ISD::FXOR nodes.
11982 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11983 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11984 // F[X]OR(0.0, x) -> x
11985 // F[X]OR(x, 0.0) -> x
11986 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11987 if (C->getValueAPF().isPosZero())
11988 return N->getOperand(1);
11989 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11990 if (C->getValueAPF().isPosZero())
11991 return N->getOperand(0);
11995 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11996 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11997 // FAND(0.0, x) -> 0.0
11998 // FAND(x, 0.0) -> 0.0
11999 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12000 if (C->getValueAPF().isPosZero())
12001 return N->getOperand(0);
12002 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12003 if (C->getValueAPF().isPosZero())
12004 return N->getOperand(1);
12008 static SDValue PerformBTCombine(SDNode *N,
12010 TargetLowering::DAGCombinerInfo &DCI) {
12011 // BT ignores high bits in the bit index operand.
12012 SDValue Op1 = N->getOperand(1);
12013 if (Op1.hasOneUse()) {
12014 unsigned BitWidth = Op1.getValueSizeInBits();
12015 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12016 APInt KnownZero, KnownOne;
12017 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12018 !DCI.isBeforeLegalizeOps());
12019 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12020 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12021 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12022 DCI.CommitTargetLoweringOpt(TLO);
12027 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12028 SDValue Op = N->getOperand(0);
12029 if (Op.getOpcode() == ISD::BITCAST)
12030 Op = Op.getOperand(0);
12031 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12032 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12033 VT.getVectorElementType().getSizeInBits() ==
12034 OpVT.getVectorElementType().getSizeInBits()) {
12035 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12040 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12041 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
12042 // (and (i32 x86isd::setcc_carry), 1)
12043 // This eliminates the zext. This transformation is necessary because
12044 // ISD::SETCC is always legalized to i8.
12045 DebugLoc dl = N->getDebugLoc();
12046 SDValue N0 = N->getOperand(0);
12047 EVT VT = N->getValueType(0);
12048 if (N0.getOpcode() == ISD::AND &&
12050 N0.getOperand(0).hasOneUse()) {
12051 SDValue N00 = N0.getOperand(0);
12052 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12054 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12055 if (!C || C->getZExtValue() != 1)
12057 return DAG.getNode(ISD::AND, dl, VT,
12058 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12059 N00.getOperand(0), N00.getOperand(1)),
12060 DAG.getConstant(1, VT));
12066 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12067 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12068 unsigned X86CC = N->getConstantOperandVal(0);
12069 SDValue EFLAG = N->getOperand(1);
12070 DebugLoc DL = N->getDebugLoc();
12072 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12073 // a zext and produces an all-ones bit which is more useful than 0/1 in some
12075 if (X86CC == X86::COND_B)
12076 return DAG.getNode(ISD::AND, DL, MVT::i8,
12077 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12078 DAG.getConstant(X86CC, MVT::i8), EFLAG),
12079 DAG.getConstant(1, MVT::i8));
12084 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12085 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12086 X86TargetLowering::DAGCombinerInfo &DCI) {
12087 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12088 // the result is either zero or one (depending on the input carry bit).
12089 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12090 if (X86::isZeroNode(N->getOperand(0)) &&
12091 X86::isZeroNode(N->getOperand(1)) &&
12092 // We don't have a good way to replace an EFLAGS use, so only do this when
12094 SDValue(N, 1).use_empty()) {
12095 DebugLoc DL = N->getDebugLoc();
12096 EVT VT = N->getValueType(0);
12097 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12098 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12099 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12100 DAG.getConstant(X86::COND_B,MVT::i8),
12102 DAG.getConstant(1, VT));
12103 return DCI.CombineTo(N, Res1, CarryOut);
12109 // fold (add Y, (sete X, 0)) -> adc 0, Y
12110 // (add Y, (setne X, 0)) -> sbb -1, Y
12111 // (sub (sete X, 0), Y) -> sbb 0, Y
12112 // (sub (setne X, 0), Y) -> adc -1, Y
12113 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12114 DebugLoc DL = N->getDebugLoc();
12116 // Look through ZExts.
12117 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12118 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12121 SDValue SetCC = Ext.getOperand(0);
12122 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12125 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12126 if (CC != X86::COND_E && CC != X86::COND_NE)
12129 SDValue Cmp = SetCC.getOperand(1);
12130 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12131 !X86::isZeroNode(Cmp.getOperand(1)) ||
12132 !Cmp.getOperand(0).getValueType().isInteger())
12135 SDValue CmpOp0 = Cmp.getOperand(0);
12136 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12137 DAG.getConstant(1, CmpOp0.getValueType()));
12139 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12140 if (CC == X86::COND_NE)
12141 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12142 DL, OtherVal.getValueType(), OtherVal,
12143 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12144 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12145 DL, OtherVal.getValueType(), OtherVal,
12146 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12149 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12150 DAGCombinerInfo &DCI) const {
12151 SelectionDAG &DAG = DCI.DAG;
12152 switch (N->getOpcode()) {
12154 case ISD::EXTRACT_VECTOR_ELT:
12155 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12156 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
12157 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
12159 case ISD::SUB: return OptimizeConditonalInDecrement(N, DAG);
12160 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
12161 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
12164 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
12165 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
12166 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
12167 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
12169 case X86ISD::FOR: return PerformFORCombine(N, DAG);
12170 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
12171 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
12172 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
12173 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
12174 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
12175 case X86ISD::SHUFPS: // Handle all target specific shuffles
12176 case X86ISD::SHUFPD:
12177 case X86ISD::PALIGN:
12178 case X86ISD::PUNPCKHBW:
12179 case X86ISD::PUNPCKHWD:
12180 case X86ISD::PUNPCKHDQ:
12181 case X86ISD::PUNPCKHQDQ:
12182 case X86ISD::UNPCKHPS:
12183 case X86ISD::UNPCKHPD:
12184 case X86ISD::PUNPCKLBW:
12185 case X86ISD::PUNPCKLWD:
12186 case X86ISD::PUNPCKLDQ:
12187 case X86ISD::PUNPCKLQDQ:
12188 case X86ISD::UNPCKLPS:
12189 case X86ISD::UNPCKLPD:
12190 case X86ISD::VUNPCKLPS:
12191 case X86ISD::VUNPCKLPD:
12192 case X86ISD::VUNPCKLPSY:
12193 case X86ISD::VUNPCKLPDY:
12194 case X86ISD::MOVHLPS:
12195 case X86ISD::MOVLHPS:
12196 case X86ISD::PSHUFD:
12197 case X86ISD::PSHUFHW:
12198 case X86ISD::PSHUFLW:
12199 case X86ISD::MOVSS:
12200 case X86ISD::MOVSD:
12201 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12207 /// isTypeDesirableForOp - Return true if the target has native support for
12208 /// the specified value type and it is 'desirable' to use the type for the
12209 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12210 /// instruction encodings are longer and some i16 instructions are slow.
12211 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12212 if (!isTypeLegal(VT))
12214 if (VT != MVT::i16)
12221 case ISD::SIGN_EXTEND:
12222 case ISD::ZERO_EXTEND:
12223 case ISD::ANY_EXTEND:
12236 /// IsDesirableToPromoteOp - This method query the target whether it is
12237 /// beneficial for dag combiner to promote the specified node. If true, it
12238 /// should return the desired promotion type by reference.
12239 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12240 EVT VT = Op.getValueType();
12241 if (VT != MVT::i16)
12244 bool Promote = false;
12245 bool Commute = false;
12246 switch (Op.getOpcode()) {
12249 LoadSDNode *LD = cast<LoadSDNode>(Op);
12250 // If the non-extending load has a single use and it's not live out, then it
12251 // might be folded.
12252 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12253 Op.hasOneUse()*/) {
12254 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12255 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12256 // The only case where we'd want to promote LOAD (rather then it being
12257 // promoted as an operand is when it's only use is liveout.
12258 if (UI->getOpcode() != ISD::CopyToReg)
12265 case ISD::SIGN_EXTEND:
12266 case ISD::ZERO_EXTEND:
12267 case ISD::ANY_EXTEND:
12272 SDValue N0 = Op.getOperand(0);
12273 // Look out for (store (shl (load), x)).
12274 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12287 SDValue N0 = Op.getOperand(0);
12288 SDValue N1 = Op.getOperand(1);
12289 if (!Commute && MayFoldLoad(N1))
12291 // Avoid disabling potential load folding opportunities.
12292 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12294 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12304 //===----------------------------------------------------------------------===//
12305 // X86 Inline Assembly Support
12306 //===----------------------------------------------------------------------===//
12308 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12309 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12311 std::string AsmStr = IA->getAsmString();
12313 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12314 SmallVector<StringRef, 4> AsmPieces;
12315 SplitString(AsmStr, AsmPieces, ";\n");
12317 switch (AsmPieces.size()) {
12318 default: return false;
12320 AsmStr = AsmPieces[0];
12322 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
12324 // FIXME: this should verify that we are targeting a 486 or better. If not,
12325 // we will turn this bswap into something that will be lowered to logical ops
12326 // instead of emitting the bswap asm. For now, we don't support 486 or lower
12327 // so don't worry about this.
12329 if (AsmPieces.size() == 2 &&
12330 (AsmPieces[0] == "bswap" ||
12331 AsmPieces[0] == "bswapq" ||
12332 AsmPieces[0] == "bswapl") &&
12333 (AsmPieces[1] == "$0" ||
12334 AsmPieces[1] == "${0:q}")) {
12335 // No need to check constraints, nothing other than the equivalent of
12336 // "=r,0" would be valid here.
12337 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12338 if (!Ty || Ty->getBitWidth() % 16 != 0)
12340 return IntrinsicLowering::LowerToByteSwap(CI);
12342 // rorw $$8, ${0:w} --> llvm.bswap.i16
12343 if (CI->getType()->isIntegerTy(16) &&
12344 AsmPieces.size() == 3 &&
12345 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12346 AsmPieces[1] == "$$8," &&
12347 AsmPieces[2] == "${0:w}" &&
12348 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12350 const std::string &ConstraintsStr = IA->getConstraintString();
12351 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12352 std::sort(AsmPieces.begin(), AsmPieces.end());
12353 if (AsmPieces.size() == 4 &&
12354 AsmPieces[0] == "~{cc}" &&
12355 AsmPieces[1] == "~{dirflag}" &&
12356 AsmPieces[2] == "~{flags}" &&
12357 AsmPieces[3] == "~{fpsr}") {
12358 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12359 if (!Ty || Ty->getBitWidth() % 16 != 0)
12361 return IntrinsicLowering::LowerToByteSwap(CI);
12366 if (CI->getType()->isIntegerTy(32) &&
12367 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12368 SmallVector<StringRef, 4> Words;
12369 SplitString(AsmPieces[0], Words, " \t,");
12370 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12371 Words[2] == "${0:w}") {
12373 SplitString(AsmPieces[1], Words, " \t,");
12374 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12375 Words[2] == "$0") {
12377 SplitString(AsmPieces[2], Words, " \t,");
12378 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12379 Words[2] == "${0:w}") {
12381 const std::string &ConstraintsStr = IA->getConstraintString();
12382 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12383 std::sort(AsmPieces.begin(), AsmPieces.end());
12384 if (AsmPieces.size() == 4 &&
12385 AsmPieces[0] == "~{cc}" &&
12386 AsmPieces[1] == "~{dirflag}" &&
12387 AsmPieces[2] == "~{flags}" &&
12388 AsmPieces[3] == "~{fpsr}") {
12389 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12390 if (!Ty || Ty->getBitWidth() % 16 != 0)
12392 return IntrinsicLowering::LowerToByteSwap(CI);
12399 if (CI->getType()->isIntegerTy(64)) {
12400 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12401 if (Constraints.size() >= 2 &&
12402 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12403 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12404 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
12405 SmallVector<StringRef, 4> Words;
12406 SplitString(AsmPieces[0], Words, " \t");
12407 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12409 SplitString(AsmPieces[1], Words, " \t");
12410 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12412 SplitString(AsmPieces[2], Words, " \t,");
12413 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12414 Words[2] == "%edx") {
12415 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12416 if (!Ty || Ty->getBitWidth() % 16 != 0)
12418 return IntrinsicLowering::LowerToByteSwap(CI);
12431 /// getConstraintType - Given a constraint letter, return the type of
12432 /// constraint it is for this target.
12433 X86TargetLowering::ConstraintType
12434 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12435 if (Constraint.size() == 1) {
12436 switch (Constraint[0]) {
12446 return C_RegisterClass;
12470 return TargetLowering::getConstraintType(Constraint);
12473 /// Examine constraint type and operand type and determine a weight value.
12474 /// This object must already have been set up with the operand type
12475 /// and the current alternative constraint selected.
12476 TargetLowering::ConstraintWeight
12477 X86TargetLowering::getSingleConstraintMatchWeight(
12478 AsmOperandInfo &info, const char *constraint) const {
12479 ConstraintWeight weight = CW_Invalid;
12480 Value *CallOperandVal = info.CallOperandVal;
12481 // If we don't have a value, we can't do a match,
12482 // but allow it at the lowest weight.
12483 if (CallOperandVal == NULL)
12485 const Type *type = CallOperandVal->getType();
12486 // Look at the constraint type.
12487 switch (*constraint) {
12489 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12500 if (CallOperandVal->getType()->isIntegerTy())
12501 weight = CW_SpecificReg;
12506 if (type->isFloatingPointTy())
12507 weight = CW_SpecificReg;
12510 if (type->isX86_MMXTy() && Subtarget->hasMMX())
12511 weight = CW_SpecificReg;
12515 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12516 weight = CW_Register;
12519 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12520 if (C->getZExtValue() <= 31)
12521 weight = CW_Constant;
12525 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12526 if (C->getZExtValue() <= 63)
12527 weight = CW_Constant;
12531 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12532 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12533 weight = CW_Constant;
12537 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12538 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12539 weight = CW_Constant;
12543 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12544 if (C->getZExtValue() <= 3)
12545 weight = CW_Constant;
12549 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12550 if (C->getZExtValue() <= 0xff)
12551 weight = CW_Constant;
12556 if (dyn_cast<ConstantFP>(CallOperandVal)) {
12557 weight = CW_Constant;
12561 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12562 if ((C->getSExtValue() >= -0x80000000LL) &&
12563 (C->getSExtValue() <= 0x7fffffffLL))
12564 weight = CW_Constant;
12568 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12569 if (C->getZExtValue() <= 0xffffffff)
12570 weight = CW_Constant;
12577 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12578 /// with another that has more specific requirements based on the type of the
12579 /// corresponding operand.
12580 const char *X86TargetLowering::
12581 LowerXConstraint(EVT ConstraintVT) const {
12582 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12583 // 'f' like normal targets.
12584 if (ConstraintVT.isFloatingPoint()) {
12585 if (Subtarget->hasXMMInt())
12587 if (Subtarget->hasXMM())
12591 return TargetLowering::LowerXConstraint(ConstraintVT);
12594 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12595 /// vector. If it is invalid, don't add anything to Ops.
12596 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12597 std::string &Constraint,
12598 std::vector<SDValue>&Ops,
12599 SelectionDAG &DAG) const {
12600 SDValue Result(0, 0);
12602 // Only support length 1 constraints for now.
12603 if (Constraint.length() > 1) return;
12605 char ConstraintLetter = Constraint[0];
12606 switch (ConstraintLetter) {
12609 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12610 if (C->getZExtValue() <= 31) {
12611 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12617 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12618 if (C->getZExtValue() <= 63) {
12619 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12625 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12626 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12627 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12633 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12634 if (C->getZExtValue() <= 255) {
12635 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12641 // 32-bit signed value
12642 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12643 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12644 C->getSExtValue())) {
12645 // Widen to 64 bits here to get it sign extended.
12646 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12649 // FIXME gcc accepts some relocatable values here too, but only in certain
12650 // memory models; it's complicated.
12655 // 32-bit unsigned value
12656 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12657 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12658 C->getZExtValue())) {
12659 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12663 // FIXME gcc accepts some relocatable values here too, but only in certain
12664 // memory models; it's complicated.
12668 // Literal immediates are always ok.
12669 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12670 // Widen to 64 bits here to get it sign extended.
12671 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12675 // In any sort of PIC mode addresses need to be computed at runtime by
12676 // adding in a register or some sort of table lookup. These can't
12677 // be used as immediates.
12678 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12681 // If we are in non-pic codegen mode, we allow the address of a global (with
12682 // an optional displacement) to be used with 'i'.
12683 GlobalAddressSDNode *GA = 0;
12684 int64_t Offset = 0;
12686 // Match either (GA), (GA+C), (GA+C1+C2), etc.
12688 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12689 Offset += GA->getOffset();
12691 } else if (Op.getOpcode() == ISD::ADD) {
12692 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12693 Offset += C->getZExtValue();
12694 Op = Op.getOperand(0);
12697 } else if (Op.getOpcode() == ISD::SUB) {
12698 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12699 Offset += -C->getZExtValue();
12700 Op = Op.getOperand(0);
12705 // Otherwise, this isn't something we can handle, reject it.
12709 const GlobalValue *GV = GA->getGlobal();
12710 // If we require an extra load to get this address, as in PIC mode, we
12711 // can't accept it.
12712 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12713 getTargetMachine())))
12716 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12717 GA->getValueType(0), Offset);
12722 if (Result.getNode()) {
12723 Ops.push_back(Result);
12726 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12729 std::vector<unsigned> X86TargetLowering::
12730 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12732 if (Constraint.size() == 1) {
12733 // FIXME: not handling fp-stack yet!
12734 switch (Constraint[0]) { // GCC X86 Constraint Letters
12735 default: break; // Unknown constraint letter
12736 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12737 if (Subtarget->is64Bit()) {
12738 if (VT == MVT::i32)
12739 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12740 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12741 X86::R10D,X86::R11D,X86::R12D,
12742 X86::R13D,X86::R14D,X86::R15D,
12743 X86::EBP, X86::ESP, 0);
12744 else if (VT == MVT::i16)
12745 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
12746 X86::SI, X86::DI, X86::R8W,X86::R9W,
12747 X86::R10W,X86::R11W,X86::R12W,
12748 X86::R13W,X86::R14W,X86::R15W,
12749 X86::BP, X86::SP, 0);
12750 else if (VT == MVT::i8)
12751 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
12752 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12753 X86::R10B,X86::R11B,X86::R12B,
12754 X86::R13B,X86::R14B,X86::R15B,
12755 X86::BPL, X86::SPL, 0);
12757 else if (VT == MVT::i64)
12758 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12759 X86::RSI, X86::RDI, X86::R8, X86::R9,
12760 X86::R10, X86::R11, X86::R12,
12761 X86::R13, X86::R14, X86::R15,
12762 X86::RBP, X86::RSP, 0);
12766 // 32-bit fallthrough
12767 case 'Q': // Q_REGS
12768 if (VT == MVT::i32)
12769 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12770 else if (VT == MVT::i16)
12771 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12772 else if (VT == MVT::i8)
12773 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12774 else if (VT == MVT::i64)
12775 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12780 return std::vector<unsigned>();
12783 std::pair<unsigned, const TargetRegisterClass*>
12784 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12786 // First, see if this is a constraint that directly corresponds to an LLVM
12788 if (Constraint.size() == 1) {
12789 // GCC Constraint Letters
12790 switch (Constraint[0]) {
12792 case 'r': // GENERAL_REGS
12793 case 'l': // INDEX_REGS
12795 return std::make_pair(0U, X86::GR8RegisterClass);
12796 if (VT == MVT::i16)
12797 return std::make_pair(0U, X86::GR16RegisterClass);
12798 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
12799 return std::make_pair(0U, X86::GR32RegisterClass);
12800 return std::make_pair(0U, X86::GR64RegisterClass);
12801 case 'R': // LEGACY_REGS
12803 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12804 if (VT == MVT::i16)
12805 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12806 if (VT == MVT::i32 || !Subtarget->is64Bit())
12807 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12808 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12809 case 'f': // FP Stack registers.
12810 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12811 // value to the correct fpstack register class.
12812 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12813 return std::make_pair(0U, X86::RFP32RegisterClass);
12814 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12815 return std::make_pair(0U, X86::RFP64RegisterClass);
12816 return std::make_pair(0U, X86::RFP80RegisterClass);
12817 case 'y': // MMX_REGS if MMX allowed.
12818 if (!Subtarget->hasMMX()) break;
12819 return std::make_pair(0U, X86::VR64RegisterClass);
12820 case 'Y': // SSE_REGS if SSE2 allowed
12821 if (!Subtarget->hasXMMInt()) break;
12823 case 'x': // SSE_REGS if SSE1 allowed
12824 if (!Subtarget->hasXMM()) break;
12826 switch (VT.getSimpleVT().SimpleTy) {
12828 // Scalar SSE types.
12831 return std::make_pair(0U, X86::FR32RegisterClass);
12834 return std::make_pair(0U, X86::FR64RegisterClass);
12842 return std::make_pair(0U, X86::VR128RegisterClass);
12848 // Use the default implementation in TargetLowering to convert the register
12849 // constraint into a member of a register class.
12850 std::pair<unsigned, const TargetRegisterClass*> Res;
12851 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12853 // Not found as a standard register?
12854 if (Res.second == 0) {
12855 // Map st(0) -> st(7) -> ST0
12856 if (Constraint.size() == 7 && Constraint[0] == '{' &&
12857 tolower(Constraint[1]) == 's' &&
12858 tolower(Constraint[2]) == 't' &&
12859 Constraint[3] == '(' &&
12860 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12861 Constraint[5] == ')' &&
12862 Constraint[6] == '}') {
12864 Res.first = X86::ST0+Constraint[4]-'0';
12865 Res.second = X86::RFP80RegisterClass;
12869 // GCC allows "st(0)" to be called just plain "st".
12870 if (StringRef("{st}").equals_lower(Constraint)) {
12871 Res.first = X86::ST0;
12872 Res.second = X86::RFP80RegisterClass;
12877 if (StringRef("{flags}").equals_lower(Constraint)) {
12878 Res.first = X86::EFLAGS;
12879 Res.second = X86::CCRRegisterClass;
12883 // 'A' means EAX + EDX.
12884 if (Constraint == "A") {
12885 Res.first = X86::EAX;
12886 Res.second = X86::GR32_ADRegisterClass;
12892 // Otherwise, check to see if this is a register class of the wrong value
12893 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12894 // turn into {ax},{dx}.
12895 if (Res.second->hasType(VT))
12896 return Res; // Correct type already, nothing to do.
12898 // All of the single-register GCC register classes map their values onto
12899 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
12900 // really want an 8-bit or 32-bit register, map to the appropriate register
12901 // class and return the appropriate register.
12902 if (Res.second == X86::GR16RegisterClass) {
12903 if (VT == MVT::i8) {
12904 unsigned DestReg = 0;
12905 switch (Res.first) {
12907 case X86::AX: DestReg = X86::AL; break;
12908 case X86::DX: DestReg = X86::DL; break;
12909 case X86::CX: DestReg = X86::CL; break;
12910 case X86::BX: DestReg = X86::BL; break;
12913 Res.first = DestReg;
12914 Res.second = X86::GR8RegisterClass;
12916 } else if (VT == MVT::i32) {
12917 unsigned DestReg = 0;
12918 switch (Res.first) {
12920 case X86::AX: DestReg = X86::EAX; break;
12921 case X86::DX: DestReg = X86::EDX; break;
12922 case X86::CX: DestReg = X86::ECX; break;
12923 case X86::BX: DestReg = X86::EBX; break;
12924 case X86::SI: DestReg = X86::ESI; break;
12925 case X86::DI: DestReg = X86::EDI; break;
12926 case X86::BP: DestReg = X86::EBP; break;
12927 case X86::SP: DestReg = X86::ESP; break;
12930 Res.first = DestReg;
12931 Res.second = X86::GR32RegisterClass;
12933 } else if (VT == MVT::i64) {
12934 unsigned DestReg = 0;
12935 switch (Res.first) {
12937 case X86::AX: DestReg = X86::RAX; break;
12938 case X86::DX: DestReg = X86::RDX; break;
12939 case X86::CX: DestReg = X86::RCX; break;
12940 case X86::BX: DestReg = X86::RBX; break;
12941 case X86::SI: DestReg = X86::RSI; break;
12942 case X86::DI: DestReg = X86::RDI; break;
12943 case X86::BP: DestReg = X86::RBP; break;
12944 case X86::SP: DestReg = X86::RSP; break;
12947 Res.first = DestReg;
12948 Res.second = X86::GR64RegisterClass;
12951 } else if (Res.second == X86::FR32RegisterClass ||
12952 Res.second == X86::FR64RegisterClass ||
12953 Res.second == X86::VR128RegisterClass) {
12954 // Handle references to XMM physical registers that got mapped into the
12955 // wrong class. This can happen with constraints like {xmm0} where the
12956 // target independent register mapper will just pick the first match it can
12957 // find, ignoring the required type.
12958 if (VT == MVT::f32)
12959 Res.second = X86::FR32RegisterClass;
12960 else if (VT == MVT::f64)
12961 Res.second = X86::FR64RegisterClass;
12962 else if (X86::VR128RegisterClass->hasType(VT))
12963 Res.second = X86::VR128RegisterClass;