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();
6703 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6704 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6705 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6707 MachinePointerInfo::getFixedStack(SSFI),
6709 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6712 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6714 SelectionDAG &DAG) const {
6716 DebugLoc DL = Op.getDebugLoc();
6718 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6720 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6722 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6724 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6726 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6727 MachineMemOperand *MMO =
6728 DAG.getMachineFunction()
6729 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6730 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6732 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6733 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6735 Tys, Ops, array_lengthof(Ops),
6739 Chain = Result.getValue(1);
6740 SDValue InFlag = Result.getValue(2);
6742 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6743 // shouldn't be necessary except that RFP cannot be live across
6744 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6745 MachineFunction &MF = DAG.getMachineFunction();
6746 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6747 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6748 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6749 Tys = DAG.getVTList(MVT::Other);
6751 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6753 MachineMemOperand *MMO =
6754 DAG.getMachineFunction()
6755 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6756 MachineMemOperand::MOStore, SSFISize, SSFISize);
6758 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6759 Ops, array_lengthof(Ops),
6760 Op.getValueType(), MMO);
6761 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6762 MachinePointerInfo::getFixedStack(SSFI),
6769 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6770 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6771 SelectionDAG &DAG) const {
6772 // This algorithm is not obvious. Here it is in C code, more or less:
6774 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6775 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6776 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6778 // Copy ints to xmm registers.
6779 __m128i xh = _mm_cvtsi32_si128( hi );
6780 __m128i xl = _mm_cvtsi32_si128( lo );
6782 // Combine into low half of a single xmm register.
6783 __m128i x = _mm_unpacklo_epi32( xh, xl );
6787 // Merge in appropriate exponents to give the integer bits the right
6789 x = _mm_unpacklo_epi32( x, exp );
6791 // Subtract away the biases to deal with the IEEE-754 double precision
6793 d = _mm_sub_pd( (__m128d) x, bias );
6795 // All conversions up to here are exact. The correctly rounded result is
6796 // calculated using the current rounding mode using the following
6798 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6799 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6800 // store doesn't really need to be here (except
6801 // maybe to zero the other double)
6806 DebugLoc dl = Op.getDebugLoc();
6807 LLVMContext *Context = DAG.getContext();
6809 // Build some magic constants.
6810 std::vector<Constant*> CV0;
6811 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6812 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6813 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6814 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6815 Constant *C0 = ConstantVector::get(CV0);
6816 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6818 std::vector<Constant*> CV1;
6820 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6822 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6823 Constant *C1 = ConstantVector::get(CV1);
6824 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6826 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6827 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6829 DAG.getIntPtrConstant(1)));
6830 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6831 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6833 DAG.getIntPtrConstant(0)));
6834 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6835 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6836 MachinePointerInfo::getConstantPool(),
6838 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6839 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6840 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6841 MachinePointerInfo::getConstantPool(),
6843 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6845 // Add the halves; easiest way is to swap them into another reg first.
6846 int ShufMask[2] = { 1, -1 };
6847 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6848 DAG.getUNDEF(MVT::v2f64), ShufMask);
6849 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6850 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6851 DAG.getIntPtrConstant(0));
6854 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6855 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6856 SelectionDAG &DAG) const {
6857 DebugLoc dl = Op.getDebugLoc();
6858 // FP constant to bias correct the final result.
6859 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6862 // Load the 32-bit value into an XMM register.
6863 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6864 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6866 DAG.getIntPtrConstant(0)));
6868 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6869 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6870 DAG.getIntPtrConstant(0));
6872 // Or the load with the bias.
6873 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6874 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6875 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6877 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6878 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6879 MVT::v2f64, Bias)));
6880 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6881 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6882 DAG.getIntPtrConstant(0));
6884 // Subtract the bias.
6885 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6887 // Handle final rounding.
6888 EVT DestVT = Op.getValueType();
6890 if (DestVT.bitsLT(MVT::f64)) {
6891 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6892 DAG.getIntPtrConstant(0));
6893 } else if (DestVT.bitsGT(MVT::f64)) {
6894 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6897 // Handle final rounding.
6901 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6902 SelectionDAG &DAG) const {
6903 SDValue N0 = Op.getOperand(0);
6904 DebugLoc dl = Op.getDebugLoc();
6906 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6907 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6908 // the optimization here.
6909 if (DAG.SignBitIsZero(N0))
6910 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6912 EVT SrcVT = N0.getValueType();
6913 EVT DstVT = Op.getValueType();
6914 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6915 return LowerUINT_TO_FP_i64(Op, DAG);
6916 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6917 return LowerUINT_TO_FP_i32(Op, DAG);
6919 // Make a 64-bit buffer, and use it to build an FILD.
6920 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6921 if (SrcVT == MVT::i32) {
6922 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6923 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6924 getPointerTy(), StackSlot, WordOff);
6925 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6926 StackSlot, MachinePointerInfo(),
6928 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6929 OffsetSlot, MachinePointerInfo(),
6931 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6935 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6936 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6937 StackSlot, MachinePointerInfo(),
6939 // For i64 source, we need to add the appropriate power of 2 if the input
6940 // was negative. This is the same as the optimization in
6941 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6942 // we must be careful to do the computation in x87 extended precision, not
6943 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6944 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6945 MachineMemOperand *MMO =
6946 DAG.getMachineFunction()
6947 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6948 MachineMemOperand::MOLoad, 8, 8);
6950 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6951 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6952 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6955 APInt FF(32, 0x5F800000ULL);
6957 // Check whether the sign bit is set.
6958 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6959 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6962 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6963 SDValue FudgePtr = DAG.getConstantPool(
6964 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6967 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6968 SDValue Zero = DAG.getIntPtrConstant(0);
6969 SDValue Four = DAG.getIntPtrConstant(4);
6970 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6972 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6974 // Load the value out, extending it from f32 to f80.
6975 // FIXME: Avoid the extend by constructing the right constant pool?
6976 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
6977 FudgePtr, MachinePointerInfo::getConstantPool(),
6978 MVT::f32, false, false, 4);
6979 // Extend everything to 80 bits to force it to be done on x87.
6980 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6981 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6984 std::pair<SDValue,SDValue> X86TargetLowering::
6985 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6986 DebugLoc DL = Op.getDebugLoc();
6988 EVT DstTy = Op.getValueType();
6991 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6995 assert(DstTy.getSimpleVT() <= MVT::i64 &&
6996 DstTy.getSimpleVT() >= MVT::i16 &&
6997 "Unknown FP_TO_SINT to lower!");
6999 // These are really Legal.
7000 if (DstTy == MVT::i32 &&
7001 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7002 return std::make_pair(SDValue(), SDValue());
7003 if (Subtarget->is64Bit() &&
7004 DstTy == MVT::i64 &&
7005 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7006 return std::make_pair(SDValue(), SDValue());
7008 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7010 MachineFunction &MF = DAG.getMachineFunction();
7011 unsigned MemSize = DstTy.getSizeInBits()/8;
7012 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7013 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7018 switch (DstTy.getSimpleVT().SimpleTy) {
7019 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7020 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7021 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7022 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7025 SDValue Chain = DAG.getEntryNode();
7026 SDValue Value = Op.getOperand(0);
7027 EVT TheVT = Op.getOperand(0).getValueType();
7028 if (isScalarFPTypeInSSEReg(TheVT)) {
7029 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7030 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7031 MachinePointerInfo::getFixedStack(SSFI),
7033 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7035 Chain, StackSlot, DAG.getValueType(TheVT)
7038 MachineMemOperand *MMO =
7039 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7040 MachineMemOperand::MOLoad, MemSize, MemSize);
7041 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7043 Chain = Value.getValue(1);
7044 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7045 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7048 MachineMemOperand *MMO =
7049 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7050 MachineMemOperand::MOStore, MemSize, MemSize);
7052 // Build the FP_TO_INT*_IN_MEM
7053 SDValue Ops[] = { Chain, Value, StackSlot };
7054 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7055 Ops, 3, DstTy, MMO);
7057 return std::make_pair(FIST, StackSlot);
7060 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7061 SelectionDAG &DAG) const {
7062 if (Op.getValueType().isVector())
7065 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7066 SDValue FIST = Vals.first, StackSlot = Vals.second;
7067 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7068 if (FIST.getNode() == 0) return Op;
7071 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7072 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7075 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7076 SelectionDAG &DAG) const {
7077 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7078 SDValue FIST = Vals.first, StackSlot = Vals.second;
7079 assert(FIST.getNode() && "Unexpected failure");
7082 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7083 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7086 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7087 SelectionDAG &DAG) const {
7088 LLVMContext *Context = DAG.getContext();
7089 DebugLoc dl = Op.getDebugLoc();
7090 EVT VT = Op.getValueType();
7093 EltVT = VT.getVectorElementType();
7094 std::vector<Constant*> CV;
7095 if (EltVT == MVT::f64) {
7096 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7100 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7106 Constant *C = ConstantVector::get(CV);
7107 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7108 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7109 MachinePointerInfo::getConstantPool(),
7111 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7114 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7115 LLVMContext *Context = DAG.getContext();
7116 DebugLoc dl = Op.getDebugLoc();
7117 EVT VT = Op.getValueType();
7120 EltVT = VT.getVectorElementType();
7121 std::vector<Constant*> CV;
7122 if (EltVT == MVT::f64) {
7123 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7127 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7133 Constant *C = ConstantVector::get(CV);
7134 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7135 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7136 MachinePointerInfo::getConstantPool(),
7138 if (VT.isVector()) {
7139 return DAG.getNode(ISD::BITCAST, dl, VT,
7140 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7141 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7143 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7145 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7149 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7150 LLVMContext *Context = DAG.getContext();
7151 SDValue Op0 = Op.getOperand(0);
7152 SDValue Op1 = Op.getOperand(1);
7153 DebugLoc dl = Op.getDebugLoc();
7154 EVT VT = Op.getValueType();
7155 EVT SrcVT = Op1.getValueType();
7157 // If second operand is smaller, extend it first.
7158 if (SrcVT.bitsLT(VT)) {
7159 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7162 // And if it is bigger, shrink it first.
7163 if (SrcVT.bitsGT(VT)) {
7164 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7168 // At this point the operands and the result should have the same
7169 // type, and that won't be f80 since that is not custom lowered.
7171 // First get the sign bit of second operand.
7172 std::vector<Constant*> CV;
7173 if (SrcVT == MVT::f64) {
7174 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7175 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7177 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7178 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7179 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7180 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7182 Constant *C = ConstantVector::get(CV);
7183 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7184 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7185 MachinePointerInfo::getConstantPool(),
7187 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7189 // Shift sign bit right or left if the two operands have different types.
7190 if (SrcVT.bitsGT(VT)) {
7191 // Op0 is MVT::f32, Op1 is MVT::f64.
7192 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7193 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7194 DAG.getConstant(32, MVT::i32));
7195 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7196 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7197 DAG.getIntPtrConstant(0));
7200 // Clear first operand sign bit.
7202 if (VT == MVT::f64) {
7203 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7204 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7206 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7207 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7208 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7209 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7211 C = ConstantVector::get(CV);
7212 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7213 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7214 MachinePointerInfo::getConstantPool(),
7216 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7218 // Or the value with the sign bit.
7219 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7222 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7223 SDValue N0 = Op.getOperand(0);
7224 DebugLoc dl = Op.getDebugLoc();
7225 EVT VT = Op.getValueType();
7227 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7228 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7229 DAG.getConstant(1, VT));
7230 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7233 /// Emit nodes that will be selected as "test Op0,Op0", or something
7235 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7236 SelectionDAG &DAG) const {
7237 DebugLoc dl = Op.getDebugLoc();
7239 // CF and OF aren't always set the way we want. Determine which
7240 // of these we need.
7241 bool NeedCF = false;
7242 bool NeedOF = false;
7245 case X86::COND_A: case X86::COND_AE:
7246 case X86::COND_B: case X86::COND_BE:
7249 case X86::COND_G: case X86::COND_GE:
7250 case X86::COND_L: case X86::COND_LE:
7251 case X86::COND_O: case X86::COND_NO:
7256 // See if we can use the EFLAGS value from the operand instead of
7257 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7258 // we prove that the arithmetic won't overflow, we can't use OF or CF.
7259 if (Op.getResNo() != 0 || NeedOF || NeedCF)
7260 // Emit a CMP with 0, which is the TEST pattern.
7261 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7262 DAG.getConstant(0, Op.getValueType()));
7264 unsigned Opcode = 0;
7265 unsigned NumOperands = 0;
7266 switch (Op.getNode()->getOpcode()) {
7268 // Due to an isel shortcoming, be conservative if this add is likely to be
7269 // selected as part of a load-modify-store instruction. When the root node
7270 // in a match is a store, isel doesn't know how to remap non-chain non-flag
7271 // uses of other nodes in the match, such as the ADD in this case. This
7272 // leads to the ADD being left around and reselected, with the result being
7273 // two adds in the output. Alas, even if none our users are stores, that
7274 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
7275 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
7276 // climbing the DAG back to the root, and it doesn't seem to be worth the
7278 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7279 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7280 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7283 if (ConstantSDNode *C =
7284 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7285 // An add of one will be selected as an INC.
7286 if (C->getAPIntValue() == 1) {
7287 Opcode = X86ISD::INC;
7292 // An add of negative one (subtract of one) will be selected as a DEC.
7293 if (C->getAPIntValue().isAllOnesValue()) {
7294 Opcode = X86ISD::DEC;
7300 // Otherwise use a regular EFLAGS-setting add.
7301 Opcode = X86ISD::ADD;
7305 // If the primary and result isn't used, don't bother using X86ISD::AND,
7306 // because a TEST instruction will be better.
7307 bool NonFlagUse = false;
7308 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7309 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7311 unsigned UOpNo = UI.getOperandNo();
7312 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7313 // Look pass truncate.
7314 UOpNo = User->use_begin().getOperandNo();
7315 User = *User->use_begin();
7318 if (User->getOpcode() != ISD::BRCOND &&
7319 User->getOpcode() != ISD::SETCC &&
7320 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7333 // Due to the ISEL shortcoming noted above, be conservative if this op is
7334 // likely to be selected as part of a load-modify-store instruction.
7335 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7336 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7337 if (UI->getOpcode() == ISD::STORE)
7340 // Otherwise use a regular EFLAGS-setting instruction.
7341 switch (Op.getNode()->getOpcode()) {
7342 default: llvm_unreachable("unexpected operator!");
7343 case ISD::SUB: Opcode = X86ISD::SUB; break;
7344 case ISD::OR: Opcode = X86ISD::OR; break;
7345 case ISD::XOR: Opcode = X86ISD::XOR; break;
7346 case ISD::AND: Opcode = X86ISD::AND; break;
7358 return SDValue(Op.getNode(), 1);
7365 // Emit a CMP with 0, which is the TEST pattern.
7366 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7367 DAG.getConstant(0, Op.getValueType()));
7369 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7370 SmallVector<SDValue, 4> Ops;
7371 for (unsigned i = 0; i != NumOperands; ++i)
7372 Ops.push_back(Op.getOperand(i));
7374 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7375 DAG.ReplaceAllUsesWith(Op, New);
7376 return SDValue(New.getNode(), 1);
7379 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7381 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7382 SelectionDAG &DAG) const {
7383 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7384 if (C->getAPIntValue() == 0)
7385 return EmitTest(Op0, X86CC, DAG);
7387 DebugLoc dl = Op0.getDebugLoc();
7388 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7391 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7392 /// if it's possible.
7393 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7394 DebugLoc dl, SelectionDAG &DAG) const {
7395 SDValue Op0 = And.getOperand(0);
7396 SDValue Op1 = And.getOperand(1);
7397 if (Op0.getOpcode() == ISD::TRUNCATE)
7398 Op0 = Op0.getOperand(0);
7399 if (Op1.getOpcode() == ISD::TRUNCATE)
7400 Op1 = Op1.getOperand(0);
7403 if (Op1.getOpcode() == ISD::SHL)
7404 std::swap(Op0, Op1);
7405 if (Op0.getOpcode() == ISD::SHL) {
7406 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7407 if (And00C->getZExtValue() == 1) {
7408 // If we looked past a truncate, check that it's only truncating away
7410 unsigned BitWidth = Op0.getValueSizeInBits();
7411 unsigned AndBitWidth = And.getValueSizeInBits();
7412 if (BitWidth > AndBitWidth) {
7413 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7414 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7415 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7419 RHS = Op0.getOperand(1);
7421 } else if (Op1.getOpcode() == ISD::Constant) {
7422 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7423 SDValue AndLHS = Op0;
7424 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7425 LHS = AndLHS.getOperand(0);
7426 RHS = AndLHS.getOperand(1);
7430 if (LHS.getNode()) {
7431 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
7432 // instruction. Since the shift amount is in-range-or-undefined, we know
7433 // that doing a bittest on the i32 value is ok. We extend to i32 because
7434 // the encoding for the i16 version is larger than the i32 version.
7435 // Also promote i16 to i32 for performance / code size reason.
7436 if (LHS.getValueType() == MVT::i8 ||
7437 LHS.getValueType() == MVT::i16)
7438 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7440 // If the operand types disagree, extend the shift amount to match. Since
7441 // BT ignores high bits (like shifts) we can use anyextend.
7442 if (LHS.getValueType() != RHS.getValueType())
7443 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7445 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7446 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7447 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7448 DAG.getConstant(Cond, MVT::i8), BT);
7454 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7455 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7456 SDValue Op0 = Op.getOperand(0);
7457 SDValue Op1 = Op.getOperand(1);
7458 DebugLoc dl = Op.getDebugLoc();
7459 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7461 // Optimize to BT if possible.
7462 // Lower (X & (1 << N)) == 0 to BT(X, N).
7463 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7464 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7465 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7466 Op1.getOpcode() == ISD::Constant &&
7467 cast<ConstantSDNode>(Op1)->isNullValue() &&
7468 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7469 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7470 if (NewSetCC.getNode())
7474 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
7476 if (Op1.getOpcode() == ISD::Constant &&
7477 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7478 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7479 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7481 // If the input is a setcc, then reuse the input setcc or use a new one with
7482 // the inverted condition.
7483 if (Op0.getOpcode() == X86ISD::SETCC) {
7484 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7485 bool Invert = (CC == ISD::SETNE) ^
7486 cast<ConstantSDNode>(Op1)->isNullValue();
7487 if (!Invert) return Op0;
7489 CCode = X86::GetOppositeBranchCondition(CCode);
7490 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7491 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7495 bool isFP = Op1.getValueType().isFloatingPoint();
7496 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7497 if (X86CC == X86::COND_INVALID)
7500 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7501 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7502 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7505 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7507 SDValue Op0 = Op.getOperand(0);
7508 SDValue Op1 = Op.getOperand(1);
7509 SDValue CC = Op.getOperand(2);
7510 EVT VT = Op.getValueType();
7511 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7512 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7513 DebugLoc dl = Op.getDebugLoc();
7517 EVT VT0 = Op0.getValueType();
7518 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7519 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7522 switch (SetCCOpcode) {
7525 case ISD::SETEQ: SSECC = 0; break;
7527 case ISD::SETGT: Swap = true; // Fallthrough
7529 case ISD::SETOLT: SSECC = 1; break;
7531 case ISD::SETGE: Swap = true; // Fallthrough
7533 case ISD::SETOLE: SSECC = 2; break;
7534 case ISD::SETUO: SSECC = 3; break;
7536 case ISD::SETNE: SSECC = 4; break;
7537 case ISD::SETULE: Swap = true;
7538 case ISD::SETUGE: SSECC = 5; break;
7539 case ISD::SETULT: Swap = true;
7540 case ISD::SETUGT: SSECC = 6; break;
7541 case ISD::SETO: SSECC = 7; break;
7544 std::swap(Op0, Op1);
7546 // In the two special cases we can't handle, emit two comparisons.
7548 if (SetCCOpcode == ISD::SETUEQ) {
7550 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7551 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7552 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7554 else if (SetCCOpcode == ISD::SETONE) {
7556 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7557 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7558 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7560 llvm_unreachable("Illegal FP comparison");
7562 // Handle all other FP comparisons here.
7563 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7566 // We are handling one of the integer comparisons here. Since SSE only has
7567 // GT and EQ comparisons for integer, swapping operands and multiple
7568 // operations may be required for some comparisons.
7569 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7570 bool Swap = false, Invert = false, FlipSigns = false;
7572 switch (VT.getSimpleVT().SimpleTy) {
7574 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7575 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7576 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7577 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7580 switch (SetCCOpcode) {
7582 case ISD::SETNE: Invert = true;
7583 case ISD::SETEQ: Opc = EQOpc; break;
7584 case ISD::SETLT: Swap = true;
7585 case ISD::SETGT: Opc = GTOpc; break;
7586 case ISD::SETGE: Swap = true;
7587 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7588 case ISD::SETULT: Swap = true;
7589 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7590 case ISD::SETUGE: Swap = true;
7591 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7594 std::swap(Op0, Op1);
7596 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7597 // bits of the inputs before performing those operations.
7599 EVT EltVT = VT.getVectorElementType();
7600 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7602 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7603 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7605 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7606 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7609 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7611 // If the logical-not of the result is required, perform that now.
7613 Result = DAG.getNOT(dl, Result, VT);
7618 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7619 static bool isX86LogicalCmp(SDValue Op) {
7620 unsigned Opc = Op.getNode()->getOpcode();
7621 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7623 if (Op.getResNo() == 1 &&
7624 (Opc == X86ISD::ADD ||
7625 Opc == X86ISD::SUB ||
7626 Opc == X86ISD::ADC ||
7627 Opc == X86ISD::SBB ||
7628 Opc == X86ISD::SMUL ||
7629 Opc == X86ISD::UMUL ||
7630 Opc == X86ISD::INC ||
7631 Opc == X86ISD::DEC ||
7632 Opc == X86ISD::OR ||
7633 Opc == X86ISD::XOR ||
7634 Opc == X86ISD::AND))
7637 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7643 static bool isZero(SDValue V) {
7644 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7645 return C && C->isNullValue();
7648 static bool isAllOnes(SDValue V) {
7649 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7650 return C && C->isAllOnesValue();
7653 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7654 bool addTest = true;
7655 SDValue Cond = Op.getOperand(0);
7656 SDValue Op1 = Op.getOperand(1);
7657 SDValue Op2 = Op.getOperand(2);
7658 DebugLoc DL = Op.getDebugLoc();
7661 if (Cond.getOpcode() == ISD::SETCC) {
7662 SDValue NewCond = LowerSETCC(Cond, DAG);
7663 if (NewCond.getNode())
7667 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7668 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7669 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7670 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7671 if (Cond.getOpcode() == X86ISD::SETCC &&
7672 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7673 isZero(Cond.getOperand(1).getOperand(1))) {
7674 SDValue Cmp = Cond.getOperand(1);
7676 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7678 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7679 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7680 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7682 SDValue CmpOp0 = Cmp.getOperand(0);
7683 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7684 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7686 SDValue Res = // Res = 0 or -1.
7687 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7688 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7690 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7691 Res = DAG.getNOT(DL, Res, Res.getValueType());
7693 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7694 if (N2C == 0 || !N2C->isNullValue())
7695 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7700 // Look past (and (setcc_carry (cmp ...)), 1).
7701 if (Cond.getOpcode() == ISD::AND &&
7702 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7703 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7704 if (C && C->getAPIntValue() == 1)
7705 Cond = Cond.getOperand(0);
7708 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7709 // setting operand in place of the X86ISD::SETCC.
7710 if (Cond.getOpcode() == X86ISD::SETCC ||
7711 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7712 CC = Cond.getOperand(0);
7714 SDValue Cmp = Cond.getOperand(1);
7715 unsigned Opc = Cmp.getOpcode();
7716 EVT VT = Op.getValueType();
7718 bool IllegalFPCMov = false;
7719 if (VT.isFloatingPoint() && !VT.isVector() &&
7720 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7721 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7723 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7724 Opc == X86ISD::BT) { // FIXME
7731 // Look pass the truncate.
7732 if (Cond.getOpcode() == ISD::TRUNCATE)
7733 Cond = Cond.getOperand(0);
7735 // We know the result of AND is compared against zero. Try to match
7737 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7738 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7739 if (NewSetCC.getNode()) {
7740 CC = NewSetCC.getOperand(0);
7741 Cond = NewSetCC.getOperand(1);
7748 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7749 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7752 // a < b ? -1 : 0 -> RES = ~setcc_carry
7753 // a < b ? 0 : -1 -> RES = setcc_carry
7754 // a >= b ? -1 : 0 -> RES = setcc_carry
7755 // a >= b ? 0 : -1 -> RES = ~setcc_carry
7756 if (Cond.getOpcode() == X86ISD::CMP) {
7757 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7759 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7760 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7761 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7762 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7763 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7764 return DAG.getNOT(DL, Res, Res.getValueType());
7769 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7770 // condition is true.
7771 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7772 SDValue Ops[] = { Op2, Op1, CC, Cond };
7773 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7776 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7777 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7778 // from the AND / OR.
7779 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7780 Opc = Op.getOpcode();
7781 if (Opc != ISD::OR && Opc != ISD::AND)
7783 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7784 Op.getOperand(0).hasOneUse() &&
7785 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7786 Op.getOperand(1).hasOneUse());
7789 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7790 // 1 and that the SETCC node has a single use.
7791 static bool isXor1OfSetCC(SDValue Op) {
7792 if (Op.getOpcode() != ISD::XOR)
7794 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7795 if (N1C && N1C->getAPIntValue() == 1) {
7796 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7797 Op.getOperand(0).hasOneUse();
7802 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7803 bool addTest = true;
7804 SDValue Chain = Op.getOperand(0);
7805 SDValue Cond = Op.getOperand(1);
7806 SDValue Dest = Op.getOperand(2);
7807 DebugLoc dl = Op.getDebugLoc();
7810 if (Cond.getOpcode() == ISD::SETCC) {
7811 SDValue NewCond = LowerSETCC(Cond, DAG);
7812 if (NewCond.getNode())
7816 // FIXME: LowerXALUO doesn't handle these!!
7817 else if (Cond.getOpcode() == X86ISD::ADD ||
7818 Cond.getOpcode() == X86ISD::SUB ||
7819 Cond.getOpcode() == X86ISD::SMUL ||
7820 Cond.getOpcode() == X86ISD::UMUL)
7821 Cond = LowerXALUO(Cond, DAG);
7824 // Look pass (and (setcc_carry (cmp ...)), 1).
7825 if (Cond.getOpcode() == ISD::AND &&
7826 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7827 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7828 if (C && C->getAPIntValue() == 1)
7829 Cond = Cond.getOperand(0);
7832 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7833 // setting operand in place of the X86ISD::SETCC.
7834 if (Cond.getOpcode() == X86ISD::SETCC ||
7835 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7836 CC = Cond.getOperand(0);
7838 SDValue Cmp = Cond.getOperand(1);
7839 unsigned Opc = Cmp.getOpcode();
7840 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7841 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7845 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7849 // These can only come from an arithmetic instruction with overflow,
7850 // e.g. SADDO, UADDO.
7851 Cond = Cond.getNode()->getOperand(1);
7858 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7859 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7860 if (CondOpc == ISD::OR) {
7861 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7862 // two branches instead of an explicit OR instruction with a
7864 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7865 isX86LogicalCmp(Cmp)) {
7866 CC = Cond.getOperand(0).getOperand(0);
7867 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7868 Chain, Dest, CC, Cmp);
7869 CC = Cond.getOperand(1).getOperand(0);
7873 } else { // ISD::AND
7874 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7875 // two branches instead of an explicit AND instruction with a
7876 // separate test. However, we only do this if this block doesn't
7877 // have a fall-through edge, because this requires an explicit
7878 // jmp when the condition is false.
7879 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7880 isX86LogicalCmp(Cmp) &&
7881 Op.getNode()->hasOneUse()) {
7882 X86::CondCode CCode =
7883 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7884 CCode = X86::GetOppositeBranchCondition(CCode);
7885 CC = DAG.getConstant(CCode, MVT::i8);
7886 SDNode *User = *Op.getNode()->use_begin();
7887 // Look for an unconditional branch following this conditional branch.
7888 // We need this because we need to reverse the successors in order
7889 // to implement FCMP_OEQ.
7890 if (User->getOpcode() == ISD::BR) {
7891 SDValue FalseBB = User->getOperand(1);
7893 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7894 assert(NewBR == User);
7898 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7899 Chain, Dest, CC, Cmp);
7900 X86::CondCode CCode =
7901 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7902 CCode = X86::GetOppositeBranchCondition(CCode);
7903 CC = DAG.getConstant(CCode, MVT::i8);
7909 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7910 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7911 // It should be transformed during dag combiner except when the condition
7912 // is set by a arithmetics with overflow node.
7913 X86::CondCode CCode =
7914 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7915 CCode = X86::GetOppositeBranchCondition(CCode);
7916 CC = DAG.getConstant(CCode, MVT::i8);
7917 Cond = Cond.getOperand(0).getOperand(1);
7923 // Look pass the truncate.
7924 if (Cond.getOpcode() == ISD::TRUNCATE)
7925 Cond = Cond.getOperand(0);
7927 // We know the result of AND is compared against zero. Try to match
7929 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7930 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7931 if (NewSetCC.getNode()) {
7932 CC = NewSetCC.getOperand(0);
7933 Cond = NewSetCC.getOperand(1);
7940 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7941 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7943 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7944 Chain, Dest, CC, Cond);
7948 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7949 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7950 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7951 // that the guard pages used by the OS virtual memory manager are allocated in
7952 // correct sequence.
7954 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7955 SelectionDAG &DAG) const {
7956 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7957 "This should be used only on Windows targets");
7958 assert(!Subtarget->isTargetEnvMacho());
7959 DebugLoc dl = Op.getDebugLoc();
7962 SDValue Chain = Op.getOperand(0);
7963 SDValue Size = Op.getOperand(1);
7964 // FIXME: Ensure alignment here
7968 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7969 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
7971 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
7972 Flag = Chain.getValue(1);
7974 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7976 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7977 Flag = Chain.getValue(1);
7979 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7981 SDValue Ops1[2] = { Chain.getValue(0), Chain };
7982 return DAG.getMergeValues(Ops1, 2, dl);
7985 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7986 MachineFunction &MF = DAG.getMachineFunction();
7987 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7989 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7990 DebugLoc DL = Op.getDebugLoc();
7992 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7993 // vastart just stores the address of the VarArgsFrameIndex slot into the
7994 // memory location argument.
7995 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7997 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7998 MachinePointerInfo(SV), false, false, 0);
8002 // gp_offset (0 - 6 * 8)
8003 // fp_offset (48 - 48 + 8 * 16)
8004 // overflow_arg_area (point to parameters coming in memory).
8006 SmallVector<SDValue, 8> MemOps;
8007 SDValue FIN = Op.getOperand(1);
8009 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8010 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8012 FIN, MachinePointerInfo(SV), false, false, 0);
8013 MemOps.push_back(Store);
8016 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8017 FIN, DAG.getIntPtrConstant(4));
8018 Store = DAG.getStore(Op.getOperand(0), DL,
8019 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8021 FIN, MachinePointerInfo(SV, 4), false, false, 0);
8022 MemOps.push_back(Store);
8024 // Store ptr to overflow_arg_area
8025 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8026 FIN, DAG.getIntPtrConstant(4));
8027 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8029 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8030 MachinePointerInfo(SV, 8),
8032 MemOps.push_back(Store);
8034 // Store ptr to reg_save_area.
8035 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8036 FIN, DAG.getIntPtrConstant(8));
8037 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8039 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8040 MachinePointerInfo(SV, 16), false, false, 0);
8041 MemOps.push_back(Store);
8042 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8043 &MemOps[0], MemOps.size());
8046 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8047 assert(Subtarget->is64Bit() &&
8048 "LowerVAARG only handles 64-bit va_arg!");
8049 assert((Subtarget->isTargetLinux() ||
8050 Subtarget->isTargetDarwin()) &&
8051 "Unhandled target in LowerVAARG");
8052 assert(Op.getNode()->getNumOperands() == 4);
8053 SDValue Chain = Op.getOperand(0);
8054 SDValue SrcPtr = Op.getOperand(1);
8055 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8056 unsigned Align = Op.getConstantOperandVal(3);
8057 DebugLoc dl = Op.getDebugLoc();
8059 EVT ArgVT = Op.getNode()->getValueType(0);
8060 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8061 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8064 // Decide which area this value should be read from.
8065 // TODO: Implement the AMD64 ABI in its entirety. This simple
8066 // selection mechanism works only for the basic types.
8067 if (ArgVT == MVT::f80) {
8068 llvm_unreachable("va_arg for f80 not yet implemented");
8069 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8070 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
8071 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8072 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
8074 llvm_unreachable("Unhandled argument type in LowerVAARG");
8078 // Sanity Check: Make sure using fp_offset makes sense.
8079 assert(!UseSoftFloat &&
8080 !(DAG.getMachineFunction()
8081 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8082 Subtarget->hasXMM());
8085 // Insert VAARG_64 node into the DAG
8086 // VAARG_64 returns two values: Variable Argument Address, Chain
8087 SmallVector<SDValue, 11> InstOps;
8088 InstOps.push_back(Chain);
8089 InstOps.push_back(SrcPtr);
8090 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8091 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8092 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8093 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8094 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8095 VTs, &InstOps[0], InstOps.size(),
8097 MachinePointerInfo(SV),
8102 Chain = VAARG.getValue(1);
8104 // Load the next argument and return it
8105 return DAG.getLoad(ArgVT, dl,
8108 MachinePointerInfo(),
8112 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8113 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8114 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8115 SDValue Chain = Op.getOperand(0);
8116 SDValue DstPtr = Op.getOperand(1);
8117 SDValue SrcPtr = Op.getOperand(2);
8118 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8119 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8120 DebugLoc DL = Op.getDebugLoc();
8122 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8123 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8125 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8129 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8130 DebugLoc dl = Op.getDebugLoc();
8131 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8133 default: return SDValue(); // Don't custom lower most intrinsics.
8134 // Comparison intrinsics.
8135 case Intrinsic::x86_sse_comieq_ss:
8136 case Intrinsic::x86_sse_comilt_ss:
8137 case Intrinsic::x86_sse_comile_ss:
8138 case Intrinsic::x86_sse_comigt_ss:
8139 case Intrinsic::x86_sse_comige_ss:
8140 case Intrinsic::x86_sse_comineq_ss:
8141 case Intrinsic::x86_sse_ucomieq_ss:
8142 case Intrinsic::x86_sse_ucomilt_ss:
8143 case Intrinsic::x86_sse_ucomile_ss:
8144 case Intrinsic::x86_sse_ucomigt_ss:
8145 case Intrinsic::x86_sse_ucomige_ss:
8146 case Intrinsic::x86_sse_ucomineq_ss:
8147 case Intrinsic::x86_sse2_comieq_sd:
8148 case Intrinsic::x86_sse2_comilt_sd:
8149 case Intrinsic::x86_sse2_comile_sd:
8150 case Intrinsic::x86_sse2_comigt_sd:
8151 case Intrinsic::x86_sse2_comige_sd:
8152 case Intrinsic::x86_sse2_comineq_sd:
8153 case Intrinsic::x86_sse2_ucomieq_sd:
8154 case Intrinsic::x86_sse2_ucomilt_sd:
8155 case Intrinsic::x86_sse2_ucomile_sd:
8156 case Intrinsic::x86_sse2_ucomigt_sd:
8157 case Intrinsic::x86_sse2_ucomige_sd:
8158 case Intrinsic::x86_sse2_ucomineq_sd: {
8160 ISD::CondCode CC = ISD::SETCC_INVALID;
8163 case Intrinsic::x86_sse_comieq_ss:
8164 case Intrinsic::x86_sse2_comieq_sd:
8168 case Intrinsic::x86_sse_comilt_ss:
8169 case Intrinsic::x86_sse2_comilt_sd:
8173 case Intrinsic::x86_sse_comile_ss:
8174 case Intrinsic::x86_sse2_comile_sd:
8178 case Intrinsic::x86_sse_comigt_ss:
8179 case Intrinsic::x86_sse2_comigt_sd:
8183 case Intrinsic::x86_sse_comige_ss:
8184 case Intrinsic::x86_sse2_comige_sd:
8188 case Intrinsic::x86_sse_comineq_ss:
8189 case Intrinsic::x86_sse2_comineq_sd:
8193 case Intrinsic::x86_sse_ucomieq_ss:
8194 case Intrinsic::x86_sse2_ucomieq_sd:
8195 Opc = X86ISD::UCOMI;
8198 case Intrinsic::x86_sse_ucomilt_ss:
8199 case Intrinsic::x86_sse2_ucomilt_sd:
8200 Opc = X86ISD::UCOMI;
8203 case Intrinsic::x86_sse_ucomile_ss:
8204 case Intrinsic::x86_sse2_ucomile_sd:
8205 Opc = X86ISD::UCOMI;
8208 case Intrinsic::x86_sse_ucomigt_ss:
8209 case Intrinsic::x86_sse2_ucomigt_sd:
8210 Opc = X86ISD::UCOMI;
8213 case Intrinsic::x86_sse_ucomige_ss:
8214 case Intrinsic::x86_sse2_ucomige_sd:
8215 Opc = X86ISD::UCOMI;
8218 case Intrinsic::x86_sse_ucomineq_ss:
8219 case Intrinsic::x86_sse2_ucomineq_sd:
8220 Opc = X86ISD::UCOMI;
8225 SDValue LHS = Op.getOperand(1);
8226 SDValue RHS = Op.getOperand(2);
8227 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8228 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8229 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8230 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8231 DAG.getConstant(X86CC, MVT::i8), Cond);
8232 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8234 // ptest and testp intrinsics. The intrinsic these come from are designed to
8235 // return an integer value, not just an instruction so lower it to the ptest
8236 // or testp pattern and a setcc for the result.
8237 case Intrinsic::x86_sse41_ptestz:
8238 case Intrinsic::x86_sse41_ptestc:
8239 case Intrinsic::x86_sse41_ptestnzc:
8240 case Intrinsic::x86_avx_ptestz_256:
8241 case Intrinsic::x86_avx_ptestc_256:
8242 case Intrinsic::x86_avx_ptestnzc_256:
8243 case Intrinsic::x86_avx_vtestz_ps:
8244 case Intrinsic::x86_avx_vtestc_ps:
8245 case Intrinsic::x86_avx_vtestnzc_ps:
8246 case Intrinsic::x86_avx_vtestz_pd:
8247 case Intrinsic::x86_avx_vtestc_pd:
8248 case Intrinsic::x86_avx_vtestnzc_pd:
8249 case Intrinsic::x86_avx_vtestz_ps_256:
8250 case Intrinsic::x86_avx_vtestc_ps_256:
8251 case Intrinsic::x86_avx_vtestnzc_ps_256:
8252 case Intrinsic::x86_avx_vtestz_pd_256:
8253 case Intrinsic::x86_avx_vtestc_pd_256:
8254 case Intrinsic::x86_avx_vtestnzc_pd_256: {
8255 bool IsTestPacked = false;
8258 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8259 case Intrinsic::x86_avx_vtestz_ps:
8260 case Intrinsic::x86_avx_vtestz_pd:
8261 case Intrinsic::x86_avx_vtestz_ps_256:
8262 case Intrinsic::x86_avx_vtestz_pd_256:
8263 IsTestPacked = true; // Fallthrough
8264 case Intrinsic::x86_sse41_ptestz:
8265 case Intrinsic::x86_avx_ptestz_256:
8267 X86CC = X86::COND_E;
8269 case Intrinsic::x86_avx_vtestc_ps:
8270 case Intrinsic::x86_avx_vtestc_pd:
8271 case Intrinsic::x86_avx_vtestc_ps_256:
8272 case Intrinsic::x86_avx_vtestc_pd_256:
8273 IsTestPacked = true; // Fallthrough
8274 case Intrinsic::x86_sse41_ptestc:
8275 case Intrinsic::x86_avx_ptestc_256:
8277 X86CC = X86::COND_B;
8279 case Intrinsic::x86_avx_vtestnzc_ps:
8280 case Intrinsic::x86_avx_vtestnzc_pd:
8281 case Intrinsic::x86_avx_vtestnzc_ps_256:
8282 case Intrinsic::x86_avx_vtestnzc_pd_256:
8283 IsTestPacked = true; // Fallthrough
8284 case Intrinsic::x86_sse41_ptestnzc:
8285 case Intrinsic::x86_avx_ptestnzc_256:
8287 X86CC = X86::COND_A;
8291 SDValue LHS = Op.getOperand(1);
8292 SDValue RHS = Op.getOperand(2);
8293 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8294 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8295 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8296 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8297 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8300 // Fix vector shift instructions where the last operand is a non-immediate
8302 case Intrinsic::x86_sse2_pslli_w:
8303 case Intrinsic::x86_sse2_pslli_d:
8304 case Intrinsic::x86_sse2_pslli_q:
8305 case Intrinsic::x86_sse2_psrli_w:
8306 case Intrinsic::x86_sse2_psrli_d:
8307 case Intrinsic::x86_sse2_psrli_q:
8308 case Intrinsic::x86_sse2_psrai_w:
8309 case Intrinsic::x86_sse2_psrai_d:
8310 case Intrinsic::x86_mmx_pslli_w:
8311 case Intrinsic::x86_mmx_pslli_d:
8312 case Intrinsic::x86_mmx_pslli_q:
8313 case Intrinsic::x86_mmx_psrli_w:
8314 case Intrinsic::x86_mmx_psrli_d:
8315 case Intrinsic::x86_mmx_psrli_q:
8316 case Intrinsic::x86_mmx_psrai_w:
8317 case Intrinsic::x86_mmx_psrai_d: {
8318 SDValue ShAmt = Op.getOperand(2);
8319 if (isa<ConstantSDNode>(ShAmt))
8322 unsigned NewIntNo = 0;
8323 EVT ShAmtVT = MVT::v4i32;
8325 case Intrinsic::x86_sse2_pslli_w:
8326 NewIntNo = Intrinsic::x86_sse2_psll_w;
8328 case Intrinsic::x86_sse2_pslli_d:
8329 NewIntNo = Intrinsic::x86_sse2_psll_d;
8331 case Intrinsic::x86_sse2_pslli_q:
8332 NewIntNo = Intrinsic::x86_sse2_psll_q;
8334 case Intrinsic::x86_sse2_psrli_w:
8335 NewIntNo = Intrinsic::x86_sse2_psrl_w;
8337 case Intrinsic::x86_sse2_psrli_d:
8338 NewIntNo = Intrinsic::x86_sse2_psrl_d;
8340 case Intrinsic::x86_sse2_psrli_q:
8341 NewIntNo = Intrinsic::x86_sse2_psrl_q;
8343 case Intrinsic::x86_sse2_psrai_w:
8344 NewIntNo = Intrinsic::x86_sse2_psra_w;
8346 case Intrinsic::x86_sse2_psrai_d:
8347 NewIntNo = Intrinsic::x86_sse2_psra_d;
8350 ShAmtVT = MVT::v2i32;
8352 case Intrinsic::x86_mmx_pslli_w:
8353 NewIntNo = Intrinsic::x86_mmx_psll_w;
8355 case Intrinsic::x86_mmx_pslli_d:
8356 NewIntNo = Intrinsic::x86_mmx_psll_d;
8358 case Intrinsic::x86_mmx_pslli_q:
8359 NewIntNo = Intrinsic::x86_mmx_psll_q;
8361 case Intrinsic::x86_mmx_psrli_w:
8362 NewIntNo = Intrinsic::x86_mmx_psrl_w;
8364 case Intrinsic::x86_mmx_psrli_d:
8365 NewIntNo = Intrinsic::x86_mmx_psrl_d;
8367 case Intrinsic::x86_mmx_psrli_q:
8368 NewIntNo = Intrinsic::x86_mmx_psrl_q;
8370 case Intrinsic::x86_mmx_psrai_w:
8371 NewIntNo = Intrinsic::x86_mmx_psra_w;
8373 case Intrinsic::x86_mmx_psrai_d:
8374 NewIntNo = Intrinsic::x86_mmx_psra_d;
8376 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8382 // The vector shift intrinsics with scalars uses 32b shift amounts but
8383 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8387 ShOps[1] = DAG.getConstant(0, MVT::i32);
8388 if (ShAmtVT == MVT::v4i32) {
8389 ShOps[2] = DAG.getUNDEF(MVT::i32);
8390 ShOps[3] = DAG.getUNDEF(MVT::i32);
8391 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8393 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8394 // FIXME this must be lowered to get rid of the invalid type.
8397 EVT VT = Op.getValueType();
8398 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8399 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8400 DAG.getConstant(NewIntNo, MVT::i32),
8401 Op.getOperand(1), ShAmt);
8406 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8407 SelectionDAG &DAG) const {
8408 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8409 MFI->setReturnAddressIsTaken(true);
8411 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8412 DebugLoc dl = Op.getDebugLoc();
8415 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8417 DAG.getConstant(TD->getPointerSize(),
8418 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8419 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8420 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8422 MachinePointerInfo(), false, false, 0);
8425 // Just load the return address.
8426 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8427 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8428 RetAddrFI, MachinePointerInfo(), false, false, 0);
8431 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8432 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8433 MFI->setFrameAddressIsTaken(true);
8435 EVT VT = Op.getValueType();
8436 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
8437 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8438 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8439 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8441 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8442 MachinePointerInfo(),
8447 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8448 SelectionDAG &DAG) const {
8449 return DAG.getIntPtrConstant(2*TD->getPointerSize());
8452 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8453 MachineFunction &MF = DAG.getMachineFunction();
8454 SDValue Chain = Op.getOperand(0);
8455 SDValue Offset = Op.getOperand(1);
8456 SDValue Handler = Op.getOperand(2);
8457 DebugLoc dl = Op.getDebugLoc();
8459 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8460 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8462 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8464 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8465 DAG.getIntPtrConstant(TD->getPointerSize()));
8466 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8467 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8469 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8470 MF.getRegInfo().addLiveOut(StoreAddrReg);
8472 return DAG.getNode(X86ISD::EH_RETURN, dl,
8474 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8477 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8478 SelectionDAG &DAG) const {
8479 SDValue Root = Op.getOperand(0);
8480 SDValue Trmp = Op.getOperand(1); // trampoline
8481 SDValue FPtr = Op.getOperand(2); // nested function
8482 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8483 DebugLoc dl = Op.getDebugLoc();
8485 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8487 if (Subtarget->is64Bit()) {
8488 SDValue OutChains[6];
8490 // Large code-model.
8491 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8492 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8494 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8495 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8497 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8499 // Load the pointer to the nested function into R11.
8500 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8501 SDValue Addr = Trmp;
8502 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8503 Addr, MachinePointerInfo(TrmpAddr),
8506 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8507 DAG.getConstant(2, MVT::i64));
8508 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8509 MachinePointerInfo(TrmpAddr, 2),
8512 // Load the 'nest' parameter value into R10.
8513 // R10 is specified in X86CallingConv.td
8514 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8515 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8516 DAG.getConstant(10, MVT::i64));
8517 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8518 Addr, MachinePointerInfo(TrmpAddr, 10),
8521 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8522 DAG.getConstant(12, MVT::i64));
8523 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8524 MachinePointerInfo(TrmpAddr, 12),
8527 // Jump to the nested function.
8528 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8529 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8530 DAG.getConstant(20, MVT::i64));
8531 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8532 Addr, MachinePointerInfo(TrmpAddr, 20),
8535 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8536 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8537 DAG.getConstant(22, MVT::i64));
8538 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8539 MachinePointerInfo(TrmpAddr, 22),
8543 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8544 return DAG.getMergeValues(Ops, 2, dl);
8546 const Function *Func =
8547 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8548 CallingConv::ID CC = Func->getCallingConv();
8553 llvm_unreachable("Unsupported calling convention");
8554 case CallingConv::C:
8555 case CallingConv::X86_StdCall: {
8556 // Pass 'nest' parameter in ECX.
8557 // Must be kept in sync with X86CallingConv.td
8560 // Check that ECX wasn't needed by an 'inreg' parameter.
8561 const FunctionType *FTy = Func->getFunctionType();
8562 const AttrListPtr &Attrs = Func->getAttributes();
8564 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8565 unsigned InRegCount = 0;
8568 for (FunctionType::param_iterator I = FTy->param_begin(),
8569 E = FTy->param_end(); I != E; ++I, ++Idx)
8570 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8571 // FIXME: should only count parameters that are lowered to integers.
8572 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8574 if (InRegCount > 2) {
8575 report_fatal_error("Nest register in use - reduce number of inreg"
8581 case CallingConv::X86_FastCall:
8582 case CallingConv::X86_ThisCall:
8583 case CallingConv::Fast:
8584 // Pass 'nest' parameter in EAX.
8585 // Must be kept in sync with X86CallingConv.td
8590 SDValue OutChains[4];
8593 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8594 DAG.getConstant(10, MVT::i32));
8595 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8597 // This is storing the opcode for MOV32ri.
8598 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8599 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8600 OutChains[0] = DAG.getStore(Root, dl,
8601 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8602 Trmp, MachinePointerInfo(TrmpAddr),
8605 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8606 DAG.getConstant(1, MVT::i32));
8607 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8608 MachinePointerInfo(TrmpAddr, 1),
8611 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8612 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8613 DAG.getConstant(5, MVT::i32));
8614 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8615 MachinePointerInfo(TrmpAddr, 5),
8618 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8619 DAG.getConstant(6, MVT::i32));
8620 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8621 MachinePointerInfo(TrmpAddr, 6),
8625 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8626 return DAG.getMergeValues(Ops, 2, dl);
8630 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8631 SelectionDAG &DAG) const {
8633 The rounding mode is in bits 11:10 of FPSR, and has the following
8640 FLT_ROUNDS, on the other hand, expects the following:
8647 To perform the conversion, we do:
8648 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8651 MachineFunction &MF = DAG.getMachineFunction();
8652 const TargetMachine &TM = MF.getTarget();
8653 const TargetFrameLowering &TFI = *TM.getFrameLowering();
8654 unsigned StackAlignment = TFI.getStackAlignment();
8655 EVT VT = Op.getValueType();
8656 DebugLoc DL = Op.getDebugLoc();
8658 // Save FP Control Word to stack slot
8659 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8660 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8663 MachineMemOperand *MMO =
8664 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8665 MachineMemOperand::MOStore, 2, 2);
8667 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8668 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8669 DAG.getVTList(MVT::Other),
8670 Ops, 2, MVT::i16, MMO);
8672 // Load FP Control Word from stack slot
8673 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8674 MachinePointerInfo(), false, false, 0);
8676 // Transform as necessary
8678 DAG.getNode(ISD::SRL, DL, MVT::i16,
8679 DAG.getNode(ISD::AND, DL, MVT::i16,
8680 CWD, DAG.getConstant(0x800, MVT::i16)),
8681 DAG.getConstant(11, MVT::i8));
8683 DAG.getNode(ISD::SRL, DL, MVT::i16,
8684 DAG.getNode(ISD::AND, DL, MVT::i16,
8685 CWD, DAG.getConstant(0x400, MVT::i16)),
8686 DAG.getConstant(9, MVT::i8));
8689 DAG.getNode(ISD::AND, DL, MVT::i16,
8690 DAG.getNode(ISD::ADD, DL, MVT::i16,
8691 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8692 DAG.getConstant(1, MVT::i16)),
8693 DAG.getConstant(3, MVT::i16));
8696 return DAG.getNode((VT.getSizeInBits() < 16 ?
8697 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8700 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8701 EVT VT = Op.getValueType();
8703 unsigned NumBits = VT.getSizeInBits();
8704 DebugLoc dl = Op.getDebugLoc();
8706 Op = Op.getOperand(0);
8707 if (VT == MVT::i8) {
8708 // Zero extend to i32 since there is not an i8 bsr.
8710 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8713 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8714 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8715 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8717 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8720 DAG.getConstant(NumBits+NumBits-1, OpVT),
8721 DAG.getConstant(X86::COND_E, MVT::i8),
8724 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8726 // Finally xor with NumBits-1.
8727 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8730 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8734 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8735 EVT VT = Op.getValueType();
8737 unsigned NumBits = VT.getSizeInBits();
8738 DebugLoc dl = Op.getDebugLoc();
8740 Op = Op.getOperand(0);
8741 if (VT == MVT::i8) {
8743 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8746 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8747 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8748 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8750 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8753 DAG.getConstant(NumBits, OpVT),
8754 DAG.getConstant(X86::COND_E, MVT::i8),
8757 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8760 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8764 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8765 EVT VT = Op.getValueType();
8766 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8767 DebugLoc dl = Op.getDebugLoc();
8769 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8770 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8771 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8772 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8773 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8775 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8776 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8777 // return AloBlo + AloBhi + AhiBlo;
8779 SDValue A = Op.getOperand(0);
8780 SDValue B = Op.getOperand(1);
8782 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8783 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8784 A, DAG.getConstant(32, MVT::i32));
8785 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8786 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8787 B, DAG.getConstant(32, MVT::i32));
8788 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8789 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8791 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8792 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8794 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8795 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8797 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8798 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8799 AloBhi, DAG.getConstant(32, MVT::i32));
8800 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8801 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8802 AhiBlo, DAG.getConstant(32, MVT::i32));
8803 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8804 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8808 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8810 EVT VT = Op.getValueType();
8811 DebugLoc dl = Op.getDebugLoc();
8812 SDValue R = Op.getOperand(0);
8813 SDValue Amt = Op.getOperand(1);
8815 LLVMContext *Context = DAG.getContext();
8818 if (!Subtarget->hasSSE2()) return SDValue();
8820 // Optimize shl/srl/sra with constant shift amount.
8821 if (isSplatVector(Amt.getNode())) {
8822 SDValue SclrAmt = Amt->getOperand(0);
8823 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8824 uint64_t ShiftAmt = C->getZExtValue();
8826 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8827 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8828 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8829 R, DAG.getConstant(ShiftAmt, MVT::i32));
8831 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
8832 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8833 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8834 R, DAG.getConstant(ShiftAmt, MVT::i32));
8836 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
8837 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8838 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8839 R, DAG.getConstant(ShiftAmt, MVT::i32));
8841 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
8842 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8843 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8844 R, DAG.getConstant(ShiftAmt, MVT::i32));
8846 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
8847 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8848 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8849 R, DAG.getConstant(ShiftAmt, MVT::i32));
8851 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
8852 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8853 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8854 R, DAG.getConstant(ShiftAmt, MVT::i32));
8856 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
8857 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8858 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8859 R, DAG.getConstant(ShiftAmt, MVT::i32));
8861 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
8862 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8863 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8864 R, DAG.getConstant(ShiftAmt, MVT::i32));
8868 // Lower SHL with variable shift amount.
8869 // Cannot lower SHL without SSE4.1 or later.
8870 if (!Subtarget->hasSSE41()) return SDValue();
8872 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
8873 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8874 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8875 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8877 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8879 std::vector<Constant*> CV(4, CI);
8880 Constant *C = ConstantVector::get(CV);
8881 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8882 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8883 MachinePointerInfo::getConstantPool(),
8886 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8887 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8888 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8889 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8891 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
8893 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8894 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8895 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8897 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8898 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8900 std::vector<Constant*> CVM1(16, CM1);
8901 std::vector<Constant*> CVM2(16, CM2);
8902 Constant *C = ConstantVector::get(CVM1);
8903 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8904 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8905 MachinePointerInfo::getConstantPool(),
8908 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8909 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8910 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8911 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8912 DAG.getConstant(4, MVT::i32));
8913 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8915 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8917 C = ConstantVector::get(CVM2);
8918 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8919 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8920 MachinePointerInfo::getConstantPool(),
8923 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8924 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8925 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8926 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8927 DAG.getConstant(2, MVT::i32));
8928 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8930 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8932 // return pblendv(r, r+r, a);
8933 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8934 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8940 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8941 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8942 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8943 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8944 // has only one use.
8945 SDNode *N = Op.getNode();
8946 SDValue LHS = N->getOperand(0);
8947 SDValue RHS = N->getOperand(1);
8948 unsigned BaseOp = 0;
8950 DebugLoc DL = Op.getDebugLoc();
8951 switch (Op.getOpcode()) {
8952 default: llvm_unreachable("Unknown ovf instruction!");
8954 // A subtract of one will be selected as a INC. Note that INC doesn't
8955 // set CF, so we can't do this for UADDO.
8956 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8958 BaseOp = X86ISD::INC;
8962 BaseOp = X86ISD::ADD;
8966 BaseOp = X86ISD::ADD;
8970 // A subtract of one will be selected as a DEC. Note that DEC doesn't
8971 // set CF, so we can't do this for USUBO.
8972 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8974 BaseOp = X86ISD::DEC;
8978 BaseOp = X86ISD::SUB;
8982 BaseOp = X86ISD::SUB;
8986 BaseOp = X86ISD::SMUL;
8989 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8990 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8992 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8995 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8996 DAG.getConstant(X86::COND_O, MVT::i32),
8997 SDValue(Sum.getNode(), 2));
8999 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9004 // Also sets EFLAGS.
9005 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9006 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9009 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9010 DAG.getConstant(Cond, MVT::i32),
9011 SDValue(Sum.getNode(), 1));
9013 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9017 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9018 DebugLoc dl = Op.getDebugLoc();
9020 if (!Subtarget->hasSSE2()) {
9021 SDValue Chain = Op.getOperand(0);
9022 SDValue Zero = DAG.getConstant(0,
9023 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9025 DAG.getRegister(X86::ESP, MVT::i32), // Base
9026 DAG.getTargetConstant(1, MVT::i8), // Scale
9027 DAG.getRegister(0, MVT::i32), // Index
9028 DAG.getTargetConstant(0, MVT::i32), // Disp
9029 DAG.getRegister(0, MVT::i32), // Segment.
9034 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9035 array_lengthof(Ops));
9036 return SDValue(Res, 0);
9039 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9041 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9043 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9044 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9045 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9046 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9048 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9049 if (!Op1 && !Op2 && !Op3 && Op4)
9050 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9052 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9053 if (Op1 && !Op2 && !Op3 && !Op4)
9054 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9056 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9058 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9061 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9062 EVT T = Op.getValueType();
9063 DebugLoc DL = Op.getDebugLoc();
9066 switch(T.getSimpleVT().SimpleTy) {
9068 assert(false && "Invalid value type!");
9069 case MVT::i8: Reg = X86::AL; size = 1; break;
9070 case MVT::i16: Reg = X86::AX; size = 2; break;
9071 case MVT::i32: Reg = X86::EAX; size = 4; break;
9073 assert(Subtarget->is64Bit() && "Node not type legal!");
9074 Reg = X86::RAX; size = 8;
9077 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9078 Op.getOperand(2), SDValue());
9079 SDValue Ops[] = { cpIn.getValue(0),
9082 DAG.getTargetConstant(size, MVT::i8),
9084 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9085 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9086 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9089 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9093 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9094 SelectionDAG &DAG) const {
9095 assert(Subtarget->is64Bit() && "Result not type legalized?");
9096 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9097 SDValue TheChain = Op.getOperand(0);
9098 DebugLoc dl = Op.getDebugLoc();
9099 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9100 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9101 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9103 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9104 DAG.getConstant(32, MVT::i8));
9106 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9109 return DAG.getMergeValues(Ops, 2, dl);
9112 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9113 SelectionDAG &DAG) const {
9114 EVT SrcVT = Op.getOperand(0).getValueType();
9115 EVT DstVT = Op.getValueType();
9116 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9117 Subtarget->hasMMX() && "Unexpected custom BITCAST");
9118 assert((DstVT == MVT::i64 ||
9119 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9120 "Unexpected custom BITCAST");
9121 // i64 <=> MMX conversions are Legal.
9122 if (SrcVT==MVT::i64 && DstVT.isVector())
9124 if (DstVT==MVT::i64 && SrcVT.isVector())
9126 // MMX <=> MMX conversions are Legal.
9127 if (SrcVT.isVector() && DstVT.isVector())
9129 // All other conversions need to be expanded.
9133 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9134 SDNode *Node = Op.getNode();
9135 DebugLoc dl = Node->getDebugLoc();
9136 EVT T = Node->getValueType(0);
9137 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9138 DAG.getConstant(0, T), Node->getOperand(2));
9139 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9140 cast<AtomicSDNode>(Node)->getMemoryVT(),
9141 Node->getOperand(0),
9142 Node->getOperand(1), negOp,
9143 cast<AtomicSDNode>(Node)->getSrcValue(),
9144 cast<AtomicSDNode>(Node)->getAlignment());
9147 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9148 EVT VT = Op.getNode()->getValueType(0);
9150 // Let legalize expand this if it isn't a legal type yet.
9151 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9154 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9157 bool ExtraOp = false;
9158 switch (Op.getOpcode()) {
9159 default: assert(0 && "Invalid code");
9160 case ISD::ADDC: Opc = X86ISD::ADD; break;
9161 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9162 case ISD::SUBC: Opc = X86ISD::SUB; break;
9163 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9167 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9169 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9170 Op.getOperand(1), Op.getOperand(2));
9173 /// LowerOperation - Provide custom lowering hooks for some operations.
9175 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9176 switch (Op.getOpcode()) {
9177 default: llvm_unreachable("Should not custom lower this!");
9178 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
9179 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
9180 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
9181 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
9182 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
9183 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
9184 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9185 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9186 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
9187 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
9188 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
9189 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9190 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9191 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9192 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
9193 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
9194 case ISD::SHL_PARTS:
9195 case ISD::SRA_PARTS:
9196 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
9197 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
9198 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
9199 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
9200 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
9201 case ISD::FABS: return LowerFABS(Op, DAG);
9202 case ISD::FNEG: return LowerFNEG(Op, DAG);
9203 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
9204 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
9205 case ISD::SETCC: return LowerSETCC(Op, DAG);
9206 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
9207 case ISD::SELECT: return LowerSELECT(Op, DAG);
9208 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
9209 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
9210 case ISD::VASTART: return LowerVASTART(Op, DAG);
9211 case ISD::VAARG: return LowerVAARG(Op, DAG);
9212 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
9213 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9214 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9215 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9216 case ISD::FRAME_TO_ARGS_OFFSET:
9217 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9218 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9219 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
9220 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
9221 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9222 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
9223 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
9224 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
9227 case ISD::SHL: return LowerShift(Op, DAG);
9233 case ISD::UMULO: return LowerXALUO(Op, DAG);
9234 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
9235 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
9239 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9243 void X86TargetLowering::
9244 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9245 SelectionDAG &DAG, unsigned NewOp) const {
9246 EVT T = Node->getValueType(0);
9247 DebugLoc dl = Node->getDebugLoc();
9248 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9250 SDValue Chain = Node->getOperand(0);
9251 SDValue In1 = Node->getOperand(1);
9252 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9253 Node->getOperand(2), DAG.getIntPtrConstant(0));
9254 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9255 Node->getOperand(2), DAG.getIntPtrConstant(1));
9256 SDValue Ops[] = { Chain, In1, In2L, In2H };
9257 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9259 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9260 cast<MemSDNode>(Node)->getMemOperand());
9261 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9262 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9263 Results.push_back(Result.getValue(2));
9266 /// ReplaceNodeResults - Replace a node with an illegal result type
9267 /// with a new node built out of custom code.
9268 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9269 SmallVectorImpl<SDValue>&Results,
9270 SelectionDAG &DAG) const {
9271 DebugLoc dl = N->getDebugLoc();
9272 switch (N->getOpcode()) {
9274 assert(false && "Do not know how to custom type legalize this operation!");
9280 // We don't want to expand or promote these.
9282 case ISD::FP_TO_SINT: {
9283 std::pair<SDValue,SDValue> Vals =
9284 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9285 SDValue FIST = Vals.first, StackSlot = Vals.second;
9286 if (FIST.getNode() != 0) {
9287 EVT VT = N->getValueType(0);
9288 // Return a load from the stack slot.
9289 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9290 MachinePointerInfo(), false, false, 0));
9294 case ISD::READCYCLECOUNTER: {
9295 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9296 SDValue TheChain = N->getOperand(0);
9297 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9298 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9300 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9302 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9303 SDValue Ops[] = { eax, edx };
9304 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9305 Results.push_back(edx.getValue(1));
9308 case ISD::ATOMIC_CMP_SWAP: {
9309 EVT T = N->getValueType(0);
9310 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9311 SDValue cpInL, cpInH;
9312 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9313 DAG.getConstant(0, MVT::i32));
9314 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9315 DAG.getConstant(1, MVT::i32));
9316 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9317 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9319 SDValue swapInL, swapInH;
9320 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9321 DAG.getConstant(0, MVT::i32));
9322 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9323 DAG.getConstant(1, MVT::i32));
9324 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9326 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9327 swapInL.getValue(1));
9328 SDValue Ops[] = { swapInH.getValue(0),
9330 swapInH.getValue(1) };
9331 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9332 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9333 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9335 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9336 MVT::i32, Result.getValue(1));
9337 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9338 MVT::i32, cpOutL.getValue(2));
9339 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9340 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9341 Results.push_back(cpOutH.getValue(1));
9344 case ISD::ATOMIC_LOAD_ADD:
9345 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9347 case ISD::ATOMIC_LOAD_AND:
9348 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9350 case ISD::ATOMIC_LOAD_NAND:
9351 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9353 case ISD::ATOMIC_LOAD_OR:
9354 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9356 case ISD::ATOMIC_LOAD_SUB:
9357 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9359 case ISD::ATOMIC_LOAD_XOR:
9360 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9362 case ISD::ATOMIC_SWAP:
9363 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9368 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9370 default: return NULL;
9371 case X86ISD::BSF: return "X86ISD::BSF";
9372 case X86ISD::BSR: return "X86ISD::BSR";
9373 case X86ISD::SHLD: return "X86ISD::SHLD";
9374 case X86ISD::SHRD: return "X86ISD::SHRD";
9375 case X86ISD::FAND: return "X86ISD::FAND";
9376 case X86ISD::FOR: return "X86ISD::FOR";
9377 case X86ISD::FXOR: return "X86ISD::FXOR";
9378 case X86ISD::FSRL: return "X86ISD::FSRL";
9379 case X86ISD::FILD: return "X86ISD::FILD";
9380 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
9381 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9382 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9383 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9384 case X86ISD::FLD: return "X86ISD::FLD";
9385 case X86ISD::FST: return "X86ISD::FST";
9386 case X86ISD::CALL: return "X86ISD::CALL";
9387 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
9388 case X86ISD::BT: return "X86ISD::BT";
9389 case X86ISD::CMP: return "X86ISD::CMP";
9390 case X86ISD::COMI: return "X86ISD::COMI";
9391 case X86ISD::UCOMI: return "X86ISD::UCOMI";
9392 case X86ISD::SETCC: return "X86ISD::SETCC";
9393 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
9394 case X86ISD::CMOV: return "X86ISD::CMOV";
9395 case X86ISD::BRCOND: return "X86ISD::BRCOND";
9396 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
9397 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
9398 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
9399 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
9400 case X86ISD::Wrapper: return "X86ISD::Wrapper";
9401 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
9402 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
9403 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
9404 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
9405 case X86ISD::PINSRB: return "X86ISD::PINSRB";
9406 case X86ISD::PINSRW: return "X86ISD::PINSRW";
9407 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
9408 case X86ISD::PANDN: return "X86ISD::PANDN";
9409 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
9410 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
9411 case X86ISD::PSIGND: return "X86ISD::PSIGND";
9412 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB";
9413 case X86ISD::FMAX: return "X86ISD::FMAX";
9414 case X86ISD::FMIN: return "X86ISD::FMIN";
9415 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
9416 case X86ISD::FRCP: return "X86ISD::FRCP";
9417 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
9418 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
9419 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
9420 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
9421 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
9422 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
9423 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
9424 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
9425 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
9426 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
9427 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
9428 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
9429 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
9430 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
9431 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
9432 case X86ISD::VSHL: return "X86ISD::VSHL";
9433 case X86ISD::VSRL: return "X86ISD::VSRL";
9434 case X86ISD::CMPPD: return "X86ISD::CMPPD";
9435 case X86ISD::CMPPS: return "X86ISD::CMPPS";
9436 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
9437 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
9438 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
9439 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
9440 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
9441 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
9442 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
9443 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
9444 case X86ISD::ADD: return "X86ISD::ADD";
9445 case X86ISD::SUB: return "X86ISD::SUB";
9446 case X86ISD::ADC: return "X86ISD::ADC";
9447 case X86ISD::SBB: return "X86ISD::SBB";
9448 case X86ISD::SMUL: return "X86ISD::SMUL";
9449 case X86ISD::UMUL: return "X86ISD::UMUL";
9450 case X86ISD::INC: return "X86ISD::INC";
9451 case X86ISD::DEC: return "X86ISD::DEC";
9452 case X86ISD::OR: return "X86ISD::OR";
9453 case X86ISD::XOR: return "X86ISD::XOR";
9454 case X86ISD::AND: return "X86ISD::AND";
9455 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
9456 case X86ISD::PTEST: return "X86ISD::PTEST";
9457 case X86ISD::TESTP: return "X86ISD::TESTP";
9458 case X86ISD::PALIGN: return "X86ISD::PALIGN";
9459 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
9460 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
9461 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
9462 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
9463 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
9464 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
9465 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
9466 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
9467 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
9468 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
9469 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
9470 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
9471 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
9472 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
9473 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
9474 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
9475 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
9476 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
9477 case X86ISD::MOVSD: return "X86ISD::MOVSD";
9478 case X86ISD::MOVSS: return "X86ISD::MOVSS";
9479 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
9480 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
9481 case X86ISD::VUNPCKLPS: return "X86ISD::VUNPCKLPS";
9482 case X86ISD::VUNPCKLPD: return "X86ISD::VUNPCKLPD";
9483 case X86ISD::VUNPCKLPSY: return "X86ISD::VUNPCKLPSY";
9484 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
9485 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
9486 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
9487 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
9488 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
9489 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
9490 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
9491 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
9492 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
9493 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
9494 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
9495 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9496 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
9497 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
9501 // isLegalAddressingMode - Return true if the addressing mode represented
9502 // by AM is legal for this target, for a load/store of the specified type.
9503 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9504 const Type *Ty) const {
9505 // X86 supports extremely general addressing modes.
9506 CodeModel::Model M = getTargetMachine().getCodeModel();
9507 Reloc::Model R = getTargetMachine().getRelocationModel();
9509 // X86 allows a sign-extended 32-bit immediate field as a displacement.
9510 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9515 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9517 // If a reference to this global requires an extra load, we can't fold it.
9518 if (isGlobalStubReference(GVFlags))
9521 // If BaseGV requires a register for the PIC base, we cannot also have a
9522 // BaseReg specified.
9523 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9526 // If lower 4G is not available, then we must use rip-relative addressing.
9527 if ((M != CodeModel::Small || R != Reloc::Static) &&
9528 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9538 // These scales always work.
9543 // These scales are formed with basereg+scalereg. Only accept if there is
9548 default: // Other stuff never works.
9556 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9557 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9559 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9560 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9561 if (NumBits1 <= NumBits2)
9566 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9567 if (!VT1.isInteger() || !VT2.isInteger())
9569 unsigned NumBits1 = VT1.getSizeInBits();
9570 unsigned NumBits2 = VT2.getSizeInBits();
9571 if (NumBits1 <= NumBits2)
9576 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9577 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9578 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9581 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9582 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9583 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9586 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9587 // i16 instructions are longer (0x66 prefix) and potentially slower.
9588 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9591 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9592 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9593 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9594 /// are assumed to be legal.
9596 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9598 // Very little shuffling can be done for 64-bit vectors right now.
9599 if (VT.getSizeInBits() == 64)
9600 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9602 // FIXME: pshufb, blends, shifts.
9603 return (VT.getVectorNumElements() == 2 ||
9604 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9605 isMOVLMask(M, VT) ||
9606 isSHUFPMask(M, VT) ||
9607 isPSHUFDMask(M, VT) ||
9608 isPSHUFHWMask(M, VT) ||
9609 isPSHUFLWMask(M, VT) ||
9610 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9611 isUNPCKLMask(M, VT) ||
9612 isUNPCKHMask(M, VT) ||
9613 isUNPCKL_v_undef_Mask(M, VT) ||
9614 isUNPCKH_v_undef_Mask(M, VT));
9618 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9620 unsigned NumElts = VT.getVectorNumElements();
9621 // FIXME: This collection of masks seems suspect.
9624 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9625 return (isMOVLMask(Mask, VT) ||
9626 isCommutedMOVLMask(Mask, VT, true) ||
9627 isSHUFPMask(Mask, VT) ||
9628 isCommutedSHUFPMask(Mask, VT));
9633 //===----------------------------------------------------------------------===//
9634 // X86 Scheduler Hooks
9635 //===----------------------------------------------------------------------===//
9637 // private utility function
9639 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9640 MachineBasicBlock *MBB,
9647 TargetRegisterClass *RC,
9648 bool invSrc) const {
9649 // For the atomic bitwise operator, we generate
9652 // ld t1 = [bitinstr.addr]
9653 // op t2 = t1, [bitinstr.val]
9655 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9657 // fallthrough -->nextMBB
9658 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9659 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9660 MachineFunction::iterator MBBIter = MBB;
9663 /// First build the CFG
9664 MachineFunction *F = MBB->getParent();
9665 MachineBasicBlock *thisMBB = MBB;
9666 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9667 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9668 F->insert(MBBIter, newMBB);
9669 F->insert(MBBIter, nextMBB);
9671 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9672 nextMBB->splice(nextMBB->begin(), thisMBB,
9673 llvm::next(MachineBasicBlock::iterator(bInstr)),
9675 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9677 // Update thisMBB to fall through to newMBB
9678 thisMBB->addSuccessor(newMBB);
9680 // newMBB jumps to itself and fall through to nextMBB
9681 newMBB->addSuccessor(nextMBB);
9682 newMBB->addSuccessor(newMBB);
9684 // Insert instructions into newMBB based on incoming instruction
9685 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9686 "unexpected number of operands");
9687 DebugLoc dl = bInstr->getDebugLoc();
9688 MachineOperand& destOper = bInstr->getOperand(0);
9689 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9690 int numArgs = bInstr->getNumOperands() - 1;
9691 for (int i=0; i < numArgs; ++i)
9692 argOpers[i] = &bInstr->getOperand(i+1);
9694 // x86 address has 4 operands: base, index, scale, and displacement
9695 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9696 int valArgIndx = lastAddrIndx + 1;
9698 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9699 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9700 for (int i=0; i <= lastAddrIndx; ++i)
9701 (*MIB).addOperand(*argOpers[i]);
9703 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9705 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9710 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9711 assert((argOpers[valArgIndx]->isReg() ||
9712 argOpers[valArgIndx]->isImm()) &&
9714 if (argOpers[valArgIndx]->isReg())
9715 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9717 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9719 (*MIB).addOperand(*argOpers[valArgIndx]);
9721 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9724 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9725 for (int i=0; i <= lastAddrIndx; ++i)
9726 (*MIB).addOperand(*argOpers[i]);
9728 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9729 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9730 bInstr->memoperands_end());
9732 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9736 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9738 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9742 // private utility function: 64 bit atomics on 32 bit host.
9744 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9745 MachineBasicBlock *MBB,
9750 bool invSrc) const {
9751 // For the atomic bitwise operator, we generate
9752 // thisMBB (instructions are in pairs, except cmpxchg8b)
9753 // ld t1,t2 = [bitinstr.addr]
9755 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9756 // op t5, t6 <- out1, out2, [bitinstr.val]
9757 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9758 // mov ECX, EBX <- t5, t6
9759 // mov EAX, EDX <- t1, t2
9760 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9761 // mov t3, t4 <- EAX, EDX
9763 // result in out1, out2
9764 // fallthrough -->nextMBB
9766 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9767 const unsigned LoadOpc = X86::MOV32rm;
9768 const unsigned NotOpc = X86::NOT32r;
9769 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9770 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9771 MachineFunction::iterator MBBIter = MBB;
9774 /// First build the CFG
9775 MachineFunction *F = MBB->getParent();
9776 MachineBasicBlock *thisMBB = MBB;
9777 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9778 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9779 F->insert(MBBIter, newMBB);
9780 F->insert(MBBIter, nextMBB);
9782 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9783 nextMBB->splice(nextMBB->begin(), thisMBB,
9784 llvm::next(MachineBasicBlock::iterator(bInstr)),
9786 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9788 // Update thisMBB to fall through to newMBB
9789 thisMBB->addSuccessor(newMBB);
9791 // newMBB jumps to itself and fall through to nextMBB
9792 newMBB->addSuccessor(nextMBB);
9793 newMBB->addSuccessor(newMBB);
9795 DebugLoc dl = bInstr->getDebugLoc();
9796 // Insert instructions into newMBB based on incoming instruction
9797 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9798 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9799 "unexpected number of operands");
9800 MachineOperand& dest1Oper = bInstr->getOperand(0);
9801 MachineOperand& dest2Oper = bInstr->getOperand(1);
9802 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9803 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9804 argOpers[i] = &bInstr->getOperand(i+2);
9806 // We use some of the operands multiple times, so conservatively just
9807 // clear any kill flags that might be present.
9808 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9809 argOpers[i]->setIsKill(false);
9812 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9813 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9815 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9816 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9817 for (int i=0; i <= lastAddrIndx; ++i)
9818 (*MIB).addOperand(*argOpers[i]);
9819 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9820 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9821 // add 4 to displacement.
9822 for (int i=0; i <= lastAddrIndx-2; ++i)
9823 (*MIB).addOperand(*argOpers[i]);
9824 MachineOperand newOp3 = *(argOpers[3]);
9826 newOp3.setImm(newOp3.getImm()+4);
9828 newOp3.setOffset(newOp3.getOffset()+4);
9829 (*MIB).addOperand(newOp3);
9830 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9832 // t3/4 are defined later, at the bottom of the loop
9833 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9834 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9835 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9836 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9837 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9838 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9840 // The subsequent operations should be using the destination registers of
9841 //the PHI instructions.
9843 t1 = F->getRegInfo().createVirtualRegister(RC);
9844 t2 = F->getRegInfo().createVirtualRegister(RC);
9845 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9846 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9848 t1 = dest1Oper.getReg();
9849 t2 = dest2Oper.getReg();
9852 int valArgIndx = lastAddrIndx + 1;
9853 assert((argOpers[valArgIndx]->isReg() ||
9854 argOpers[valArgIndx]->isImm()) &&
9856 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9857 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9858 if (argOpers[valArgIndx]->isReg())
9859 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9861 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9862 if (regOpcL != X86::MOV32rr)
9864 (*MIB).addOperand(*argOpers[valArgIndx]);
9865 assert(argOpers[valArgIndx + 1]->isReg() ==
9866 argOpers[valArgIndx]->isReg());
9867 assert(argOpers[valArgIndx + 1]->isImm() ==
9868 argOpers[valArgIndx]->isImm());
9869 if (argOpers[valArgIndx + 1]->isReg())
9870 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9872 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9873 if (regOpcH != X86::MOV32rr)
9875 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9877 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9879 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9882 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9884 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9887 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9888 for (int i=0; i <= lastAddrIndx; ++i)
9889 (*MIB).addOperand(*argOpers[i]);
9891 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9892 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9893 bInstr->memoperands_end());
9895 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9896 MIB.addReg(X86::EAX);
9897 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9898 MIB.addReg(X86::EDX);
9901 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9903 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9907 // private utility function
9909 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9910 MachineBasicBlock *MBB,
9911 unsigned cmovOpc) const {
9912 // For the atomic min/max operator, we generate
9915 // ld t1 = [min/max.addr]
9916 // mov t2 = [min/max.val]
9918 // cmov[cond] t2 = t1
9920 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9922 // fallthrough -->nextMBB
9924 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9925 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9926 MachineFunction::iterator MBBIter = MBB;
9929 /// First build the CFG
9930 MachineFunction *F = MBB->getParent();
9931 MachineBasicBlock *thisMBB = MBB;
9932 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9933 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9934 F->insert(MBBIter, newMBB);
9935 F->insert(MBBIter, nextMBB);
9937 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9938 nextMBB->splice(nextMBB->begin(), thisMBB,
9939 llvm::next(MachineBasicBlock::iterator(mInstr)),
9941 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9943 // Update thisMBB to fall through to newMBB
9944 thisMBB->addSuccessor(newMBB);
9946 // newMBB jumps to newMBB and fall through to nextMBB
9947 newMBB->addSuccessor(nextMBB);
9948 newMBB->addSuccessor(newMBB);
9950 DebugLoc dl = mInstr->getDebugLoc();
9951 // Insert instructions into newMBB based on incoming instruction
9952 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9953 "unexpected number of operands");
9954 MachineOperand& destOper = mInstr->getOperand(0);
9955 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9956 int numArgs = mInstr->getNumOperands() - 1;
9957 for (int i=0; i < numArgs; ++i)
9958 argOpers[i] = &mInstr->getOperand(i+1);
9960 // x86 address has 4 operands: base, index, scale, and displacement
9961 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9962 int valArgIndx = lastAddrIndx + 1;
9964 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9965 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9966 for (int i=0; i <= lastAddrIndx; ++i)
9967 (*MIB).addOperand(*argOpers[i]);
9969 // We only support register and immediate values
9970 assert((argOpers[valArgIndx]->isReg() ||
9971 argOpers[valArgIndx]->isImm()) &&
9974 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9975 if (argOpers[valArgIndx]->isReg())
9976 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9978 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9979 (*MIB).addOperand(*argOpers[valArgIndx]);
9981 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9984 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9989 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9990 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9994 // Cmp and exchange if none has modified the memory location
9995 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9996 for (int i=0; i <= lastAddrIndx; ++i)
9997 (*MIB).addOperand(*argOpers[i]);
9999 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10000 (*MIB).setMemRefs(mInstr->memoperands_begin(),
10001 mInstr->memoperands_end());
10003 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10004 MIB.addReg(X86::EAX);
10007 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10009 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
10013 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10014 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10015 // in the .td file.
10016 MachineBasicBlock *
10017 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10018 unsigned numArgs, bool memArg) const {
10019 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10020 "Target must have SSE4.2 or AVX features enabled");
10022 DebugLoc dl = MI->getDebugLoc();
10023 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10025 if (!Subtarget->hasAVX()) {
10027 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10029 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10032 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10034 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10037 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10038 for (unsigned i = 0; i < numArgs; ++i) {
10039 MachineOperand &Op = MI->getOperand(i+1);
10040 if (!(Op.isReg() && Op.isImplicit()))
10041 MIB.addOperand(Op);
10043 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10044 .addReg(X86::XMM0);
10046 MI->eraseFromParent();
10050 MachineBasicBlock *
10051 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10052 DebugLoc dl = MI->getDebugLoc();
10053 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10055 // Address into RAX/EAX, other two args into ECX, EDX.
10056 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10057 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10058 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10059 for (int i = 0; i < X86::AddrNumOperands; ++i)
10060 MIB.addOperand(MI->getOperand(i));
10062 unsigned ValOps = X86::AddrNumOperands;
10063 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10064 .addReg(MI->getOperand(ValOps).getReg());
10065 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10066 .addReg(MI->getOperand(ValOps+1).getReg());
10068 // The instruction doesn't actually take any operands though.
10069 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10071 MI->eraseFromParent(); // The pseudo is gone now.
10075 MachineBasicBlock *
10076 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10077 DebugLoc dl = MI->getDebugLoc();
10078 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10080 // First arg in ECX, the second in EAX.
10081 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10082 .addReg(MI->getOperand(0).getReg());
10083 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10084 .addReg(MI->getOperand(1).getReg());
10086 // The instruction doesn't actually take any operands though.
10087 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10089 MI->eraseFromParent(); // The pseudo is gone now.
10093 MachineBasicBlock *
10094 X86TargetLowering::EmitVAARG64WithCustomInserter(
10096 MachineBasicBlock *MBB) const {
10097 // Emit va_arg instruction on X86-64.
10099 // Operands to this pseudo-instruction:
10100 // 0 ) Output : destination address (reg)
10101 // 1-5) Input : va_list address (addr, i64mem)
10102 // 6 ) ArgSize : Size (in bytes) of vararg type
10103 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10104 // 8 ) Align : Alignment of type
10105 // 9 ) EFLAGS (implicit-def)
10107 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10108 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10110 unsigned DestReg = MI->getOperand(0).getReg();
10111 MachineOperand &Base = MI->getOperand(1);
10112 MachineOperand &Scale = MI->getOperand(2);
10113 MachineOperand &Index = MI->getOperand(3);
10114 MachineOperand &Disp = MI->getOperand(4);
10115 MachineOperand &Segment = MI->getOperand(5);
10116 unsigned ArgSize = MI->getOperand(6).getImm();
10117 unsigned ArgMode = MI->getOperand(7).getImm();
10118 unsigned Align = MI->getOperand(8).getImm();
10120 // Memory Reference
10121 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10122 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10123 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10125 // Machine Information
10126 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10127 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10128 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10129 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10130 DebugLoc DL = MI->getDebugLoc();
10132 // struct va_list {
10135 // i64 overflow_area (address)
10136 // i64 reg_save_area (address)
10138 // sizeof(va_list) = 24
10139 // alignment(va_list) = 8
10141 unsigned TotalNumIntRegs = 6;
10142 unsigned TotalNumXMMRegs = 8;
10143 bool UseGPOffset = (ArgMode == 1);
10144 bool UseFPOffset = (ArgMode == 2);
10145 unsigned MaxOffset = TotalNumIntRegs * 8 +
10146 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10148 /* Align ArgSize to a multiple of 8 */
10149 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10150 bool NeedsAlign = (Align > 8);
10152 MachineBasicBlock *thisMBB = MBB;
10153 MachineBasicBlock *overflowMBB;
10154 MachineBasicBlock *offsetMBB;
10155 MachineBasicBlock *endMBB;
10157 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
10158 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
10159 unsigned OffsetReg = 0;
10161 if (!UseGPOffset && !UseFPOffset) {
10162 // If we only pull from the overflow region, we don't create a branch.
10163 // We don't need to alter control flow.
10164 OffsetDestReg = 0; // unused
10165 OverflowDestReg = DestReg;
10168 overflowMBB = thisMBB;
10171 // First emit code to check if gp_offset (or fp_offset) is below the bound.
10172 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10173 // If not, pull from overflow_area. (branch to overflowMBB)
10178 // offsetMBB overflowMBB
10183 // Registers for the PHI in endMBB
10184 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10185 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10187 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10188 MachineFunction *MF = MBB->getParent();
10189 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10190 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10191 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10193 MachineFunction::iterator MBBIter = MBB;
10196 // Insert the new basic blocks
10197 MF->insert(MBBIter, offsetMBB);
10198 MF->insert(MBBIter, overflowMBB);
10199 MF->insert(MBBIter, endMBB);
10201 // Transfer the remainder of MBB and its successor edges to endMBB.
10202 endMBB->splice(endMBB->begin(), thisMBB,
10203 llvm::next(MachineBasicBlock::iterator(MI)),
10205 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10207 // Make offsetMBB and overflowMBB successors of thisMBB
10208 thisMBB->addSuccessor(offsetMBB);
10209 thisMBB->addSuccessor(overflowMBB);
10211 // endMBB is a successor of both offsetMBB and overflowMBB
10212 offsetMBB->addSuccessor(endMBB);
10213 overflowMBB->addSuccessor(endMBB);
10215 // Load the offset value into a register
10216 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10217 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10221 .addDisp(Disp, UseFPOffset ? 4 : 0)
10222 .addOperand(Segment)
10223 .setMemRefs(MMOBegin, MMOEnd);
10225 // Check if there is enough room left to pull this argument.
10226 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10228 .addImm(MaxOffset + 8 - ArgSizeA8);
10230 // Branch to "overflowMBB" if offset >= max
10231 // Fall through to "offsetMBB" otherwise
10232 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10233 .addMBB(overflowMBB);
10236 // In offsetMBB, emit code to use the reg_save_area.
10238 assert(OffsetReg != 0);
10240 // Read the reg_save_area address.
10241 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10242 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10247 .addOperand(Segment)
10248 .setMemRefs(MMOBegin, MMOEnd);
10250 // Zero-extend the offset
10251 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10252 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10255 .addImm(X86::sub_32bit);
10257 // Add the offset to the reg_save_area to get the final address.
10258 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10259 .addReg(OffsetReg64)
10260 .addReg(RegSaveReg);
10262 // Compute the offset for the next argument
10263 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10264 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10266 .addImm(UseFPOffset ? 16 : 8);
10268 // Store it back into the va_list.
10269 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10273 .addDisp(Disp, UseFPOffset ? 4 : 0)
10274 .addOperand(Segment)
10275 .addReg(NextOffsetReg)
10276 .setMemRefs(MMOBegin, MMOEnd);
10279 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10284 // Emit code to use overflow area
10287 // Load the overflow_area address into a register.
10288 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10289 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10294 .addOperand(Segment)
10295 .setMemRefs(MMOBegin, MMOEnd);
10297 // If we need to align it, do so. Otherwise, just copy the address
10298 // to OverflowDestReg.
10300 // Align the overflow address
10301 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10302 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10304 // aligned_addr = (addr + (align-1)) & ~(align-1)
10305 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10306 .addReg(OverflowAddrReg)
10309 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10311 .addImm(~(uint64_t)(Align-1));
10313 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10314 .addReg(OverflowAddrReg);
10317 // Compute the next overflow address after this argument.
10318 // (the overflow address should be kept 8-byte aligned)
10319 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10320 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10321 .addReg(OverflowDestReg)
10322 .addImm(ArgSizeA8);
10324 // Store the new overflow address.
10325 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10330 .addOperand(Segment)
10331 .addReg(NextAddrReg)
10332 .setMemRefs(MMOBegin, MMOEnd);
10334 // If we branched, emit the PHI to the front of endMBB.
10336 BuildMI(*endMBB, endMBB->begin(), DL,
10337 TII->get(X86::PHI), DestReg)
10338 .addReg(OffsetDestReg).addMBB(offsetMBB)
10339 .addReg(OverflowDestReg).addMBB(overflowMBB);
10342 // Erase the pseudo instruction
10343 MI->eraseFromParent();
10348 MachineBasicBlock *
10349 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10351 MachineBasicBlock *MBB) const {
10352 // Emit code to save XMM registers to the stack. The ABI says that the
10353 // number of registers to save is given in %al, so it's theoretically
10354 // possible to do an indirect jump trick to avoid saving all of them,
10355 // however this code takes a simpler approach and just executes all
10356 // of the stores if %al is non-zero. It's less code, and it's probably
10357 // easier on the hardware branch predictor, and stores aren't all that
10358 // expensive anyway.
10360 // Create the new basic blocks. One block contains all the XMM stores,
10361 // and one block is the final destination regardless of whether any
10362 // stores were performed.
10363 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10364 MachineFunction *F = MBB->getParent();
10365 MachineFunction::iterator MBBIter = MBB;
10367 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10368 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10369 F->insert(MBBIter, XMMSaveMBB);
10370 F->insert(MBBIter, EndMBB);
10372 // Transfer the remainder of MBB and its successor edges to EndMBB.
10373 EndMBB->splice(EndMBB->begin(), MBB,
10374 llvm::next(MachineBasicBlock::iterator(MI)),
10376 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10378 // The original block will now fall through to the XMM save block.
10379 MBB->addSuccessor(XMMSaveMBB);
10380 // The XMMSaveMBB will fall through to the end block.
10381 XMMSaveMBB->addSuccessor(EndMBB);
10383 // Now add the instructions.
10384 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10385 DebugLoc DL = MI->getDebugLoc();
10387 unsigned CountReg = MI->getOperand(0).getReg();
10388 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10389 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10391 if (!Subtarget->isTargetWin64()) {
10392 // If %al is 0, branch around the XMM save block.
10393 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10394 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10395 MBB->addSuccessor(EndMBB);
10398 // In the XMM save block, save all the XMM argument registers.
10399 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10400 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10401 MachineMemOperand *MMO =
10402 F->getMachineMemOperand(
10403 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10404 MachineMemOperand::MOStore,
10405 /*Size=*/16, /*Align=*/16);
10406 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10407 .addFrameIndex(RegSaveFrameIndex)
10408 .addImm(/*Scale=*/1)
10409 .addReg(/*IndexReg=*/0)
10410 .addImm(/*Disp=*/Offset)
10411 .addReg(/*Segment=*/0)
10412 .addReg(MI->getOperand(i).getReg())
10413 .addMemOperand(MMO);
10416 MI->eraseFromParent(); // The pseudo instruction is gone now.
10421 MachineBasicBlock *
10422 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10423 MachineBasicBlock *BB) const {
10424 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10425 DebugLoc DL = MI->getDebugLoc();
10427 // To "insert" a SELECT_CC instruction, we actually have to insert the
10428 // diamond control-flow pattern. The incoming instruction knows the
10429 // destination vreg to set, the condition code register to branch on, the
10430 // true/false values to select between, and a branch opcode to use.
10431 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10432 MachineFunction::iterator It = BB;
10438 // cmpTY ccX, r1, r2
10440 // fallthrough --> copy0MBB
10441 MachineBasicBlock *thisMBB = BB;
10442 MachineFunction *F = BB->getParent();
10443 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10444 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10445 F->insert(It, copy0MBB);
10446 F->insert(It, sinkMBB);
10448 // If the EFLAGS register isn't dead in the terminator, then claim that it's
10449 // live into the sink and copy blocks.
10450 const MachineFunction *MF = BB->getParent();
10451 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10452 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10454 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10455 const MachineOperand &MO = MI->getOperand(I);
10456 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10457 unsigned Reg = MO.getReg();
10458 if (Reg != X86::EFLAGS) continue;
10459 copy0MBB->addLiveIn(Reg);
10460 sinkMBB->addLiveIn(Reg);
10463 // Transfer the remainder of BB and its successor edges to sinkMBB.
10464 sinkMBB->splice(sinkMBB->begin(), BB,
10465 llvm::next(MachineBasicBlock::iterator(MI)),
10467 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10469 // Add the true and fallthrough blocks as its successors.
10470 BB->addSuccessor(copy0MBB);
10471 BB->addSuccessor(sinkMBB);
10473 // Create the conditional branch instruction.
10475 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10476 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10479 // %FalseValue = ...
10480 // # fallthrough to sinkMBB
10481 copy0MBB->addSuccessor(sinkMBB);
10484 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10486 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10487 TII->get(X86::PHI), MI->getOperand(0).getReg())
10488 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10489 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10491 MI->eraseFromParent(); // The pseudo instruction is gone now.
10495 MachineBasicBlock *
10496 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10497 MachineBasicBlock *BB) const {
10498 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10499 DebugLoc DL = MI->getDebugLoc();
10501 assert(!Subtarget->isTargetEnvMacho());
10503 // The lowering is pretty easy: we're just emitting the call to _alloca. The
10504 // non-trivial part is impdef of ESP.
10506 if (Subtarget->isTargetWin64()) {
10507 if (Subtarget->isTargetCygMing()) {
10508 // ___chkstk(Mingw64):
10509 // Clobbers R10, R11, RAX and EFLAGS.
10511 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10512 .addExternalSymbol("___chkstk")
10513 .addReg(X86::RAX, RegState::Implicit)
10514 .addReg(X86::RSP, RegState::Implicit)
10515 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10516 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10517 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10519 // __chkstk(MSVCRT): does not update stack pointer.
10520 // Clobbers R10, R11 and EFLAGS.
10521 // FIXME: RAX(allocated size) might be reused and not killed.
10522 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10523 .addExternalSymbol("__chkstk")
10524 .addReg(X86::RAX, RegState::Implicit)
10525 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10526 // RAX has the offset to subtracted from RSP.
10527 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10532 const char *StackProbeSymbol =
10533 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10535 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10536 .addExternalSymbol(StackProbeSymbol)
10537 .addReg(X86::EAX, RegState::Implicit)
10538 .addReg(X86::ESP, RegState::Implicit)
10539 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10540 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10541 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10544 MI->eraseFromParent(); // The pseudo instruction is gone now.
10548 MachineBasicBlock *
10549 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10550 MachineBasicBlock *BB) const {
10551 // This is pretty easy. We're taking the value that we received from
10552 // our load from the relocation, sticking it in either RDI (x86-64)
10553 // or EAX and doing an indirect call. The return value will then
10554 // be in the normal return register.
10555 const X86InstrInfo *TII
10556 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10557 DebugLoc DL = MI->getDebugLoc();
10558 MachineFunction *F = BB->getParent();
10560 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10561 assert(MI->getOperand(3).isGlobal() && "This should be a global");
10563 if (Subtarget->is64Bit()) {
10564 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10565 TII->get(X86::MOV64rm), X86::RDI)
10567 .addImm(0).addReg(0)
10568 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10569 MI->getOperand(3).getTargetFlags())
10571 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10572 addDirectMem(MIB, X86::RDI);
10573 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10574 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10575 TII->get(X86::MOV32rm), X86::EAX)
10577 .addImm(0).addReg(0)
10578 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10579 MI->getOperand(3).getTargetFlags())
10581 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10582 addDirectMem(MIB, X86::EAX);
10584 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10585 TII->get(X86::MOV32rm), X86::EAX)
10586 .addReg(TII->getGlobalBaseReg(F))
10587 .addImm(0).addReg(0)
10588 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10589 MI->getOperand(3).getTargetFlags())
10591 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10592 addDirectMem(MIB, X86::EAX);
10595 MI->eraseFromParent(); // The pseudo instruction is gone now.
10599 MachineBasicBlock *
10600 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10601 MachineBasicBlock *BB) const {
10602 switch (MI->getOpcode()) {
10603 default: assert(false && "Unexpected instr type to insert");
10604 case X86::TAILJMPd64:
10605 case X86::TAILJMPr64:
10606 case X86::TAILJMPm64:
10607 assert(!"TAILJMP64 would not be touched here.");
10608 case X86::TCRETURNdi64:
10609 case X86::TCRETURNri64:
10610 case X86::TCRETURNmi64:
10611 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10612 // On AMD64, additional defs should be added before register allocation.
10613 if (!Subtarget->isTargetWin64()) {
10614 MI->addRegisterDefined(X86::RSI);
10615 MI->addRegisterDefined(X86::RDI);
10616 MI->addRegisterDefined(X86::XMM6);
10617 MI->addRegisterDefined(X86::XMM7);
10618 MI->addRegisterDefined(X86::XMM8);
10619 MI->addRegisterDefined(X86::XMM9);
10620 MI->addRegisterDefined(X86::XMM10);
10621 MI->addRegisterDefined(X86::XMM11);
10622 MI->addRegisterDefined(X86::XMM12);
10623 MI->addRegisterDefined(X86::XMM13);
10624 MI->addRegisterDefined(X86::XMM14);
10625 MI->addRegisterDefined(X86::XMM15);
10628 case X86::WIN_ALLOCA:
10629 return EmitLoweredWinAlloca(MI, BB);
10630 case X86::TLSCall_32:
10631 case X86::TLSCall_64:
10632 return EmitLoweredTLSCall(MI, BB);
10633 case X86::CMOV_GR8:
10634 case X86::CMOV_FR32:
10635 case X86::CMOV_FR64:
10636 case X86::CMOV_V4F32:
10637 case X86::CMOV_V2F64:
10638 case X86::CMOV_V2I64:
10639 case X86::CMOV_GR16:
10640 case X86::CMOV_GR32:
10641 case X86::CMOV_RFP32:
10642 case X86::CMOV_RFP64:
10643 case X86::CMOV_RFP80:
10644 return EmitLoweredSelect(MI, BB);
10646 case X86::FP32_TO_INT16_IN_MEM:
10647 case X86::FP32_TO_INT32_IN_MEM:
10648 case X86::FP32_TO_INT64_IN_MEM:
10649 case X86::FP64_TO_INT16_IN_MEM:
10650 case X86::FP64_TO_INT32_IN_MEM:
10651 case X86::FP64_TO_INT64_IN_MEM:
10652 case X86::FP80_TO_INT16_IN_MEM:
10653 case X86::FP80_TO_INT32_IN_MEM:
10654 case X86::FP80_TO_INT64_IN_MEM: {
10655 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10656 DebugLoc DL = MI->getDebugLoc();
10658 // Change the floating point control register to use "round towards zero"
10659 // mode when truncating to an integer value.
10660 MachineFunction *F = BB->getParent();
10661 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10662 addFrameReference(BuildMI(*BB, MI, DL,
10663 TII->get(X86::FNSTCW16m)), CWFrameIdx);
10665 // Load the old value of the high byte of the control word...
10667 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10668 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10671 // Set the high part to be round to zero...
10672 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10675 // Reload the modified control word now...
10676 addFrameReference(BuildMI(*BB, MI, DL,
10677 TII->get(X86::FLDCW16m)), CWFrameIdx);
10679 // Restore the memory image of control word to original value
10680 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10683 // Get the X86 opcode to use.
10685 switch (MI->getOpcode()) {
10686 default: llvm_unreachable("illegal opcode!");
10687 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10688 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10689 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10690 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10691 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10692 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10693 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10694 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10695 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10699 MachineOperand &Op = MI->getOperand(0);
10701 AM.BaseType = X86AddressMode::RegBase;
10702 AM.Base.Reg = Op.getReg();
10704 AM.BaseType = X86AddressMode::FrameIndexBase;
10705 AM.Base.FrameIndex = Op.getIndex();
10707 Op = MI->getOperand(1);
10709 AM.Scale = Op.getImm();
10710 Op = MI->getOperand(2);
10712 AM.IndexReg = Op.getImm();
10713 Op = MI->getOperand(3);
10714 if (Op.isGlobal()) {
10715 AM.GV = Op.getGlobal();
10717 AM.Disp = Op.getImm();
10719 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10720 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10722 // Reload the original control word now.
10723 addFrameReference(BuildMI(*BB, MI, DL,
10724 TII->get(X86::FLDCW16m)), CWFrameIdx);
10726 MI->eraseFromParent(); // The pseudo instruction is gone now.
10729 // String/text processing lowering.
10730 case X86::PCMPISTRM128REG:
10731 case X86::VPCMPISTRM128REG:
10732 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10733 case X86::PCMPISTRM128MEM:
10734 case X86::VPCMPISTRM128MEM:
10735 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10736 case X86::PCMPESTRM128REG:
10737 case X86::VPCMPESTRM128REG:
10738 return EmitPCMP(MI, BB, 5, false /* in mem */);
10739 case X86::PCMPESTRM128MEM:
10740 case X86::VPCMPESTRM128MEM:
10741 return EmitPCMP(MI, BB, 5, true /* in mem */);
10743 // Thread synchronization.
10745 return EmitMonitor(MI, BB);
10747 return EmitMwait(MI, BB);
10749 // Atomic Lowering.
10750 case X86::ATOMAND32:
10751 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10752 X86::AND32ri, X86::MOV32rm,
10754 X86::NOT32r, X86::EAX,
10755 X86::GR32RegisterClass);
10756 case X86::ATOMOR32:
10757 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10758 X86::OR32ri, X86::MOV32rm,
10760 X86::NOT32r, X86::EAX,
10761 X86::GR32RegisterClass);
10762 case X86::ATOMXOR32:
10763 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10764 X86::XOR32ri, X86::MOV32rm,
10766 X86::NOT32r, X86::EAX,
10767 X86::GR32RegisterClass);
10768 case X86::ATOMNAND32:
10769 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10770 X86::AND32ri, X86::MOV32rm,
10772 X86::NOT32r, X86::EAX,
10773 X86::GR32RegisterClass, true);
10774 case X86::ATOMMIN32:
10775 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10776 case X86::ATOMMAX32:
10777 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10778 case X86::ATOMUMIN32:
10779 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10780 case X86::ATOMUMAX32:
10781 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10783 case X86::ATOMAND16:
10784 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10785 X86::AND16ri, X86::MOV16rm,
10787 X86::NOT16r, X86::AX,
10788 X86::GR16RegisterClass);
10789 case X86::ATOMOR16:
10790 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10791 X86::OR16ri, X86::MOV16rm,
10793 X86::NOT16r, X86::AX,
10794 X86::GR16RegisterClass);
10795 case X86::ATOMXOR16:
10796 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10797 X86::XOR16ri, X86::MOV16rm,
10799 X86::NOT16r, X86::AX,
10800 X86::GR16RegisterClass);
10801 case X86::ATOMNAND16:
10802 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10803 X86::AND16ri, X86::MOV16rm,
10805 X86::NOT16r, X86::AX,
10806 X86::GR16RegisterClass, true);
10807 case X86::ATOMMIN16:
10808 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10809 case X86::ATOMMAX16:
10810 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10811 case X86::ATOMUMIN16:
10812 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10813 case X86::ATOMUMAX16:
10814 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10816 case X86::ATOMAND8:
10817 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10818 X86::AND8ri, X86::MOV8rm,
10820 X86::NOT8r, X86::AL,
10821 X86::GR8RegisterClass);
10823 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10824 X86::OR8ri, X86::MOV8rm,
10826 X86::NOT8r, X86::AL,
10827 X86::GR8RegisterClass);
10828 case X86::ATOMXOR8:
10829 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10830 X86::XOR8ri, X86::MOV8rm,
10832 X86::NOT8r, X86::AL,
10833 X86::GR8RegisterClass);
10834 case X86::ATOMNAND8:
10835 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10836 X86::AND8ri, X86::MOV8rm,
10838 X86::NOT8r, X86::AL,
10839 X86::GR8RegisterClass, true);
10840 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10841 // This group is for 64-bit host.
10842 case X86::ATOMAND64:
10843 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10844 X86::AND64ri32, X86::MOV64rm,
10846 X86::NOT64r, X86::RAX,
10847 X86::GR64RegisterClass);
10848 case X86::ATOMOR64:
10849 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10850 X86::OR64ri32, X86::MOV64rm,
10852 X86::NOT64r, X86::RAX,
10853 X86::GR64RegisterClass);
10854 case X86::ATOMXOR64:
10855 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10856 X86::XOR64ri32, X86::MOV64rm,
10858 X86::NOT64r, X86::RAX,
10859 X86::GR64RegisterClass);
10860 case X86::ATOMNAND64:
10861 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10862 X86::AND64ri32, X86::MOV64rm,
10864 X86::NOT64r, X86::RAX,
10865 X86::GR64RegisterClass, true);
10866 case X86::ATOMMIN64:
10867 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10868 case X86::ATOMMAX64:
10869 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10870 case X86::ATOMUMIN64:
10871 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10872 case X86::ATOMUMAX64:
10873 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10875 // This group does 64-bit operations on a 32-bit host.
10876 case X86::ATOMAND6432:
10877 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10878 X86::AND32rr, X86::AND32rr,
10879 X86::AND32ri, X86::AND32ri,
10881 case X86::ATOMOR6432:
10882 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10883 X86::OR32rr, X86::OR32rr,
10884 X86::OR32ri, X86::OR32ri,
10886 case X86::ATOMXOR6432:
10887 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10888 X86::XOR32rr, X86::XOR32rr,
10889 X86::XOR32ri, X86::XOR32ri,
10891 case X86::ATOMNAND6432:
10892 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10893 X86::AND32rr, X86::AND32rr,
10894 X86::AND32ri, X86::AND32ri,
10896 case X86::ATOMADD6432:
10897 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10898 X86::ADD32rr, X86::ADC32rr,
10899 X86::ADD32ri, X86::ADC32ri,
10901 case X86::ATOMSUB6432:
10902 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10903 X86::SUB32rr, X86::SBB32rr,
10904 X86::SUB32ri, X86::SBB32ri,
10906 case X86::ATOMSWAP6432:
10907 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10908 X86::MOV32rr, X86::MOV32rr,
10909 X86::MOV32ri, X86::MOV32ri,
10911 case X86::VASTART_SAVE_XMM_REGS:
10912 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10914 case X86::VAARG_64:
10915 return EmitVAARG64WithCustomInserter(MI, BB);
10919 //===----------------------------------------------------------------------===//
10920 // X86 Optimization Hooks
10921 //===----------------------------------------------------------------------===//
10923 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10927 const SelectionDAG &DAG,
10928 unsigned Depth) const {
10929 unsigned Opc = Op.getOpcode();
10930 assert((Opc >= ISD::BUILTIN_OP_END ||
10931 Opc == ISD::INTRINSIC_WO_CHAIN ||
10932 Opc == ISD::INTRINSIC_W_CHAIN ||
10933 Opc == ISD::INTRINSIC_VOID) &&
10934 "Should use MaskedValueIsZero if you don't know whether Op"
10935 " is a target node!");
10937 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
10951 // These nodes' second result is a boolean.
10952 if (Op.getResNo() == 0)
10955 case X86ISD::SETCC:
10956 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10957 Mask.getBitWidth() - 1);
10962 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10963 unsigned Depth) const {
10964 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10965 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10966 return Op.getValueType().getScalarType().getSizeInBits();
10972 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10973 /// node is a GlobalAddress + offset.
10974 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10975 const GlobalValue* &GA,
10976 int64_t &Offset) const {
10977 if (N->getOpcode() == X86ISD::Wrapper) {
10978 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10979 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10980 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10984 return TargetLowering::isGAPlusOffset(N, GA, Offset);
10987 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10988 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10989 /// if the load addresses are consecutive, non-overlapping, and in the right
10991 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10992 TargetLowering::DAGCombinerInfo &DCI) {
10993 DebugLoc dl = N->getDebugLoc();
10994 EVT VT = N->getValueType(0);
10996 if (VT.getSizeInBits() != 128)
10999 // Don't create instructions with illegal types after legalize types has run.
11000 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11001 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11004 SmallVector<SDValue, 16> Elts;
11005 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11006 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11008 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11011 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11012 /// generation and convert it from being a bunch of shuffles and extracts
11013 /// to a simple store and scalar loads to extract the elements.
11014 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11015 const TargetLowering &TLI) {
11016 SDValue InputVector = N->getOperand(0);
11018 // Only operate on vectors of 4 elements, where the alternative shuffling
11019 // gets to be more expensive.
11020 if (InputVector.getValueType() != MVT::v4i32)
11023 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11024 // single use which is a sign-extend or zero-extend, and all elements are
11026 SmallVector<SDNode *, 4> Uses;
11027 unsigned ExtractedElements = 0;
11028 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11029 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11030 if (UI.getUse().getResNo() != InputVector.getResNo())
11033 SDNode *Extract = *UI;
11034 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11037 if (Extract->getValueType(0) != MVT::i32)
11039 if (!Extract->hasOneUse())
11041 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11042 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11044 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11047 // Record which element was extracted.
11048 ExtractedElements |=
11049 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11051 Uses.push_back(Extract);
11054 // If not all the elements were used, this may not be worthwhile.
11055 if (ExtractedElements != 15)
11058 // Ok, we've now decided to do the transformation.
11059 DebugLoc dl = InputVector.getDebugLoc();
11061 // Store the value to a temporary stack slot.
11062 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11063 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11064 MachinePointerInfo(), false, false, 0);
11066 // Replace each use (extract) with a load of the appropriate element.
11067 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11068 UE = Uses.end(); UI != UE; ++UI) {
11069 SDNode *Extract = *UI;
11071 // cOMpute the element's address.
11072 SDValue Idx = Extract->getOperand(1);
11074 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11075 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11076 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11078 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11079 StackPtr, OffsetVal);
11081 // Load the scalar.
11082 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11083 ScalarAddr, MachinePointerInfo(),
11086 // Replace the exact with the load.
11087 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11090 // The replacement was made in place; don't return anything.
11094 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11095 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11096 const X86Subtarget *Subtarget) {
11097 DebugLoc DL = N->getDebugLoc();
11098 SDValue Cond = N->getOperand(0);
11099 // Get the LHS/RHS of the select.
11100 SDValue LHS = N->getOperand(1);
11101 SDValue RHS = N->getOperand(2);
11103 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11104 // instructions match the semantics of the common C idiom x<y?x:y but not
11105 // x<=y?x:y, because of how they handle negative zero (which can be
11106 // ignored in unsafe-math mode).
11107 if (Subtarget->hasSSE2() &&
11108 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11109 Cond.getOpcode() == ISD::SETCC) {
11110 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11112 unsigned Opcode = 0;
11113 // Check for x CC y ? x : y.
11114 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11115 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11119 // Converting this to a min would handle NaNs incorrectly, and swapping
11120 // the operands would cause it to handle comparisons between positive
11121 // and negative zero incorrectly.
11122 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11123 if (!UnsafeFPMath &&
11124 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11126 std::swap(LHS, RHS);
11128 Opcode = X86ISD::FMIN;
11131 // Converting this to a min would handle comparisons between positive
11132 // and negative zero incorrectly.
11133 if (!UnsafeFPMath &&
11134 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11136 Opcode = X86ISD::FMIN;
11139 // Converting this to a min would handle both negative zeros and NaNs
11140 // incorrectly, but we can swap the operands to fix both.
11141 std::swap(LHS, RHS);
11145 Opcode = X86ISD::FMIN;
11149 // Converting this to a max would handle comparisons between positive
11150 // and negative zero incorrectly.
11151 if (!UnsafeFPMath &&
11152 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11154 Opcode = X86ISD::FMAX;
11157 // Converting this to a max would handle NaNs incorrectly, and swapping
11158 // the operands would cause it to handle comparisons between positive
11159 // and negative zero incorrectly.
11160 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11161 if (!UnsafeFPMath &&
11162 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11164 std::swap(LHS, RHS);
11166 Opcode = X86ISD::FMAX;
11169 // Converting this to a max would handle both negative zeros and NaNs
11170 // incorrectly, but we can swap the operands to fix both.
11171 std::swap(LHS, RHS);
11175 Opcode = X86ISD::FMAX;
11178 // Check for x CC y ? y : x -- a min/max with reversed arms.
11179 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11180 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11184 // Converting this to a min would handle comparisons between positive
11185 // and negative zero incorrectly, and swapping the operands would
11186 // cause it to handle NaNs incorrectly.
11187 if (!UnsafeFPMath &&
11188 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11189 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11191 std::swap(LHS, RHS);
11193 Opcode = X86ISD::FMIN;
11196 // Converting this to a min would handle NaNs incorrectly.
11197 if (!UnsafeFPMath &&
11198 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11200 Opcode = X86ISD::FMIN;
11203 // Converting this to a min would handle both negative zeros and NaNs
11204 // incorrectly, but we can swap the operands to fix both.
11205 std::swap(LHS, RHS);
11209 Opcode = X86ISD::FMIN;
11213 // Converting this to a max would handle NaNs incorrectly.
11214 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11216 Opcode = X86ISD::FMAX;
11219 // Converting this to a max would handle comparisons between positive
11220 // and negative zero incorrectly, and swapping the operands would
11221 // cause it to handle NaNs incorrectly.
11222 if (!UnsafeFPMath &&
11223 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11224 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11226 std::swap(LHS, RHS);
11228 Opcode = X86ISD::FMAX;
11231 // Converting this to a max would handle both negative zeros and NaNs
11232 // incorrectly, but we can swap the operands to fix both.
11233 std::swap(LHS, RHS);
11237 Opcode = X86ISD::FMAX;
11243 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11246 // If this is a select between two integer constants, try to do some
11248 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11249 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11250 // Don't do this for crazy integer types.
11251 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11252 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11253 // so that TrueC (the true value) is larger than FalseC.
11254 bool NeedsCondInvert = false;
11256 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11257 // Efficiently invertible.
11258 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
11259 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
11260 isa<ConstantSDNode>(Cond.getOperand(1))))) {
11261 NeedsCondInvert = true;
11262 std::swap(TrueC, FalseC);
11265 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
11266 if (FalseC->getAPIntValue() == 0 &&
11267 TrueC->getAPIntValue().isPowerOf2()) {
11268 if (NeedsCondInvert) // Invert the condition if needed.
11269 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11270 DAG.getConstant(1, Cond.getValueType()));
11272 // Zero extend the condition if needed.
11273 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11275 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11276 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11277 DAG.getConstant(ShAmt, MVT::i8));
11280 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11281 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11282 if (NeedsCondInvert) // Invert the condition if needed.
11283 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11284 DAG.getConstant(1, Cond.getValueType()));
11286 // Zero extend the condition if needed.
11287 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11288 FalseC->getValueType(0), Cond);
11289 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11290 SDValue(FalseC, 0));
11293 // Optimize cases that will turn into an LEA instruction. This requires
11294 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11295 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11296 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11297 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11299 bool isFastMultiplier = false;
11301 switch ((unsigned char)Diff) {
11303 case 1: // result = add base, cond
11304 case 2: // result = lea base( , cond*2)
11305 case 3: // result = lea base(cond, cond*2)
11306 case 4: // result = lea base( , cond*4)
11307 case 5: // result = lea base(cond, cond*4)
11308 case 8: // result = lea base( , cond*8)
11309 case 9: // result = lea base(cond, cond*8)
11310 isFastMultiplier = true;
11315 if (isFastMultiplier) {
11316 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11317 if (NeedsCondInvert) // Invert the condition if needed.
11318 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11319 DAG.getConstant(1, Cond.getValueType()));
11321 // Zero extend the condition if needed.
11322 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11324 // Scale the condition by the difference.
11326 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11327 DAG.getConstant(Diff, Cond.getValueType()));
11329 // Add the base if non-zero.
11330 if (FalseC->getAPIntValue() != 0)
11331 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11332 SDValue(FalseC, 0));
11342 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11343 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11344 TargetLowering::DAGCombinerInfo &DCI) {
11345 DebugLoc DL = N->getDebugLoc();
11347 // If the flag operand isn't dead, don't touch this CMOV.
11348 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11351 SDValue FalseOp = N->getOperand(0);
11352 SDValue TrueOp = N->getOperand(1);
11353 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11354 SDValue Cond = N->getOperand(3);
11355 if (CC == X86::COND_E || CC == X86::COND_NE) {
11356 switch (Cond.getOpcode()) {
11360 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11361 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11362 return (CC == X86::COND_E) ? FalseOp : TrueOp;
11366 // If this is a select between two integer constants, try to do some
11367 // optimizations. Note that the operands are ordered the opposite of SELECT
11369 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11370 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11371 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11372 // larger than FalseC (the false value).
11373 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11374 CC = X86::GetOppositeBranchCondition(CC);
11375 std::swap(TrueC, FalseC);
11378 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
11379 // This is efficient for any integer data type (including i8/i16) and
11381 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11382 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11383 DAG.getConstant(CC, MVT::i8), Cond);
11385 // Zero extend the condition if needed.
11386 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11388 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11389 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11390 DAG.getConstant(ShAmt, MVT::i8));
11391 if (N->getNumValues() == 2) // Dead flag value?
11392 return DCI.CombineTo(N, Cond, SDValue());
11396 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
11397 // for any integer data type, including i8/i16.
11398 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11399 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11400 DAG.getConstant(CC, MVT::i8), Cond);
11402 // Zero extend the condition if needed.
11403 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11404 FalseC->getValueType(0), Cond);
11405 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11406 SDValue(FalseC, 0));
11408 if (N->getNumValues() == 2) // Dead flag value?
11409 return DCI.CombineTo(N, Cond, SDValue());
11413 // Optimize cases that will turn into an LEA instruction. This requires
11414 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11415 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11416 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11417 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11419 bool isFastMultiplier = false;
11421 switch ((unsigned char)Diff) {
11423 case 1: // result = add base, cond
11424 case 2: // result = lea base( , cond*2)
11425 case 3: // result = lea base(cond, cond*2)
11426 case 4: // result = lea base( , cond*4)
11427 case 5: // result = lea base(cond, cond*4)
11428 case 8: // result = lea base( , cond*8)
11429 case 9: // result = lea base(cond, cond*8)
11430 isFastMultiplier = true;
11435 if (isFastMultiplier) {
11436 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11437 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11438 DAG.getConstant(CC, MVT::i8), Cond);
11439 // Zero extend the condition if needed.
11440 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11442 // Scale the condition by the difference.
11444 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11445 DAG.getConstant(Diff, Cond.getValueType()));
11447 // Add the base if non-zero.
11448 if (FalseC->getAPIntValue() != 0)
11449 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11450 SDValue(FalseC, 0));
11451 if (N->getNumValues() == 2) // Dead flag value?
11452 return DCI.CombineTo(N, Cond, SDValue());
11462 /// PerformMulCombine - Optimize a single multiply with constant into two
11463 /// in order to implement it with two cheaper instructions, e.g.
11464 /// LEA + SHL, LEA + LEA.
11465 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11466 TargetLowering::DAGCombinerInfo &DCI) {
11467 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11470 EVT VT = N->getValueType(0);
11471 if (VT != MVT::i64)
11474 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11477 uint64_t MulAmt = C->getZExtValue();
11478 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11481 uint64_t MulAmt1 = 0;
11482 uint64_t MulAmt2 = 0;
11483 if ((MulAmt % 9) == 0) {
11485 MulAmt2 = MulAmt / 9;
11486 } else if ((MulAmt % 5) == 0) {
11488 MulAmt2 = MulAmt / 5;
11489 } else if ((MulAmt % 3) == 0) {
11491 MulAmt2 = MulAmt / 3;
11494 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11495 DebugLoc DL = N->getDebugLoc();
11497 if (isPowerOf2_64(MulAmt2) &&
11498 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11499 // If second multiplifer is pow2, issue it first. We want the multiply by
11500 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11502 std::swap(MulAmt1, MulAmt2);
11505 if (isPowerOf2_64(MulAmt1))
11506 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11507 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11509 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11510 DAG.getConstant(MulAmt1, VT));
11512 if (isPowerOf2_64(MulAmt2))
11513 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11514 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11516 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11517 DAG.getConstant(MulAmt2, VT));
11519 // Do not add new nodes to DAG combiner worklist.
11520 DCI.CombineTo(N, NewMul, false);
11525 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11526 SDValue N0 = N->getOperand(0);
11527 SDValue N1 = N->getOperand(1);
11528 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11529 EVT VT = N0.getValueType();
11531 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11532 // since the result of setcc_c is all zero's or all ones.
11533 if (N1C && N0.getOpcode() == ISD::AND &&
11534 N0.getOperand(1).getOpcode() == ISD::Constant) {
11535 SDValue N00 = N0.getOperand(0);
11536 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11537 ((N00.getOpcode() == ISD::ANY_EXTEND ||
11538 N00.getOpcode() == ISD::ZERO_EXTEND) &&
11539 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11540 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11541 APInt ShAmt = N1C->getAPIntValue();
11542 Mask = Mask.shl(ShAmt);
11544 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11545 N00, DAG.getConstant(Mask, VT));
11552 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11554 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11555 const X86Subtarget *Subtarget) {
11556 EVT VT = N->getValueType(0);
11557 if (!VT.isVector() && VT.isInteger() &&
11558 N->getOpcode() == ISD::SHL)
11559 return PerformSHLCombine(N, DAG);
11561 // On X86 with SSE2 support, we can transform this to a vector shift if
11562 // all elements are shifted by the same amount. We can't do this in legalize
11563 // because the a constant vector is typically transformed to a constant pool
11564 // so we have no knowledge of the shift amount.
11565 if (!Subtarget->hasSSE2())
11568 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11571 SDValue ShAmtOp = N->getOperand(1);
11572 EVT EltVT = VT.getVectorElementType();
11573 DebugLoc DL = N->getDebugLoc();
11574 SDValue BaseShAmt = SDValue();
11575 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11576 unsigned NumElts = VT.getVectorNumElements();
11578 for (; i != NumElts; ++i) {
11579 SDValue Arg = ShAmtOp.getOperand(i);
11580 if (Arg.getOpcode() == ISD::UNDEF) continue;
11584 for (; i != NumElts; ++i) {
11585 SDValue Arg = ShAmtOp.getOperand(i);
11586 if (Arg.getOpcode() == ISD::UNDEF) continue;
11587 if (Arg != BaseShAmt) {
11591 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11592 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11593 SDValue InVec = ShAmtOp.getOperand(0);
11594 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11595 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11597 for (; i != NumElts; ++i) {
11598 SDValue Arg = InVec.getOperand(i);
11599 if (Arg.getOpcode() == ISD::UNDEF) continue;
11603 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11604 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11605 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11606 if (C->getZExtValue() == SplatIdx)
11607 BaseShAmt = InVec.getOperand(1);
11610 if (BaseShAmt.getNode() == 0)
11611 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11612 DAG.getIntPtrConstant(0));
11616 // The shift amount is an i32.
11617 if (EltVT.bitsGT(MVT::i32))
11618 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11619 else if (EltVT.bitsLT(MVT::i32))
11620 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11622 // The shift amount is identical so we can do a vector shift.
11623 SDValue ValOp = N->getOperand(0);
11624 switch (N->getOpcode()) {
11626 llvm_unreachable("Unknown shift opcode!");
11629 if (VT == MVT::v2i64)
11630 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11631 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11633 if (VT == MVT::v4i32)
11634 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11635 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11637 if (VT == MVT::v8i16)
11638 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11639 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11643 if (VT == MVT::v4i32)
11644 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11645 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11647 if (VT == MVT::v8i16)
11648 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11649 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11653 if (VT == MVT::v2i64)
11654 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11655 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11657 if (VT == MVT::v4i32)
11658 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11659 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11661 if (VT == MVT::v8i16)
11662 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11663 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11671 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11672 TargetLowering::DAGCombinerInfo &DCI,
11673 const X86Subtarget *Subtarget) {
11674 if (DCI.isBeforeLegalizeOps())
11677 // Want to form PANDN nodes, in the hopes of then easily combining them with
11678 // OR and AND nodes to form PBLEND/PSIGN.
11679 EVT VT = N->getValueType(0);
11680 if (VT != MVT::v2i64)
11683 SDValue N0 = N->getOperand(0);
11684 SDValue N1 = N->getOperand(1);
11685 DebugLoc DL = N->getDebugLoc();
11687 // Check LHS for vnot
11688 if (N0.getOpcode() == ISD::XOR &&
11689 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11690 return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11692 // Check RHS for vnot
11693 if (N1.getOpcode() == ISD::XOR &&
11694 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11695 return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11700 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11701 TargetLowering::DAGCombinerInfo &DCI,
11702 const X86Subtarget *Subtarget) {
11703 if (DCI.isBeforeLegalizeOps())
11706 EVT VT = N->getValueType(0);
11707 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11710 SDValue N0 = N->getOperand(0);
11711 SDValue N1 = N->getOperand(1);
11713 // look for psign/blend
11714 if (Subtarget->hasSSSE3()) {
11715 if (VT == MVT::v2i64) {
11716 // Canonicalize pandn to RHS
11717 if (N0.getOpcode() == X86ISD::PANDN)
11719 // or (and (m, x), (pandn m, y))
11720 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11721 SDValue Mask = N1.getOperand(0);
11722 SDValue X = N1.getOperand(1);
11724 if (N0.getOperand(0) == Mask)
11725 Y = N0.getOperand(1);
11726 if (N0.getOperand(1) == Mask)
11727 Y = N0.getOperand(0);
11729 // Check to see if the mask appeared in both the AND and PANDN and
11733 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11734 if (Mask.getOpcode() != ISD::BITCAST ||
11735 X.getOpcode() != ISD::BITCAST ||
11736 Y.getOpcode() != ISD::BITCAST)
11739 // Look through mask bitcast.
11740 Mask = Mask.getOperand(0);
11741 EVT MaskVT = Mask.getValueType();
11743 // Validate that the Mask operand is a vector sra node. The sra node
11744 // will be an intrinsic.
11745 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11748 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11749 // there is no psrai.b
11750 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11751 case Intrinsic::x86_sse2_psrai_w:
11752 case Intrinsic::x86_sse2_psrai_d:
11754 default: return SDValue();
11757 // Check that the SRA is all signbits.
11758 SDValue SraC = Mask.getOperand(2);
11759 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
11760 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11761 if ((SraAmt + 1) != EltBits)
11764 DebugLoc DL = N->getDebugLoc();
11766 // Now we know we at least have a plendvb with the mask val. See if
11767 // we can form a psignb/w/d.
11768 // psign = x.type == y.type == mask.type && y = sub(0, x);
11769 X = X.getOperand(0);
11770 Y = Y.getOperand(0);
11771 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11772 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11773 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11776 case 8: Opc = X86ISD::PSIGNB; break;
11777 case 16: Opc = X86ISD::PSIGNW; break;
11778 case 32: Opc = X86ISD::PSIGND; break;
11782 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11783 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11786 // PBLENDVB only available on SSE 4.1
11787 if (!Subtarget->hasSSE41())
11790 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11791 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11792 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11793 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11794 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11799 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11800 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11802 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11804 if (!N0.hasOneUse() || !N1.hasOneUse())
11807 SDValue ShAmt0 = N0.getOperand(1);
11808 if (ShAmt0.getValueType() != MVT::i8)
11810 SDValue ShAmt1 = N1.getOperand(1);
11811 if (ShAmt1.getValueType() != MVT::i8)
11813 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11814 ShAmt0 = ShAmt0.getOperand(0);
11815 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11816 ShAmt1 = ShAmt1.getOperand(0);
11818 DebugLoc DL = N->getDebugLoc();
11819 unsigned Opc = X86ISD::SHLD;
11820 SDValue Op0 = N0.getOperand(0);
11821 SDValue Op1 = N1.getOperand(0);
11822 if (ShAmt0.getOpcode() == ISD::SUB) {
11823 Opc = X86ISD::SHRD;
11824 std::swap(Op0, Op1);
11825 std::swap(ShAmt0, ShAmt1);
11828 unsigned Bits = VT.getSizeInBits();
11829 if (ShAmt1.getOpcode() == ISD::SUB) {
11830 SDValue Sum = ShAmt1.getOperand(0);
11831 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11832 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11833 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11834 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11835 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11836 return DAG.getNode(Opc, DL, VT,
11838 DAG.getNode(ISD::TRUNCATE, DL,
11841 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11842 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11844 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11845 return DAG.getNode(Opc, DL, VT,
11846 N0.getOperand(0), N1.getOperand(0),
11847 DAG.getNode(ISD::TRUNCATE, DL,
11854 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11855 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11856 const X86Subtarget *Subtarget) {
11857 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
11858 // the FP state in cases where an emms may be missing.
11859 // A preferable solution to the general problem is to figure out the right
11860 // places to insert EMMS. This qualifies as a quick hack.
11862 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11863 StoreSDNode *St = cast<StoreSDNode>(N);
11864 EVT VT = St->getValue().getValueType();
11865 if (VT.getSizeInBits() != 64)
11868 const Function *F = DAG.getMachineFunction().getFunction();
11869 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11870 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11871 && Subtarget->hasSSE2();
11872 if ((VT.isVector() ||
11873 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11874 isa<LoadSDNode>(St->getValue()) &&
11875 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11876 St->getChain().hasOneUse() && !St->isVolatile()) {
11877 SDNode* LdVal = St->getValue().getNode();
11878 LoadSDNode *Ld = 0;
11879 int TokenFactorIndex = -1;
11880 SmallVector<SDValue, 8> Ops;
11881 SDNode* ChainVal = St->getChain().getNode();
11882 // Must be a store of a load. We currently handle two cases: the load
11883 // is a direct child, and it's under an intervening TokenFactor. It is
11884 // possible to dig deeper under nested TokenFactors.
11885 if (ChainVal == LdVal)
11886 Ld = cast<LoadSDNode>(St->getChain());
11887 else if (St->getValue().hasOneUse() &&
11888 ChainVal->getOpcode() == ISD::TokenFactor) {
11889 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11890 if (ChainVal->getOperand(i).getNode() == LdVal) {
11891 TokenFactorIndex = i;
11892 Ld = cast<LoadSDNode>(St->getValue());
11894 Ops.push_back(ChainVal->getOperand(i));
11898 if (!Ld || !ISD::isNormalLoad(Ld))
11901 // If this is not the MMX case, i.e. we are just turning i64 load/store
11902 // into f64 load/store, avoid the transformation if there are multiple
11903 // uses of the loaded value.
11904 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11907 DebugLoc LdDL = Ld->getDebugLoc();
11908 DebugLoc StDL = N->getDebugLoc();
11909 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11910 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11912 if (Subtarget->is64Bit() || F64IsLegal) {
11913 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11914 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11915 Ld->getPointerInfo(), Ld->isVolatile(),
11916 Ld->isNonTemporal(), Ld->getAlignment());
11917 SDValue NewChain = NewLd.getValue(1);
11918 if (TokenFactorIndex != -1) {
11919 Ops.push_back(NewChain);
11920 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11923 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11924 St->getPointerInfo(),
11925 St->isVolatile(), St->isNonTemporal(),
11926 St->getAlignment());
11929 // Otherwise, lower to two pairs of 32-bit loads / stores.
11930 SDValue LoAddr = Ld->getBasePtr();
11931 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11932 DAG.getConstant(4, MVT::i32));
11934 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11935 Ld->getPointerInfo(),
11936 Ld->isVolatile(), Ld->isNonTemporal(),
11937 Ld->getAlignment());
11938 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11939 Ld->getPointerInfo().getWithOffset(4),
11940 Ld->isVolatile(), Ld->isNonTemporal(),
11941 MinAlign(Ld->getAlignment(), 4));
11943 SDValue NewChain = LoLd.getValue(1);
11944 if (TokenFactorIndex != -1) {
11945 Ops.push_back(LoLd);
11946 Ops.push_back(HiLd);
11947 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11951 LoAddr = St->getBasePtr();
11952 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11953 DAG.getConstant(4, MVT::i32));
11955 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11956 St->getPointerInfo(),
11957 St->isVolatile(), St->isNonTemporal(),
11958 St->getAlignment());
11959 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11960 St->getPointerInfo().getWithOffset(4),
11962 St->isNonTemporal(),
11963 MinAlign(St->getAlignment(), 4));
11964 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11969 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11970 /// X86ISD::FXOR nodes.
11971 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11972 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11973 // F[X]OR(0.0, x) -> x
11974 // F[X]OR(x, 0.0) -> x
11975 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11976 if (C->getValueAPF().isPosZero())
11977 return N->getOperand(1);
11978 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11979 if (C->getValueAPF().isPosZero())
11980 return N->getOperand(0);
11984 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11985 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11986 // FAND(0.0, x) -> 0.0
11987 // FAND(x, 0.0) -> 0.0
11988 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11989 if (C->getValueAPF().isPosZero())
11990 return N->getOperand(0);
11991 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11992 if (C->getValueAPF().isPosZero())
11993 return N->getOperand(1);
11997 static SDValue PerformBTCombine(SDNode *N,
11999 TargetLowering::DAGCombinerInfo &DCI) {
12000 // BT ignores high bits in the bit index operand.
12001 SDValue Op1 = N->getOperand(1);
12002 if (Op1.hasOneUse()) {
12003 unsigned BitWidth = Op1.getValueSizeInBits();
12004 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12005 APInt KnownZero, KnownOne;
12006 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12007 !DCI.isBeforeLegalizeOps());
12008 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12009 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12010 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12011 DCI.CommitTargetLoweringOpt(TLO);
12016 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12017 SDValue Op = N->getOperand(0);
12018 if (Op.getOpcode() == ISD::BITCAST)
12019 Op = Op.getOperand(0);
12020 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12021 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12022 VT.getVectorElementType().getSizeInBits() ==
12023 OpVT.getVectorElementType().getSizeInBits()) {
12024 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12029 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12030 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
12031 // (and (i32 x86isd::setcc_carry), 1)
12032 // This eliminates the zext. This transformation is necessary because
12033 // ISD::SETCC is always legalized to i8.
12034 DebugLoc dl = N->getDebugLoc();
12035 SDValue N0 = N->getOperand(0);
12036 EVT VT = N->getValueType(0);
12037 if (N0.getOpcode() == ISD::AND &&
12039 N0.getOperand(0).hasOneUse()) {
12040 SDValue N00 = N0.getOperand(0);
12041 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12043 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12044 if (!C || C->getZExtValue() != 1)
12046 return DAG.getNode(ISD::AND, dl, VT,
12047 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12048 N00.getOperand(0), N00.getOperand(1)),
12049 DAG.getConstant(1, VT));
12055 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12056 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12057 unsigned X86CC = N->getConstantOperandVal(0);
12058 SDValue EFLAG = N->getOperand(1);
12059 DebugLoc DL = N->getDebugLoc();
12061 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12062 // a zext and produces an all-ones bit which is more useful than 0/1 in some
12064 if (X86CC == X86::COND_B)
12065 return DAG.getNode(ISD::AND, DL, MVT::i8,
12066 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12067 DAG.getConstant(X86CC, MVT::i8), EFLAG),
12068 DAG.getConstant(1, MVT::i8));
12073 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12074 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12075 X86TargetLowering::DAGCombinerInfo &DCI) {
12076 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12077 // the result is either zero or one (depending on the input carry bit).
12078 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12079 if (X86::isZeroNode(N->getOperand(0)) &&
12080 X86::isZeroNode(N->getOperand(1)) &&
12081 // We don't have a good way to replace an EFLAGS use, so only do this when
12083 SDValue(N, 1).use_empty()) {
12084 DebugLoc DL = N->getDebugLoc();
12085 EVT VT = N->getValueType(0);
12086 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12087 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12088 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12089 DAG.getConstant(X86::COND_B,MVT::i8),
12091 DAG.getConstant(1, VT));
12092 return DCI.CombineTo(N, Res1, CarryOut);
12098 // fold (add Y, (sete X, 0)) -> adc 0, Y
12099 // (add Y, (setne X, 0)) -> sbb -1, Y
12100 // (sub (sete X, 0), Y) -> sbb 0, Y
12101 // (sub (setne X, 0), Y) -> adc -1, Y
12102 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12103 DebugLoc DL = N->getDebugLoc();
12105 // Look through ZExts.
12106 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12107 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12110 SDValue SetCC = Ext.getOperand(0);
12111 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12114 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12115 if (CC != X86::COND_E && CC != X86::COND_NE)
12118 SDValue Cmp = SetCC.getOperand(1);
12119 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12120 !X86::isZeroNode(Cmp.getOperand(1)) ||
12121 !Cmp.getOperand(0).getValueType().isInteger())
12124 SDValue CmpOp0 = Cmp.getOperand(0);
12125 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12126 DAG.getConstant(1, CmpOp0.getValueType()));
12128 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12129 if (CC == X86::COND_NE)
12130 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12131 DL, OtherVal.getValueType(), OtherVal,
12132 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12133 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12134 DL, OtherVal.getValueType(), OtherVal,
12135 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12138 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12139 DAGCombinerInfo &DCI) const {
12140 SelectionDAG &DAG = DCI.DAG;
12141 switch (N->getOpcode()) {
12143 case ISD::EXTRACT_VECTOR_ELT:
12144 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12145 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
12146 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
12148 case ISD::SUB: return OptimizeConditonalInDecrement(N, DAG);
12149 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
12150 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
12153 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
12154 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
12155 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
12156 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
12158 case X86ISD::FOR: return PerformFORCombine(N, DAG);
12159 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
12160 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
12161 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
12162 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
12163 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
12164 case X86ISD::SHUFPS: // Handle all target specific shuffles
12165 case X86ISD::SHUFPD:
12166 case X86ISD::PALIGN:
12167 case X86ISD::PUNPCKHBW:
12168 case X86ISD::PUNPCKHWD:
12169 case X86ISD::PUNPCKHDQ:
12170 case X86ISD::PUNPCKHQDQ:
12171 case X86ISD::UNPCKHPS:
12172 case X86ISD::UNPCKHPD:
12173 case X86ISD::PUNPCKLBW:
12174 case X86ISD::PUNPCKLWD:
12175 case X86ISD::PUNPCKLDQ:
12176 case X86ISD::PUNPCKLQDQ:
12177 case X86ISD::UNPCKLPS:
12178 case X86ISD::UNPCKLPD:
12179 case X86ISD::VUNPCKLPS:
12180 case X86ISD::VUNPCKLPD:
12181 case X86ISD::VUNPCKLPSY:
12182 case X86ISD::VUNPCKLPDY:
12183 case X86ISD::MOVHLPS:
12184 case X86ISD::MOVLHPS:
12185 case X86ISD::PSHUFD:
12186 case X86ISD::PSHUFHW:
12187 case X86ISD::PSHUFLW:
12188 case X86ISD::MOVSS:
12189 case X86ISD::MOVSD:
12190 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12196 /// isTypeDesirableForOp - Return true if the target has native support for
12197 /// the specified value type and it is 'desirable' to use the type for the
12198 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12199 /// instruction encodings are longer and some i16 instructions are slow.
12200 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12201 if (!isTypeLegal(VT))
12203 if (VT != MVT::i16)
12210 case ISD::SIGN_EXTEND:
12211 case ISD::ZERO_EXTEND:
12212 case ISD::ANY_EXTEND:
12225 /// IsDesirableToPromoteOp - This method query the target whether it is
12226 /// beneficial for dag combiner to promote the specified node. If true, it
12227 /// should return the desired promotion type by reference.
12228 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12229 EVT VT = Op.getValueType();
12230 if (VT != MVT::i16)
12233 bool Promote = false;
12234 bool Commute = false;
12235 switch (Op.getOpcode()) {
12238 LoadSDNode *LD = cast<LoadSDNode>(Op);
12239 // If the non-extending load has a single use and it's not live out, then it
12240 // might be folded.
12241 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12242 Op.hasOneUse()*/) {
12243 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12244 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12245 // The only case where we'd want to promote LOAD (rather then it being
12246 // promoted as an operand is when it's only use is liveout.
12247 if (UI->getOpcode() != ISD::CopyToReg)
12254 case ISD::SIGN_EXTEND:
12255 case ISD::ZERO_EXTEND:
12256 case ISD::ANY_EXTEND:
12261 SDValue N0 = Op.getOperand(0);
12262 // Look out for (store (shl (load), x)).
12263 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12276 SDValue N0 = Op.getOperand(0);
12277 SDValue N1 = Op.getOperand(1);
12278 if (!Commute && MayFoldLoad(N1))
12280 // Avoid disabling potential load folding opportunities.
12281 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12283 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12293 //===----------------------------------------------------------------------===//
12294 // X86 Inline Assembly Support
12295 //===----------------------------------------------------------------------===//
12297 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12298 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12300 std::string AsmStr = IA->getAsmString();
12302 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12303 SmallVector<StringRef, 4> AsmPieces;
12304 SplitString(AsmStr, AsmPieces, ";\n");
12306 switch (AsmPieces.size()) {
12307 default: return false;
12309 AsmStr = AsmPieces[0];
12311 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
12313 // FIXME: this should verify that we are targeting a 486 or better. If not,
12314 // we will turn this bswap into something that will be lowered to logical ops
12315 // instead of emitting the bswap asm. For now, we don't support 486 or lower
12316 // so don't worry about this.
12318 if (AsmPieces.size() == 2 &&
12319 (AsmPieces[0] == "bswap" ||
12320 AsmPieces[0] == "bswapq" ||
12321 AsmPieces[0] == "bswapl") &&
12322 (AsmPieces[1] == "$0" ||
12323 AsmPieces[1] == "${0:q}")) {
12324 // No need to check constraints, nothing other than the equivalent of
12325 // "=r,0" would be valid here.
12326 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12327 if (!Ty || Ty->getBitWidth() % 16 != 0)
12329 return IntrinsicLowering::LowerToByteSwap(CI);
12331 // rorw $$8, ${0:w} --> llvm.bswap.i16
12332 if (CI->getType()->isIntegerTy(16) &&
12333 AsmPieces.size() == 3 &&
12334 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12335 AsmPieces[1] == "$$8," &&
12336 AsmPieces[2] == "${0:w}" &&
12337 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12339 const std::string &ConstraintsStr = IA->getConstraintString();
12340 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12341 std::sort(AsmPieces.begin(), AsmPieces.end());
12342 if (AsmPieces.size() == 4 &&
12343 AsmPieces[0] == "~{cc}" &&
12344 AsmPieces[1] == "~{dirflag}" &&
12345 AsmPieces[2] == "~{flags}" &&
12346 AsmPieces[3] == "~{fpsr}") {
12347 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12348 if (!Ty || Ty->getBitWidth() % 16 != 0)
12350 return IntrinsicLowering::LowerToByteSwap(CI);
12355 if (CI->getType()->isIntegerTy(32) &&
12356 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12357 SmallVector<StringRef, 4> Words;
12358 SplitString(AsmPieces[0], Words, " \t,");
12359 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12360 Words[2] == "${0:w}") {
12362 SplitString(AsmPieces[1], Words, " \t,");
12363 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12364 Words[2] == "$0") {
12366 SplitString(AsmPieces[2], Words, " \t,");
12367 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12368 Words[2] == "${0:w}") {
12370 const std::string &ConstraintsStr = IA->getConstraintString();
12371 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12372 std::sort(AsmPieces.begin(), AsmPieces.end());
12373 if (AsmPieces.size() == 4 &&
12374 AsmPieces[0] == "~{cc}" &&
12375 AsmPieces[1] == "~{dirflag}" &&
12376 AsmPieces[2] == "~{flags}" &&
12377 AsmPieces[3] == "~{fpsr}") {
12378 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12379 if (!Ty || Ty->getBitWidth() % 16 != 0)
12381 return IntrinsicLowering::LowerToByteSwap(CI);
12388 if (CI->getType()->isIntegerTy(64)) {
12389 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12390 if (Constraints.size() >= 2 &&
12391 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12392 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12393 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
12394 SmallVector<StringRef, 4> Words;
12395 SplitString(AsmPieces[0], Words, " \t");
12396 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12398 SplitString(AsmPieces[1], Words, " \t");
12399 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12401 SplitString(AsmPieces[2], Words, " \t,");
12402 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12403 Words[2] == "%edx") {
12404 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12405 if (!Ty || Ty->getBitWidth() % 16 != 0)
12407 return IntrinsicLowering::LowerToByteSwap(CI);
12420 /// getConstraintType - Given a constraint letter, return the type of
12421 /// constraint it is for this target.
12422 X86TargetLowering::ConstraintType
12423 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12424 if (Constraint.size() == 1) {
12425 switch (Constraint[0]) {
12435 return C_RegisterClass;
12459 return TargetLowering::getConstraintType(Constraint);
12462 /// Examine constraint type and operand type and determine a weight value.
12463 /// This object must already have been set up with the operand type
12464 /// and the current alternative constraint selected.
12465 TargetLowering::ConstraintWeight
12466 X86TargetLowering::getSingleConstraintMatchWeight(
12467 AsmOperandInfo &info, const char *constraint) const {
12468 ConstraintWeight weight = CW_Invalid;
12469 Value *CallOperandVal = info.CallOperandVal;
12470 // If we don't have a value, we can't do a match,
12471 // but allow it at the lowest weight.
12472 if (CallOperandVal == NULL)
12474 const Type *type = CallOperandVal->getType();
12475 // Look at the constraint type.
12476 switch (*constraint) {
12478 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12489 if (CallOperandVal->getType()->isIntegerTy())
12490 weight = CW_SpecificReg;
12495 if (type->isFloatingPointTy())
12496 weight = CW_SpecificReg;
12499 if (type->isX86_MMXTy() && Subtarget->hasMMX())
12500 weight = CW_SpecificReg;
12504 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12505 weight = CW_Register;
12508 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12509 if (C->getZExtValue() <= 31)
12510 weight = CW_Constant;
12514 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12515 if (C->getZExtValue() <= 63)
12516 weight = CW_Constant;
12520 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12521 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12522 weight = CW_Constant;
12526 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12527 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12528 weight = CW_Constant;
12532 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12533 if (C->getZExtValue() <= 3)
12534 weight = CW_Constant;
12538 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12539 if (C->getZExtValue() <= 0xff)
12540 weight = CW_Constant;
12545 if (dyn_cast<ConstantFP>(CallOperandVal)) {
12546 weight = CW_Constant;
12550 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12551 if ((C->getSExtValue() >= -0x80000000LL) &&
12552 (C->getSExtValue() <= 0x7fffffffLL))
12553 weight = CW_Constant;
12557 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12558 if (C->getZExtValue() <= 0xffffffff)
12559 weight = CW_Constant;
12566 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12567 /// with another that has more specific requirements based on the type of the
12568 /// corresponding operand.
12569 const char *X86TargetLowering::
12570 LowerXConstraint(EVT ConstraintVT) const {
12571 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12572 // 'f' like normal targets.
12573 if (ConstraintVT.isFloatingPoint()) {
12574 if (Subtarget->hasXMMInt())
12576 if (Subtarget->hasXMM())
12580 return TargetLowering::LowerXConstraint(ConstraintVT);
12583 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12584 /// vector. If it is invalid, don't add anything to Ops.
12585 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12587 std::vector<SDValue>&Ops,
12588 SelectionDAG &DAG) const {
12589 SDValue Result(0, 0);
12591 switch (Constraint) {
12594 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12595 if (C->getZExtValue() <= 31) {
12596 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12602 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12603 if (C->getZExtValue() <= 63) {
12604 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12610 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12611 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12612 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12618 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12619 if (C->getZExtValue() <= 255) {
12620 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12626 // 32-bit signed value
12627 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12628 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12629 C->getSExtValue())) {
12630 // Widen to 64 bits here to get it sign extended.
12631 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12634 // FIXME gcc accepts some relocatable values here too, but only in certain
12635 // memory models; it's complicated.
12640 // 32-bit unsigned value
12641 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12642 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12643 C->getZExtValue())) {
12644 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12648 // FIXME gcc accepts some relocatable values here too, but only in certain
12649 // memory models; it's complicated.
12653 // Literal immediates are always ok.
12654 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12655 // Widen to 64 bits here to get it sign extended.
12656 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12660 // In any sort of PIC mode addresses need to be computed at runtime by
12661 // adding in a register or some sort of table lookup. These can't
12662 // be used as immediates.
12663 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12666 // If we are in non-pic codegen mode, we allow the address of a global (with
12667 // an optional displacement) to be used with 'i'.
12668 GlobalAddressSDNode *GA = 0;
12669 int64_t Offset = 0;
12671 // Match either (GA), (GA+C), (GA+C1+C2), etc.
12673 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12674 Offset += GA->getOffset();
12676 } else if (Op.getOpcode() == ISD::ADD) {
12677 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12678 Offset += C->getZExtValue();
12679 Op = Op.getOperand(0);
12682 } else if (Op.getOpcode() == ISD::SUB) {
12683 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12684 Offset += -C->getZExtValue();
12685 Op = Op.getOperand(0);
12690 // Otherwise, this isn't something we can handle, reject it.
12694 const GlobalValue *GV = GA->getGlobal();
12695 // If we require an extra load to get this address, as in PIC mode, we
12696 // can't accept it.
12697 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12698 getTargetMachine())))
12701 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12702 GA->getValueType(0), Offset);
12707 if (Result.getNode()) {
12708 Ops.push_back(Result);
12711 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12714 std::vector<unsigned> X86TargetLowering::
12715 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12717 if (Constraint.size() == 1) {
12718 // FIXME: not handling fp-stack yet!
12719 switch (Constraint[0]) { // GCC X86 Constraint Letters
12720 default: break; // Unknown constraint letter
12721 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12722 if (Subtarget->is64Bit()) {
12723 if (VT == MVT::i32)
12724 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12725 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12726 X86::R10D,X86::R11D,X86::R12D,
12727 X86::R13D,X86::R14D,X86::R15D,
12728 X86::EBP, X86::ESP, 0);
12729 else if (VT == MVT::i16)
12730 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
12731 X86::SI, X86::DI, X86::R8W,X86::R9W,
12732 X86::R10W,X86::R11W,X86::R12W,
12733 X86::R13W,X86::R14W,X86::R15W,
12734 X86::BP, X86::SP, 0);
12735 else if (VT == MVT::i8)
12736 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
12737 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12738 X86::R10B,X86::R11B,X86::R12B,
12739 X86::R13B,X86::R14B,X86::R15B,
12740 X86::BPL, X86::SPL, 0);
12742 else if (VT == MVT::i64)
12743 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12744 X86::RSI, X86::RDI, X86::R8, X86::R9,
12745 X86::R10, X86::R11, X86::R12,
12746 X86::R13, X86::R14, X86::R15,
12747 X86::RBP, X86::RSP, 0);
12751 // 32-bit fallthrough
12752 case 'Q': // Q_REGS
12753 if (VT == MVT::i32)
12754 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12755 else if (VT == MVT::i16)
12756 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12757 else if (VT == MVT::i8)
12758 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12759 else if (VT == MVT::i64)
12760 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12765 return std::vector<unsigned>();
12768 std::pair<unsigned, const TargetRegisterClass*>
12769 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12771 // First, see if this is a constraint that directly corresponds to an LLVM
12773 if (Constraint.size() == 1) {
12774 // GCC Constraint Letters
12775 switch (Constraint[0]) {
12777 case 'r': // GENERAL_REGS
12778 case 'l': // INDEX_REGS
12780 return std::make_pair(0U, X86::GR8RegisterClass);
12781 if (VT == MVT::i16)
12782 return std::make_pair(0U, X86::GR16RegisterClass);
12783 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
12784 return std::make_pair(0U, X86::GR32RegisterClass);
12785 return std::make_pair(0U, X86::GR64RegisterClass);
12786 case 'R': // LEGACY_REGS
12788 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12789 if (VT == MVT::i16)
12790 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12791 if (VT == MVT::i32 || !Subtarget->is64Bit())
12792 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12793 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12794 case 'f': // FP Stack registers.
12795 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12796 // value to the correct fpstack register class.
12797 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12798 return std::make_pair(0U, X86::RFP32RegisterClass);
12799 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12800 return std::make_pair(0U, X86::RFP64RegisterClass);
12801 return std::make_pair(0U, X86::RFP80RegisterClass);
12802 case 'y': // MMX_REGS if MMX allowed.
12803 if (!Subtarget->hasMMX()) break;
12804 return std::make_pair(0U, X86::VR64RegisterClass);
12805 case 'Y': // SSE_REGS if SSE2 allowed
12806 if (!Subtarget->hasXMMInt()) break;
12808 case 'x': // SSE_REGS if SSE1 allowed
12809 if (!Subtarget->hasXMM()) break;
12811 switch (VT.getSimpleVT().SimpleTy) {
12813 // Scalar SSE types.
12816 return std::make_pair(0U, X86::FR32RegisterClass);
12819 return std::make_pair(0U, X86::FR64RegisterClass);
12827 return std::make_pair(0U, X86::VR128RegisterClass);
12833 // Use the default implementation in TargetLowering to convert the register
12834 // constraint into a member of a register class.
12835 std::pair<unsigned, const TargetRegisterClass*> Res;
12836 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12838 // Not found as a standard register?
12839 if (Res.second == 0) {
12840 // Map st(0) -> st(7) -> ST0
12841 if (Constraint.size() == 7 && Constraint[0] == '{' &&
12842 tolower(Constraint[1]) == 's' &&
12843 tolower(Constraint[2]) == 't' &&
12844 Constraint[3] == '(' &&
12845 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12846 Constraint[5] == ')' &&
12847 Constraint[6] == '}') {
12849 Res.first = X86::ST0+Constraint[4]-'0';
12850 Res.second = X86::RFP80RegisterClass;
12854 // GCC allows "st(0)" to be called just plain "st".
12855 if (StringRef("{st}").equals_lower(Constraint)) {
12856 Res.first = X86::ST0;
12857 Res.second = X86::RFP80RegisterClass;
12862 if (StringRef("{flags}").equals_lower(Constraint)) {
12863 Res.first = X86::EFLAGS;
12864 Res.second = X86::CCRRegisterClass;
12868 // 'A' means EAX + EDX.
12869 if (Constraint == "A") {
12870 Res.first = X86::EAX;
12871 Res.second = X86::GR32_ADRegisterClass;
12877 // Otherwise, check to see if this is a register class of the wrong value
12878 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12879 // turn into {ax},{dx}.
12880 if (Res.second->hasType(VT))
12881 return Res; // Correct type already, nothing to do.
12883 // All of the single-register GCC register classes map their values onto
12884 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
12885 // really want an 8-bit or 32-bit register, map to the appropriate register
12886 // class and return the appropriate register.
12887 if (Res.second == X86::GR16RegisterClass) {
12888 if (VT == MVT::i8) {
12889 unsigned DestReg = 0;
12890 switch (Res.first) {
12892 case X86::AX: DestReg = X86::AL; break;
12893 case X86::DX: DestReg = X86::DL; break;
12894 case X86::CX: DestReg = X86::CL; break;
12895 case X86::BX: DestReg = X86::BL; break;
12898 Res.first = DestReg;
12899 Res.second = X86::GR8RegisterClass;
12901 } else if (VT == MVT::i32) {
12902 unsigned DestReg = 0;
12903 switch (Res.first) {
12905 case X86::AX: DestReg = X86::EAX; break;
12906 case X86::DX: DestReg = X86::EDX; break;
12907 case X86::CX: DestReg = X86::ECX; break;
12908 case X86::BX: DestReg = X86::EBX; break;
12909 case X86::SI: DestReg = X86::ESI; break;
12910 case X86::DI: DestReg = X86::EDI; break;
12911 case X86::BP: DestReg = X86::EBP; break;
12912 case X86::SP: DestReg = X86::ESP; break;
12915 Res.first = DestReg;
12916 Res.second = X86::GR32RegisterClass;
12918 } else if (VT == MVT::i64) {
12919 unsigned DestReg = 0;
12920 switch (Res.first) {
12922 case X86::AX: DestReg = X86::RAX; break;
12923 case X86::DX: DestReg = X86::RDX; break;
12924 case X86::CX: DestReg = X86::RCX; break;
12925 case X86::BX: DestReg = X86::RBX; break;
12926 case X86::SI: DestReg = X86::RSI; break;
12927 case X86::DI: DestReg = X86::RDI; break;
12928 case X86::BP: DestReg = X86::RBP; break;
12929 case X86::SP: DestReg = X86::RSP; break;
12932 Res.first = DestReg;
12933 Res.second = X86::GR64RegisterClass;
12936 } else if (Res.second == X86::FR32RegisterClass ||
12937 Res.second == X86::FR64RegisterClass ||
12938 Res.second == X86::VR128RegisterClass) {
12939 // Handle references to XMM physical registers that got mapped into the
12940 // wrong class. This can happen with constraints like {xmm0} where the
12941 // target independent register mapper will just pick the first match it can
12942 // find, ignoring the required type.
12943 if (VT == MVT::f32)
12944 Res.second = X86::FR32RegisterClass;
12945 else if (VT == MVT::f64)
12946 Res.second = X86::FR64RegisterClass;
12947 else if (X86::VR128RegisterClass->hasType(VT))
12948 Res.second = X86::VR128RegisterClass;