1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
55 using namespace dwarf;
57 STATISTIC(NumTailCalls, "Number of tail calls");
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
63 static SDValue Insert128BitVector(SDValue Result,
69 static SDValue Extract128BitVector(SDValue Vec,
74 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
77 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
78 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
79 /// simple subregister reference. Idx is an index in the 128 bits we
80 /// want. It need not be aligned to a 128-bit bounday. That makes
81 /// lowering EXTRACT_VECTOR_ELT operations easier.
82 static SDValue Extract128BitVector(SDValue Vec,
86 EVT VT = Vec.getValueType();
87 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
89 EVT ElVT = VT.getVectorElementType();
91 int Factor = VT.getSizeInBits() / 128;
93 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(),
95 VT.getVectorNumElements() / Factor);
97 // Extract from UNDEF is UNDEF.
98 if (Vec.getOpcode() == ISD::UNDEF)
99 return DAG.getNode(ISD::UNDEF, dl, ResultVT);
101 if (isa<ConstantSDNode>(Idx)) {
102 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
104 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
105 // we can match to VEXTRACTF128.
106 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
108 // This is the index of the first element of the 128-bit chunk
110 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
113 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
115 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
124 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
125 /// sets things up to match to an AVX VINSERTF128 instruction or a
126 /// simple superregister reference. Idx is an index in the 128 bits
127 /// we want. It need not be aligned to a 128-bit bounday. That makes
128 /// lowering INSERT_VECTOR_ELT operations easier.
129 static SDValue Insert128BitVector(SDValue Result,
134 if (isa<ConstantSDNode>(Idx)) {
135 EVT VT = Vec.getValueType();
136 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
138 EVT ElVT = VT.getVectorElementType();
140 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
142 EVT ResultVT = Result.getValueType();
144 // Insert the relevant 128 bits.
145 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
147 // This is the index of the first element of the 128-bit chunk
149 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
152 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
154 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
162 /// Given two vectors, concat them.
163 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
164 DebugLoc dl = Lower.getDebugLoc();
166 assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
168 EVT VT = EVT::getVectorVT(*DAG.getContext(),
169 Lower.getValueType().getVectorElementType(),
170 Lower.getValueType().getVectorNumElements() * 2);
172 // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
173 assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
175 // Insert the upper subvector.
176 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
178 // This is half the length of the result
179 // vector. Start inserting the upper 128
181 Lower.getValueType().getVectorNumElements(),
185 // Insert the lower subvector.
186 Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
190 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
191 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
192 bool is64Bit = Subtarget->is64Bit();
194 if (Subtarget->isTargetEnvMacho()) {
196 return new X8664_MachoTargetObjectFile();
197 return new TargetLoweringObjectFileMachO();
200 if (Subtarget->isTargetELF()) {
202 return new X8664_ELFTargetObjectFile(TM);
203 return new X8632_ELFTargetObjectFile(TM);
205 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
206 return new TargetLoweringObjectFileCOFF();
207 llvm_unreachable("unknown subtarget type");
210 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
211 : TargetLowering(TM, createTLOF(TM)) {
212 Subtarget = &TM.getSubtarget<X86Subtarget>();
213 X86ScalarSSEf64 = Subtarget->hasXMMInt();
214 X86ScalarSSEf32 = Subtarget->hasXMM();
215 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
217 RegInfo = TM.getRegisterInfo();
218 TD = getTargetData();
220 // Set up the TargetLowering object.
221 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
223 // X86 is weird, it always uses i8 for shift amounts and setcc results.
224 setBooleanContents(ZeroOrOneBooleanContent);
226 // For 64-bit since we have so many registers use the ILP scheduler, for
227 // 32-bit code use the register pressure specific scheduling.
228 if (Subtarget->is64Bit())
229 setSchedulingPreference(Sched::ILP);
231 setSchedulingPreference(Sched::RegPressure);
232 setStackPointerRegisterToSaveRestore(X86StackPtr);
234 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
235 // Setup Windows compiler runtime calls.
236 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
237 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
238 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
239 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
240 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
241 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
242 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
243 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
246 if (Subtarget->isTargetDarwin()) {
247 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
248 setUseUnderscoreSetJmp(false);
249 setUseUnderscoreLongJmp(false);
250 } else if (Subtarget->isTargetMingw()) {
251 // MS runtime is weird: it exports _setjmp, but longjmp!
252 setUseUnderscoreSetJmp(true);
253 setUseUnderscoreLongJmp(false);
255 setUseUnderscoreSetJmp(true);
256 setUseUnderscoreLongJmp(true);
259 // Set up the register classes.
260 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
261 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
262 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
263 if (Subtarget->is64Bit())
264 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
266 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
268 // We don't accept any truncstore of integer registers.
269 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
270 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
271 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
272 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
273 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
274 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
276 // SETOEQ and SETUNE require checking two conditions.
277 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
278 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
279 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
280 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
281 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
282 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
284 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
286 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
287 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
288 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
290 if (Subtarget->is64Bit()) {
291 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
292 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
293 } else if (!UseSoftFloat) {
294 // We have an algorithm for SSE2->double, and we turn this into a
295 // 64-bit FILD followed by conditional FADD for other targets.
296 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
297 // We have an algorithm for SSE2, and we turn this into a 64-bit
298 // FILD for other targets.
299 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
302 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
304 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
305 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
308 // SSE has no i16 to fp conversion, only i32
309 if (X86ScalarSSEf32) {
310 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
311 // f32 and f64 cases are Legal, f80 case is not
312 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
314 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
315 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
318 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
319 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
322 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
323 // are Legal, f80 is custom lowered.
324 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
325 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
327 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
329 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
330 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
332 if (X86ScalarSSEf32) {
333 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
334 // f32 and f64 cases are Legal, f80 case is not
335 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
337 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
338 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
341 // Handle FP_TO_UINT by promoting the destination to a larger signed
343 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
344 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
345 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
347 if (Subtarget->is64Bit()) {
348 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
349 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
350 } else if (!UseSoftFloat) {
351 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
352 // Expand FP_TO_UINT into a select.
353 // FIXME: We would like to use a Custom expander here eventually to do
354 // the optimal thing for SSE vs. the default expansion in the legalizer.
355 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
357 // With SSE3 we can use fisttpll to convert to a signed i64; without
358 // SSE, we're stuck with a fistpll.
359 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
362 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
363 if (!X86ScalarSSEf64) {
364 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
365 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
366 if (Subtarget->is64Bit()) {
367 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
368 // Without SSE, i64->f64 goes through memory.
369 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
373 // Scalar integer divide and remainder are lowered to use operations that
374 // produce two results, to match the available instructions. This exposes
375 // the two-result form to trivial CSE, which is able to combine x/y and x%y
376 // into a single instruction.
378 // Scalar integer multiply-high is also lowered to use two-result
379 // operations, to match the available instructions. However, plain multiply
380 // (low) operations are left as Legal, as there are single-result
381 // instructions for this in x86. Using the two-result multiply instructions
382 // when both high and low results are needed must be arranged by dagcombine.
383 for (unsigned i = 0, e = 4; i != e; ++i) {
385 setOperationAction(ISD::MULHS, VT, Expand);
386 setOperationAction(ISD::MULHU, VT, Expand);
387 setOperationAction(ISD::SDIV, VT, Expand);
388 setOperationAction(ISD::UDIV, VT, Expand);
389 setOperationAction(ISD::SREM, VT, Expand);
390 setOperationAction(ISD::UREM, VT, Expand);
392 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
393 setOperationAction(ISD::ADDC, VT, Custom);
394 setOperationAction(ISD::ADDE, VT, Custom);
395 setOperationAction(ISD::SUBC, VT, Custom);
396 setOperationAction(ISD::SUBE, VT, Custom);
399 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
400 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
401 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
402 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
403 if (Subtarget->is64Bit())
404 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
405 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
406 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
407 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
408 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
409 setOperationAction(ISD::FREM , MVT::f32 , Expand);
410 setOperationAction(ISD::FREM , MVT::f64 , Expand);
411 setOperationAction(ISD::FREM , MVT::f80 , Expand);
412 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
414 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
415 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
416 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
417 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
418 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
419 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
420 if (Subtarget->is64Bit()) {
421 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
422 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
425 if (Subtarget->hasPOPCNT()) {
426 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
428 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
429 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
430 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
431 if (Subtarget->is64Bit())
432 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
435 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
436 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
438 // These should be promoted to a larger select which is supported.
439 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
440 // X86 wants to expand cmov itself.
441 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
442 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
443 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
444 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
445 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
446 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
447 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
448 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
449 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
450 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
451 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
452 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
453 if (Subtarget->is64Bit()) {
454 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
455 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
457 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
460 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
461 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
462 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
463 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
464 if (Subtarget->is64Bit())
465 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
466 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
467 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
468 if (Subtarget->is64Bit()) {
469 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
470 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
471 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
472 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
473 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
475 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
476 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
477 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
478 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
479 if (Subtarget->is64Bit()) {
480 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
481 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
482 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
485 if (Subtarget->hasXMM())
486 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
488 // We may not have a libcall for MEMBARRIER so we should lower this.
489 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
491 // On X86 and X86-64, atomic operations are lowered to locked instructions.
492 // Locked instructions, in turn, have implicit fence semantics (all memory
493 // operations are flushed before issuing the locked instruction, and they
494 // are not buffered), so we can fold away the common pattern of
495 // fence-atomic-fence.
496 setShouldFoldAtomicFences(true);
498 // Expand certain atomics
499 for (unsigned i = 0, e = 4; i != e; ++i) {
501 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
502 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
505 if (!Subtarget->is64Bit()) {
506 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
507 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
508 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
509 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
510 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
511 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
512 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
515 // FIXME - use subtarget debug flags
516 if (!Subtarget->isTargetDarwin() &&
517 !Subtarget->isTargetELF() &&
518 !Subtarget->isTargetCygMing()) {
519 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
522 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
523 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
524 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
525 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
526 if (Subtarget->is64Bit()) {
527 setExceptionPointerRegister(X86::RAX);
528 setExceptionSelectorRegister(X86::RDX);
530 setExceptionPointerRegister(X86::EAX);
531 setExceptionSelectorRegister(X86::EDX);
533 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
534 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
536 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
538 setOperationAction(ISD::TRAP, MVT::Other, Legal);
540 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
541 setOperationAction(ISD::VASTART , MVT::Other, Custom);
542 setOperationAction(ISD::VAEND , MVT::Other, Expand);
543 if (Subtarget->is64Bit()) {
544 setOperationAction(ISD::VAARG , MVT::Other, Custom);
545 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
547 setOperationAction(ISD::VAARG , MVT::Other, Expand);
548 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
551 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
552 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
553 setOperationAction(ISD::DYNAMIC_STACKALLOC,
554 (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
555 (Subtarget->isTargetCOFF()
556 && !Subtarget->isTargetEnvMacho()
559 if (!UseSoftFloat && X86ScalarSSEf64) {
560 // f32 and f64 use SSE.
561 // Set up the FP register classes.
562 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
563 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
565 // Use ANDPD to simulate FABS.
566 setOperationAction(ISD::FABS , MVT::f64, Custom);
567 setOperationAction(ISD::FABS , MVT::f32, Custom);
569 // Use XORP to simulate FNEG.
570 setOperationAction(ISD::FNEG , MVT::f64, Custom);
571 setOperationAction(ISD::FNEG , MVT::f32, Custom);
573 // Use ANDPD and ORPD to simulate FCOPYSIGN.
574 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
575 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
577 // We don't support sin/cos/fmod
578 setOperationAction(ISD::FSIN , MVT::f64, Expand);
579 setOperationAction(ISD::FCOS , MVT::f64, Expand);
580 setOperationAction(ISD::FSIN , MVT::f32, Expand);
581 setOperationAction(ISD::FCOS , MVT::f32, Expand);
583 // Expand FP immediates into loads from the stack, except for the special
585 addLegalFPImmediate(APFloat(+0.0)); // xorpd
586 addLegalFPImmediate(APFloat(+0.0f)); // xorps
587 } else if (!UseSoftFloat && X86ScalarSSEf32) {
588 // Use SSE for f32, x87 for f64.
589 // Set up the FP register classes.
590 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
591 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
593 // Use ANDPS to simulate FABS.
594 setOperationAction(ISD::FABS , MVT::f32, Custom);
596 // Use XORP to simulate FNEG.
597 setOperationAction(ISD::FNEG , MVT::f32, Custom);
599 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
601 // Use ANDPS and ORPS to simulate FCOPYSIGN.
602 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
603 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
605 // We don't support sin/cos/fmod
606 setOperationAction(ISD::FSIN , MVT::f32, Expand);
607 setOperationAction(ISD::FCOS , MVT::f32, Expand);
609 // Special cases we handle for FP constants.
610 addLegalFPImmediate(APFloat(+0.0f)); // xorps
611 addLegalFPImmediate(APFloat(+0.0)); // FLD0
612 addLegalFPImmediate(APFloat(+1.0)); // FLD1
613 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
614 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
617 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
618 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
620 } else if (!UseSoftFloat) {
621 // f32 and f64 in x87.
622 // Set up the FP register classes.
623 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
624 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
626 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
627 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
628 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
629 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
632 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
633 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
635 addLegalFPImmediate(APFloat(+0.0)); // FLD0
636 addLegalFPImmediate(APFloat(+1.0)); // FLD1
637 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
638 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
639 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
640 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
641 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
642 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
645 // Long double always uses X87.
647 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
648 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
649 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
651 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
652 addLegalFPImmediate(TmpFlt); // FLD0
654 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
657 APFloat TmpFlt2(+1.0);
658 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
660 addLegalFPImmediate(TmpFlt2); // FLD1
661 TmpFlt2.changeSign();
662 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
666 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
667 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
671 // Always use a library call for pow.
672 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
673 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
674 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
676 setOperationAction(ISD::FLOG, MVT::f80, Expand);
677 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
678 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
679 setOperationAction(ISD::FEXP, MVT::f80, Expand);
680 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
682 // First set operation action for all vector types to either promote
683 // (for widening) or expand (for scalarization). Then we will selectively
684 // turn on ones that can be effectively codegen'd.
685 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
686 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
687 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
688 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
689 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
690 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
691 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
692 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
693 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
694 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
695 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
696 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
698 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
699 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
700 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
701 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
702 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
703 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
704 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
705 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
737 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
741 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
742 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
743 setTruncStoreAction((MVT::SimpleValueType)VT,
744 (MVT::SimpleValueType)InnerVT, Expand);
745 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
747 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
750 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
751 // with -msoft-float, disable use of MMX as well.
752 if (!UseSoftFloat && Subtarget->hasMMX()) {
753 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
754 // No operations on x86mmx supported, everything uses intrinsics.
757 // MMX-sized vectors (other than x86mmx) are expected to be expanded
758 // into smaller operations.
759 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
760 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
761 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
762 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
763 setOperationAction(ISD::AND, MVT::v8i8, Expand);
764 setOperationAction(ISD::AND, MVT::v4i16, Expand);
765 setOperationAction(ISD::AND, MVT::v2i32, Expand);
766 setOperationAction(ISD::AND, MVT::v1i64, Expand);
767 setOperationAction(ISD::OR, MVT::v8i8, Expand);
768 setOperationAction(ISD::OR, MVT::v4i16, Expand);
769 setOperationAction(ISD::OR, MVT::v2i32, Expand);
770 setOperationAction(ISD::OR, MVT::v1i64, Expand);
771 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
772 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
773 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
774 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
775 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
776 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
777 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
778 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
779 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
780 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
781 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
782 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
783 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
784 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
785 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
786 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
787 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
789 if (!UseSoftFloat && Subtarget->hasXMM()) {
790 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
792 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
793 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
794 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
795 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
796 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
797 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
798 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
799 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
800 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
801 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
802 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
803 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
806 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
807 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
809 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
810 // registers cannot be used even for integer operations.
811 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
812 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
813 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
814 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
816 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
817 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
818 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
819 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
820 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
821 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
822 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
823 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
824 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
825 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
826 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
827 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
828 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
829 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
830 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
831 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
833 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
834 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
835 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
836 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
838 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
839 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
840 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
841 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
842 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
844 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
845 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
846 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
847 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
848 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
850 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
851 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
852 EVT VT = (MVT::SimpleValueType)i;
853 // Do not attempt to custom lower non-power-of-2 vectors
854 if (!isPowerOf2_32(VT.getVectorNumElements()))
856 // Do not attempt to custom lower non-128-bit vectors
857 if (!VT.is128BitVector())
859 setOperationAction(ISD::BUILD_VECTOR,
860 VT.getSimpleVT().SimpleTy, Custom);
861 setOperationAction(ISD::VECTOR_SHUFFLE,
862 VT.getSimpleVT().SimpleTy, Custom);
863 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
864 VT.getSimpleVT().SimpleTy, Custom);
867 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
868 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
869 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
870 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
871 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
872 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
874 if (Subtarget->is64Bit()) {
875 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
876 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
879 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
880 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
881 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
884 // Do not attempt to promote non-128-bit vectors
885 if (!VT.is128BitVector())
888 setOperationAction(ISD::AND, SVT, Promote);
889 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
890 setOperationAction(ISD::OR, SVT, Promote);
891 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
892 setOperationAction(ISD::XOR, SVT, Promote);
893 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
894 setOperationAction(ISD::LOAD, SVT, Promote);
895 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
896 setOperationAction(ISD::SELECT, SVT, Promote);
897 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
900 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
902 // Custom lower v2i64 and v2f64 selects.
903 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
904 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
905 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
906 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
908 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
909 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
912 if (Subtarget->hasSSE41()) {
913 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
914 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
915 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
916 setOperationAction(ISD::FRINT, MVT::f32, Legal);
917 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
918 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
919 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
920 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
921 setOperationAction(ISD::FRINT, MVT::f64, Legal);
922 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
924 // FIXME: Do we need to handle scalar-to-vector here?
925 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
927 // Can turn SHL into an integer multiply.
928 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
929 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
931 // i8 and i16 vectors are custom , because the source register and source
932 // source memory operand types are not the same width. f32 vectors are
933 // custom since the immediate controlling the insert encodes additional
935 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
936 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
937 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
938 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
940 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
941 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
942 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
943 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
945 if (Subtarget->is64Bit()) {
946 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
947 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
951 if (Subtarget->hasSSE2()) {
952 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
953 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
954 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
956 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
957 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
958 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
960 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
961 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
964 if (Subtarget->hasSSE42())
965 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
967 if (!UseSoftFloat && Subtarget->hasAVX()) {
968 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
969 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
970 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
971 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
972 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
974 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
975 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
976 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
977 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
979 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
980 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
981 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
982 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
983 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
984 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
986 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
987 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
988 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
989 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
990 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
991 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
993 // Custom lower build_vector, vector_shuffle, scalar_to_vector,
994 // insert_vector_elt extract_subvector and extract_vector_elt for
996 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
997 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
999 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1000 // Do not attempt to custom lower non-256-bit vectors
1001 if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
1002 || (MVT(VT).getSizeInBits() < 256))
1004 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1005 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1006 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1007 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1008 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1010 // Custom-lower insert_subvector and extract_subvector based on
1012 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1013 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1015 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1016 // Do not attempt to custom lower non-256-bit vectors
1017 if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1020 if (MVT(VT).getSizeInBits() == 128) {
1021 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1023 else if (MVT(VT).getSizeInBits() == 256) {
1024 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1028 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1029 // Don't promote loads because we need them for VPERM vector index versions.
1031 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1032 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1034 if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1035 || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1037 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
1038 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v4i64);
1039 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
1040 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v4i64);
1041 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
1042 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v4i64);
1043 //setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
1044 //AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v4i64);
1045 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1046 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1050 // We want to custom lower some of our intrinsics.
1051 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1054 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1055 // handle type legalization for these operations here.
1057 // FIXME: We really should do custom legalization for addition and
1058 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1059 // than generic legalization for 64-bit multiplication-with-overflow, though.
1060 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1061 // Add/Sub/Mul with overflow operations are custom lowered.
1063 setOperationAction(ISD::SADDO, VT, Custom);
1064 setOperationAction(ISD::UADDO, VT, Custom);
1065 setOperationAction(ISD::SSUBO, VT, Custom);
1066 setOperationAction(ISD::USUBO, VT, Custom);
1067 setOperationAction(ISD::SMULO, VT, Custom);
1068 setOperationAction(ISD::UMULO, VT, Custom);
1071 // There are no 8-bit 3-address imul/mul instructions
1072 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1073 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1075 if (!Subtarget->is64Bit()) {
1076 // These libcalls are not available in 32-bit.
1077 setLibcallName(RTLIB::SHL_I128, 0);
1078 setLibcallName(RTLIB::SRL_I128, 0);
1079 setLibcallName(RTLIB::SRA_I128, 0);
1082 // We have target-specific dag combine patterns for the following nodes:
1083 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1084 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1085 setTargetDAGCombine(ISD::BUILD_VECTOR);
1086 setTargetDAGCombine(ISD::SELECT);
1087 setTargetDAGCombine(ISD::SHL);
1088 setTargetDAGCombine(ISD::SRA);
1089 setTargetDAGCombine(ISD::SRL);
1090 setTargetDAGCombine(ISD::OR);
1091 setTargetDAGCombine(ISD::AND);
1092 setTargetDAGCombine(ISD::ADD);
1093 setTargetDAGCombine(ISD::SUB);
1094 setTargetDAGCombine(ISD::STORE);
1095 setTargetDAGCombine(ISD::ZERO_EXTEND);
1096 if (Subtarget->is64Bit())
1097 setTargetDAGCombine(ISD::MUL);
1099 computeRegisterProperties();
1101 // On Darwin, -Os means optimize for size without hurting performance,
1102 // do not reduce the limit.
1103 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1104 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1105 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1106 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1107 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1108 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1109 setPrefLoopAlignment(16);
1110 benefitFromCodePlacementOpt = true;
1112 setPrefFunctionAlignment(4);
1116 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1121 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1122 /// the desired ByVal argument alignment.
1123 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1126 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1127 if (VTy->getBitWidth() == 128)
1129 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1130 unsigned EltAlign = 0;
1131 getMaxByValAlign(ATy->getElementType(), EltAlign);
1132 if (EltAlign > MaxAlign)
1133 MaxAlign = EltAlign;
1134 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1135 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1136 unsigned EltAlign = 0;
1137 getMaxByValAlign(STy->getElementType(i), EltAlign);
1138 if (EltAlign > MaxAlign)
1139 MaxAlign = EltAlign;
1147 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1148 /// function arguments in the caller parameter area. For X86, aggregates
1149 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1150 /// are at 4-byte boundaries.
1151 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1152 if (Subtarget->is64Bit()) {
1153 // Max of 8 and alignment of type.
1154 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1161 if (Subtarget->hasXMM())
1162 getMaxByValAlign(Ty, Align);
1166 /// getOptimalMemOpType - Returns the target specific optimal type for load
1167 /// and store operations as a result of memset, memcpy, and memmove
1168 /// lowering. If DstAlign is zero that means it's safe to destination
1169 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1170 /// means there isn't a need to check it against alignment requirement,
1171 /// probably because the source does not need to be loaded. If
1172 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1173 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1174 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1175 /// constant so it does not need to be loaded.
1176 /// It returns EVT::Other if the type should be determined using generic
1177 /// target-independent logic.
1179 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1180 unsigned DstAlign, unsigned SrcAlign,
1181 bool NonScalarIntSafe,
1183 MachineFunction &MF) const {
1184 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1185 // linux. This is because the stack realignment code can't handle certain
1186 // cases like PR2962. This should be removed when PR2962 is fixed.
1187 const Function *F = MF.getFunction();
1188 if (NonScalarIntSafe &&
1189 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1191 (Subtarget->isUnalignedMemAccessFast() ||
1192 ((DstAlign == 0 || DstAlign >= 16) &&
1193 (SrcAlign == 0 || SrcAlign >= 16))) &&
1194 Subtarget->getStackAlignment() >= 16) {
1195 if (Subtarget->hasSSE2())
1197 if (Subtarget->hasSSE1())
1199 } else if (!MemcpyStrSrc && Size >= 8 &&
1200 !Subtarget->is64Bit() &&
1201 Subtarget->getStackAlignment() >= 8 &&
1202 Subtarget->hasXMMInt()) {
1203 // Do not use f64 to lower memcpy if source is string constant. It's
1204 // better to use i32 to avoid the loads.
1208 if (Subtarget->is64Bit() && Size >= 8)
1213 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1214 /// current function. The returned value is a member of the
1215 /// MachineJumpTableInfo::JTEntryKind enum.
1216 unsigned X86TargetLowering::getJumpTableEncoding() const {
1217 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1219 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1220 Subtarget->isPICStyleGOT())
1221 return MachineJumpTableInfo::EK_Custom32;
1223 // Otherwise, use the normal jump table encoding heuristics.
1224 return TargetLowering::getJumpTableEncoding();
1228 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1229 const MachineBasicBlock *MBB,
1230 unsigned uid,MCContext &Ctx) const{
1231 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1232 Subtarget->isPICStyleGOT());
1233 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1235 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1236 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1239 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1241 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1242 SelectionDAG &DAG) const {
1243 if (!Subtarget->is64Bit())
1244 // This doesn't have DebugLoc associated with it, but is not really the
1245 // same as a Register.
1246 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1250 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1251 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1253 const MCExpr *X86TargetLowering::
1254 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1255 MCContext &Ctx) const {
1256 // X86-64 uses RIP relative addressing based on the jump table label.
1257 if (Subtarget->isPICStyleRIPRel())
1258 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1260 // Otherwise, the reference is relative to the PIC base.
1261 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1264 // FIXME: Why this routine is here? Move to RegInfo!
1265 std::pair<const TargetRegisterClass*, uint8_t>
1266 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1267 const TargetRegisterClass *RRC = 0;
1269 switch (VT.getSimpleVT().SimpleTy) {
1271 return TargetLowering::findRepresentativeClass(VT);
1272 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1273 RRC = (Subtarget->is64Bit()
1274 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1277 RRC = X86::VR64RegisterClass;
1279 case MVT::f32: case MVT::f64:
1280 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1281 case MVT::v4f32: case MVT::v2f64:
1282 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1284 RRC = X86::VR128RegisterClass;
1287 return std::make_pair(RRC, Cost);
1290 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1291 unsigned &Offset) const {
1292 if (!Subtarget->isTargetLinux())
1295 if (Subtarget->is64Bit()) {
1296 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1298 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1311 //===----------------------------------------------------------------------===//
1312 // Return Value Calling Convention Implementation
1313 //===----------------------------------------------------------------------===//
1315 #include "X86GenCallingConv.inc"
1318 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1319 const SmallVectorImpl<ISD::OutputArg> &Outs,
1320 LLVMContext &Context) const {
1321 SmallVector<CCValAssign, 16> RVLocs;
1322 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1324 return CCInfo.CheckReturn(Outs, RetCC_X86);
1328 X86TargetLowering::LowerReturn(SDValue Chain,
1329 CallingConv::ID CallConv, bool isVarArg,
1330 const SmallVectorImpl<ISD::OutputArg> &Outs,
1331 const SmallVectorImpl<SDValue> &OutVals,
1332 DebugLoc dl, SelectionDAG &DAG) const {
1333 MachineFunction &MF = DAG.getMachineFunction();
1334 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1336 SmallVector<CCValAssign, 16> RVLocs;
1337 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1338 RVLocs, *DAG.getContext());
1339 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1341 // Add the regs to the liveout set for the function.
1342 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1343 for (unsigned i = 0; i != RVLocs.size(); ++i)
1344 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1345 MRI.addLiveOut(RVLocs[i].getLocReg());
1349 SmallVector<SDValue, 6> RetOps;
1350 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1351 // Operand #1 = Bytes To Pop
1352 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1355 // Copy the result values into the output registers.
1356 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1357 CCValAssign &VA = RVLocs[i];
1358 assert(VA.isRegLoc() && "Can only return in registers!");
1359 SDValue ValToCopy = OutVals[i];
1360 EVT ValVT = ValToCopy.getValueType();
1362 // If this is x86-64, and we disabled SSE, we can't return FP values,
1363 // or SSE or MMX vectors.
1364 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1365 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1366 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1367 report_fatal_error("SSE register return with SSE disabled");
1369 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1370 // llvm-gcc has never done it right and no one has noticed, so this
1371 // should be OK for now.
1372 if (ValVT == MVT::f64 &&
1373 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1374 report_fatal_error("SSE2 register return with SSE2 disabled");
1376 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1377 // the RET instruction and handled by the FP Stackifier.
1378 if (VA.getLocReg() == X86::ST0 ||
1379 VA.getLocReg() == X86::ST1) {
1380 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1381 // change the value to the FP stack register class.
1382 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1383 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1384 RetOps.push_back(ValToCopy);
1385 // Don't emit a copytoreg.
1389 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1390 // which is returned in RAX / RDX.
1391 if (Subtarget->is64Bit()) {
1392 if (ValVT == MVT::x86mmx) {
1393 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1394 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1395 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1397 // If we don't have SSE2 available, convert to v4f32 so the generated
1398 // register is legal.
1399 if (!Subtarget->hasSSE2())
1400 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1405 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1406 Flag = Chain.getValue(1);
1409 // The x86-64 ABI for returning structs by value requires that we copy
1410 // the sret argument into %rax for the return. We saved the argument into
1411 // a virtual register in the entry block, so now we copy the value out
1413 if (Subtarget->is64Bit() &&
1414 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1415 MachineFunction &MF = DAG.getMachineFunction();
1416 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1417 unsigned Reg = FuncInfo->getSRetReturnReg();
1419 "SRetReturnReg should have been set in LowerFormalArguments().");
1420 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1422 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1423 Flag = Chain.getValue(1);
1425 // RAX now acts like a return value.
1426 MRI.addLiveOut(X86::RAX);
1429 RetOps[0] = Chain; // Update chain.
1431 // Add the flag if we have it.
1433 RetOps.push_back(Flag);
1435 return DAG.getNode(X86ISD::RET_FLAG, dl,
1436 MVT::Other, &RetOps[0], RetOps.size());
1439 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1440 if (N->getNumValues() != 1)
1442 if (!N->hasNUsesOfValue(1, 0))
1445 SDNode *Copy = *N->use_begin();
1446 if (Copy->getOpcode() != ISD::CopyToReg &&
1447 Copy->getOpcode() != ISD::FP_EXTEND)
1450 bool HasRet = false;
1451 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1453 if (UI->getOpcode() != X86ISD::RET_FLAG)
1462 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1463 ISD::NodeType ExtendKind) const {
1465 // TODO: Is this also valid on 32-bit?
1466 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1467 ReturnMVT = MVT::i8;
1469 ReturnMVT = MVT::i32;
1471 EVT MinVT = getRegisterType(Context, ReturnMVT);
1472 return VT.bitsLT(MinVT) ? MinVT : VT;
1475 /// LowerCallResult - Lower the result values of a call into the
1476 /// appropriate copies out of appropriate physical registers.
1479 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1480 CallingConv::ID CallConv, bool isVarArg,
1481 const SmallVectorImpl<ISD::InputArg> &Ins,
1482 DebugLoc dl, SelectionDAG &DAG,
1483 SmallVectorImpl<SDValue> &InVals) const {
1485 // Assign locations to each value returned by this call.
1486 SmallVector<CCValAssign, 16> RVLocs;
1487 bool Is64Bit = Subtarget->is64Bit();
1488 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1489 RVLocs, *DAG.getContext());
1490 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1492 // Copy all of the result registers out of their specified physreg.
1493 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1494 CCValAssign &VA = RVLocs[i];
1495 EVT CopyVT = VA.getValVT();
1497 // If this is x86-64, and we disabled SSE, we can't return FP values
1498 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1499 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1500 report_fatal_error("SSE register return with SSE disabled");
1505 // If this is a call to a function that returns an fp value on the floating
1506 // point stack, we must guarantee the the value is popped from the stack, so
1507 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1508 // if the return value is not used. We use the FpGET_ST0 instructions
1510 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1511 // If we prefer to use the value in xmm registers, copy it out as f80 and
1512 // use a truncate to move it from fp stack reg to xmm reg.
1513 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1514 bool isST0 = VA.getLocReg() == X86::ST0;
1516 if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1517 if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1518 if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1519 SDValue Ops[] = { Chain, InFlag };
1520 Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1522 Val = Chain.getValue(0);
1524 // Round the f80 to the right size, which also moves it to the appropriate
1526 if (CopyVT != VA.getValVT())
1527 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1528 // This truncation won't change the value.
1529 DAG.getIntPtrConstant(1));
1531 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1532 CopyVT, InFlag).getValue(1);
1533 Val = Chain.getValue(0);
1535 InFlag = Chain.getValue(2);
1536 InVals.push_back(Val);
1543 //===----------------------------------------------------------------------===//
1544 // C & StdCall & Fast Calling Convention implementation
1545 //===----------------------------------------------------------------------===//
1546 // StdCall calling convention seems to be standard for many Windows' API
1547 // routines and around. It differs from C calling convention just a little:
1548 // callee should clean up the stack, not caller. Symbols should be also
1549 // decorated in some fancy way :) It doesn't support any vector arguments.
1550 // For info on fast calling convention see Fast Calling Convention (tail call)
1551 // implementation LowerX86_32FastCCCallTo.
1553 /// CallIsStructReturn - Determines whether a call uses struct return
1555 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1559 return Outs[0].Flags.isSRet();
1562 /// ArgsAreStructReturn - Determines whether a function uses struct
1563 /// return semantics.
1565 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1569 return Ins[0].Flags.isSRet();
1572 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1573 /// by "Src" to address "Dst" with size and alignment information specified by
1574 /// the specific parameter attribute. The copy will be passed as a byval
1575 /// function parameter.
1577 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1578 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1580 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1582 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1583 /*isVolatile*/false, /*AlwaysInline=*/true,
1584 MachinePointerInfo(), MachinePointerInfo());
1587 /// IsTailCallConvention - Return true if the calling convention is one that
1588 /// supports tail call optimization.
1589 static bool IsTailCallConvention(CallingConv::ID CC) {
1590 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1593 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1594 if (!CI->isTailCall())
1598 CallingConv::ID CalleeCC = CS.getCallingConv();
1599 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1605 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1606 /// a tailcall target by changing its ABI.
1607 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1608 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1612 X86TargetLowering::LowerMemArgument(SDValue Chain,
1613 CallingConv::ID CallConv,
1614 const SmallVectorImpl<ISD::InputArg> &Ins,
1615 DebugLoc dl, SelectionDAG &DAG,
1616 const CCValAssign &VA,
1617 MachineFrameInfo *MFI,
1619 // Create the nodes corresponding to a load from this parameter slot.
1620 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1621 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1622 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1625 // If value is passed by pointer we have address passed instead of the value
1627 if (VA.getLocInfo() == CCValAssign::Indirect)
1628 ValVT = VA.getLocVT();
1630 ValVT = VA.getValVT();
1632 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1633 // changed with more analysis.
1634 // In case of tail call optimization mark all arguments mutable. Since they
1635 // could be overwritten by lowering of arguments in case of a tail call.
1636 if (Flags.isByVal()) {
1637 unsigned Bytes = Flags.getByValSize();
1638 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1639 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1640 return DAG.getFrameIndex(FI, getPointerTy());
1642 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1643 VA.getLocMemOffset(), isImmutable);
1644 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1645 return DAG.getLoad(ValVT, dl, Chain, FIN,
1646 MachinePointerInfo::getFixedStack(FI),
1652 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1653 CallingConv::ID CallConv,
1655 const SmallVectorImpl<ISD::InputArg> &Ins,
1658 SmallVectorImpl<SDValue> &InVals)
1660 MachineFunction &MF = DAG.getMachineFunction();
1661 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1663 const Function* Fn = MF.getFunction();
1664 if (Fn->hasExternalLinkage() &&
1665 Subtarget->isTargetCygMing() &&
1666 Fn->getName() == "main")
1667 FuncInfo->setForceFramePointer(true);
1669 MachineFrameInfo *MFI = MF.getFrameInfo();
1670 bool Is64Bit = Subtarget->is64Bit();
1671 bool IsWin64 = Subtarget->isTargetWin64();
1673 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1674 "Var args not supported with calling convention fastcc or ghc");
1676 // Assign locations to all of the incoming arguments.
1677 SmallVector<CCValAssign, 16> ArgLocs;
1678 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1679 ArgLocs, *DAG.getContext());
1681 // Allocate shadow area for Win64
1683 CCInfo.AllocateStack(32, 8);
1686 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1688 unsigned LastVal = ~0U;
1690 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1691 CCValAssign &VA = ArgLocs[i];
1692 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1694 assert(VA.getValNo() != LastVal &&
1695 "Don't support value assigned to multiple locs yet");
1696 LastVal = VA.getValNo();
1698 if (VA.isRegLoc()) {
1699 EVT RegVT = VA.getLocVT();
1700 TargetRegisterClass *RC = NULL;
1701 if (RegVT == MVT::i32)
1702 RC = X86::GR32RegisterClass;
1703 else if (Is64Bit && RegVT == MVT::i64)
1704 RC = X86::GR64RegisterClass;
1705 else if (RegVT == MVT::f32)
1706 RC = X86::FR32RegisterClass;
1707 else if (RegVT == MVT::f64)
1708 RC = X86::FR64RegisterClass;
1709 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1710 RC = X86::VR256RegisterClass;
1711 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1712 RC = X86::VR128RegisterClass;
1713 else if (RegVT == MVT::x86mmx)
1714 RC = X86::VR64RegisterClass;
1716 llvm_unreachable("Unknown argument type!");
1718 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1719 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1721 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1722 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1724 if (VA.getLocInfo() == CCValAssign::SExt)
1725 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1726 DAG.getValueType(VA.getValVT()));
1727 else if (VA.getLocInfo() == CCValAssign::ZExt)
1728 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1729 DAG.getValueType(VA.getValVT()));
1730 else if (VA.getLocInfo() == CCValAssign::BCvt)
1731 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1733 if (VA.isExtInLoc()) {
1734 // Handle MMX values passed in XMM regs.
1735 if (RegVT.isVector()) {
1736 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1739 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1742 assert(VA.isMemLoc());
1743 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1746 // If value is passed via pointer - do a load.
1747 if (VA.getLocInfo() == CCValAssign::Indirect)
1748 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1749 MachinePointerInfo(), false, false, 0);
1751 InVals.push_back(ArgValue);
1754 // The x86-64 ABI for returning structs by value requires that we copy
1755 // the sret argument into %rax for the return. Save the argument into
1756 // a virtual register so that we can access it from the return points.
1757 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1758 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1759 unsigned Reg = FuncInfo->getSRetReturnReg();
1761 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1762 FuncInfo->setSRetReturnReg(Reg);
1764 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1765 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1768 unsigned StackSize = CCInfo.getNextStackOffset();
1769 // Align stack specially for tail calls.
1770 if (FuncIsMadeTailCallSafe(CallConv))
1771 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1773 // If the function takes variable number of arguments, make a frame index for
1774 // the start of the first vararg value... for expansion of llvm.va_start.
1776 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1777 CallConv != CallingConv::X86_ThisCall)) {
1778 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1781 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1783 // FIXME: We should really autogenerate these arrays
1784 static const unsigned GPR64ArgRegsWin64[] = {
1785 X86::RCX, X86::RDX, X86::R8, X86::R9
1787 static const unsigned GPR64ArgRegs64Bit[] = {
1788 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1790 static const unsigned XMMArgRegs64Bit[] = {
1791 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1792 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1794 const unsigned *GPR64ArgRegs;
1795 unsigned NumXMMRegs = 0;
1798 // The XMM registers which might contain var arg parameters are shadowed
1799 // in their paired GPR. So we only need to save the GPR to their home
1801 TotalNumIntRegs = 4;
1802 GPR64ArgRegs = GPR64ArgRegsWin64;
1804 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1805 GPR64ArgRegs = GPR64ArgRegs64Bit;
1807 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1809 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1812 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1813 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1814 "SSE register cannot be used when SSE is disabled!");
1815 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1816 "SSE register cannot be used when SSE is disabled!");
1817 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1818 // Kernel mode asks for SSE to be disabled, so don't push them
1820 TotalNumXMMRegs = 0;
1823 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1824 // Get to the caller-allocated home save location. Add 8 to account
1825 // for the return address.
1826 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1827 FuncInfo->setRegSaveFrameIndex(
1828 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1829 // Fixup to set vararg frame on shadow area (4 x i64).
1831 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1833 // For X86-64, if there are vararg parameters that are passed via
1834 // registers, then we must store them to their spots on the stack so they
1835 // may be loaded by deferencing the result of va_next.
1836 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1837 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1838 FuncInfo->setRegSaveFrameIndex(
1839 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1843 // Store the integer parameter registers.
1844 SmallVector<SDValue, 8> MemOps;
1845 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1847 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1848 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1849 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1850 DAG.getIntPtrConstant(Offset));
1851 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1852 X86::GR64RegisterClass);
1853 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1855 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1856 MachinePointerInfo::getFixedStack(
1857 FuncInfo->getRegSaveFrameIndex(), Offset),
1859 MemOps.push_back(Store);
1863 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1864 // Now store the XMM (fp + vector) parameter registers.
1865 SmallVector<SDValue, 11> SaveXMMOps;
1866 SaveXMMOps.push_back(Chain);
1868 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1869 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1870 SaveXMMOps.push_back(ALVal);
1872 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1873 FuncInfo->getRegSaveFrameIndex()));
1874 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1875 FuncInfo->getVarArgsFPOffset()));
1877 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1878 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1879 X86::VR128RegisterClass);
1880 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1881 SaveXMMOps.push_back(Val);
1883 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1885 &SaveXMMOps[0], SaveXMMOps.size()));
1888 if (!MemOps.empty())
1889 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1890 &MemOps[0], MemOps.size());
1894 // Some CCs need callee pop.
1895 if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1896 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1898 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1899 // If this is an sret function, the return should pop the hidden pointer.
1900 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1901 FuncInfo->setBytesToPopOnReturn(4);
1905 // RegSaveFrameIndex is X86-64 only.
1906 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1907 if (CallConv == CallingConv::X86_FastCall ||
1908 CallConv == CallingConv::X86_ThisCall)
1909 // fastcc functions can't have varargs.
1910 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1917 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1918 SDValue StackPtr, SDValue Arg,
1919 DebugLoc dl, SelectionDAG &DAG,
1920 const CCValAssign &VA,
1921 ISD::ArgFlagsTy Flags) const {
1922 unsigned LocMemOffset = VA.getLocMemOffset();
1923 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1924 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1925 if (Flags.isByVal())
1926 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1928 return DAG.getStore(Chain, dl, Arg, PtrOff,
1929 MachinePointerInfo::getStack(LocMemOffset),
1933 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1934 /// optimization is performed and it is required.
1936 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1937 SDValue &OutRetAddr, SDValue Chain,
1938 bool IsTailCall, bool Is64Bit,
1939 int FPDiff, DebugLoc dl) const {
1940 // Adjust the Return address stack slot.
1941 EVT VT = getPointerTy();
1942 OutRetAddr = getReturnAddressFrameIndex(DAG);
1944 // Load the "old" Return address.
1945 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1947 return SDValue(OutRetAddr.getNode(), 1);
1950 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1951 /// optimization is performed and it is required (FPDiff!=0).
1953 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1954 SDValue Chain, SDValue RetAddrFrIdx,
1955 bool Is64Bit, int FPDiff, DebugLoc dl) {
1956 // Store the return address to the appropriate stack slot.
1957 if (!FPDiff) return Chain;
1958 // Calculate the new stack slot for the return address.
1959 int SlotSize = Is64Bit ? 8 : 4;
1960 int NewReturnAddrFI =
1961 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1962 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1963 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1964 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1965 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1971 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1972 CallingConv::ID CallConv, bool isVarArg,
1974 const SmallVectorImpl<ISD::OutputArg> &Outs,
1975 const SmallVectorImpl<SDValue> &OutVals,
1976 const SmallVectorImpl<ISD::InputArg> &Ins,
1977 DebugLoc dl, SelectionDAG &DAG,
1978 SmallVectorImpl<SDValue> &InVals) const {
1979 MachineFunction &MF = DAG.getMachineFunction();
1980 bool Is64Bit = Subtarget->is64Bit();
1981 bool IsWin64 = Subtarget->isTargetWin64();
1982 bool IsStructRet = CallIsStructReturn(Outs);
1983 bool IsSibcall = false;
1986 // Check if it's really possible to do a tail call.
1987 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1988 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1989 Outs, OutVals, Ins, DAG);
1991 // Sibcalls are automatically detected tailcalls which do not require
1993 if (!GuaranteedTailCallOpt && isTailCall)
2000 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2001 "Var args not supported with calling convention fastcc or ghc");
2003 // Analyze operands of the call, assigning locations to each operand.
2004 SmallVector<CCValAssign, 16> ArgLocs;
2005 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
2006 ArgLocs, *DAG.getContext());
2008 // Allocate shadow area for Win64
2010 CCInfo.AllocateStack(32, 8);
2013 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2015 // Get a count of how many bytes are to be pushed on the stack.
2016 unsigned NumBytes = CCInfo.getNextStackOffset();
2018 // This is a sibcall. The memory operands are available in caller's
2019 // own caller's stack.
2021 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2022 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2025 if (isTailCall && !IsSibcall) {
2026 // Lower arguments at fp - stackoffset + fpdiff.
2027 unsigned NumBytesCallerPushed =
2028 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2029 FPDiff = NumBytesCallerPushed - NumBytes;
2031 // Set the delta of movement of the returnaddr stackslot.
2032 // But only set if delta is greater than previous delta.
2033 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2034 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2038 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2040 SDValue RetAddrFrIdx;
2041 // Load return address for tail calls.
2042 if (isTailCall && FPDiff)
2043 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2044 Is64Bit, FPDiff, dl);
2046 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2047 SmallVector<SDValue, 8> MemOpChains;
2050 // Walk the register/memloc assignments, inserting copies/loads. In the case
2051 // of tail call optimization arguments are handle later.
2052 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2053 CCValAssign &VA = ArgLocs[i];
2054 EVT RegVT = VA.getLocVT();
2055 SDValue Arg = OutVals[i];
2056 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2057 bool isByVal = Flags.isByVal();
2059 // Promote the value if needed.
2060 switch (VA.getLocInfo()) {
2061 default: llvm_unreachable("Unknown loc info!");
2062 case CCValAssign::Full: break;
2063 case CCValAssign::SExt:
2064 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2066 case CCValAssign::ZExt:
2067 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2069 case CCValAssign::AExt:
2070 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2071 // Special case: passing MMX values in XMM registers.
2072 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2073 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2074 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2076 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2078 case CCValAssign::BCvt:
2079 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2081 case CCValAssign::Indirect: {
2082 // Store the argument.
2083 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2084 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2085 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2086 MachinePointerInfo::getFixedStack(FI),
2093 if (VA.isRegLoc()) {
2094 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2095 if (isVarArg && IsWin64) {
2096 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2097 // shadow reg if callee is a varargs function.
2098 unsigned ShadowReg = 0;
2099 switch (VA.getLocReg()) {
2100 case X86::XMM0: ShadowReg = X86::RCX; break;
2101 case X86::XMM1: ShadowReg = X86::RDX; break;
2102 case X86::XMM2: ShadowReg = X86::R8; break;
2103 case X86::XMM3: ShadowReg = X86::R9; break;
2106 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2108 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2109 assert(VA.isMemLoc());
2110 if (StackPtr.getNode() == 0)
2111 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2112 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2113 dl, DAG, VA, Flags));
2117 if (!MemOpChains.empty())
2118 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2119 &MemOpChains[0], MemOpChains.size());
2121 // Build a sequence of copy-to-reg nodes chained together with token chain
2122 // and flag operands which copy the outgoing args into registers.
2124 // Tail call byval lowering might overwrite argument registers so in case of
2125 // tail call optimization the copies to registers are lowered later.
2127 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2128 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2129 RegsToPass[i].second, InFlag);
2130 InFlag = Chain.getValue(1);
2133 if (Subtarget->isPICStyleGOT()) {
2134 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2137 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2138 DAG.getNode(X86ISD::GlobalBaseReg,
2139 DebugLoc(), getPointerTy()),
2141 InFlag = Chain.getValue(1);
2143 // If we are tail calling and generating PIC/GOT style code load the
2144 // address of the callee into ECX. The value in ecx is used as target of
2145 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2146 // for tail calls on PIC/GOT architectures. Normally we would just put the
2147 // address of GOT into ebx and then call target@PLT. But for tail calls
2148 // ebx would be restored (since ebx is callee saved) before jumping to the
2151 // Note: The actual moving to ECX is done further down.
2152 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2153 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2154 !G->getGlobal()->hasProtectedVisibility())
2155 Callee = LowerGlobalAddress(Callee, DAG);
2156 else if (isa<ExternalSymbolSDNode>(Callee))
2157 Callee = LowerExternalSymbol(Callee, DAG);
2161 if (Is64Bit && isVarArg && !IsWin64) {
2162 // From AMD64 ABI document:
2163 // For calls that may call functions that use varargs or stdargs
2164 // (prototype-less calls or calls to functions containing ellipsis (...) in
2165 // the declaration) %al is used as hidden argument to specify the number
2166 // of SSE registers used. The contents of %al do not need to match exactly
2167 // the number of registers, but must be an ubound on the number of SSE
2168 // registers used and is in the range 0 - 8 inclusive.
2170 // Count the number of XMM registers allocated.
2171 static const unsigned XMMArgRegs[] = {
2172 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2173 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2175 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2176 assert((Subtarget->hasXMM() || !NumXMMRegs)
2177 && "SSE registers cannot be used when SSE is disabled");
2179 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2180 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2181 InFlag = Chain.getValue(1);
2185 // For tail calls lower the arguments to the 'real' stack slot.
2187 // Force all the incoming stack arguments to be loaded from the stack
2188 // before any new outgoing arguments are stored to the stack, because the
2189 // outgoing stack slots may alias the incoming argument stack slots, and
2190 // the alias isn't otherwise explicit. This is slightly more conservative
2191 // than necessary, because it means that each store effectively depends
2192 // on every argument instead of just those arguments it would clobber.
2193 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2195 SmallVector<SDValue, 8> MemOpChains2;
2198 // Do not flag preceding copytoreg stuff together with the following stuff.
2200 if (GuaranteedTailCallOpt) {
2201 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2202 CCValAssign &VA = ArgLocs[i];
2205 assert(VA.isMemLoc());
2206 SDValue Arg = OutVals[i];
2207 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2208 // Create frame index.
2209 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2210 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2211 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2212 FIN = DAG.getFrameIndex(FI, getPointerTy());
2214 if (Flags.isByVal()) {
2215 // Copy relative to framepointer.
2216 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2217 if (StackPtr.getNode() == 0)
2218 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2220 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2222 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2226 // Store relative to framepointer.
2227 MemOpChains2.push_back(
2228 DAG.getStore(ArgChain, dl, Arg, FIN,
2229 MachinePointerInfo::getFixedStack(FI),
2235 if (!MemOpChains2.empty())
2236 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2237 &MemOpChains2[0], MemOpChains2.size());
2239 // Copy arguments to their registers.
2240 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2241 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2242 RegsToPass[i].second, InFlag);
2243 InFlag = Chain.getValue(1);
2247 // Store the return address to the appropriate stack slot.
2248 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2252 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2253 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2254 // In the 64-bit large code model, we have to make all calls
2255 // through a register, since the call instruction's 32-bit
2256 // pc-relative offset may not be large enough to hold the whole
2258 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2259 // If the callee is a GlobalAddress node (quite common, every direct call
2260 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2263 // We should use extra load for direct calls to dllimported functions in
2265 const GlobalValue *GV = G->getGlobal();
2266 if (!GV->hasDLLImportLinkage()) {
2267 unsigned char OpFlags = 0;
2269 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2270 // external symbols most go through the PLT in PIC mode. If the symbol
2271 // has hidden or protected visibility, or if it is static or local, then
2272 // we don't need to use the PLT - we can directly call it.
2273 if (Subtarget->isTargetELF() &&
2274 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2275 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2276 OpFlags = X86II::MO_PLT;
2277 } else if (Subtarget->isPICStyleStubAny() &&
2278 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2279 (!Subtarget->getTargetTriple().isMacOSX() ||
2280 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2281 // PC-relative references to external symbols should go through $stub,
2282 // unless we're building with the leopard linker or later, which
2283 // automatically synthesizes these stubs.
2284 OpFlags = X86II::MO_DARWIN_STUB;
2287 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2288 G->getOffset(), OpFlags);
2290 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2291 unsigned char OpFlags = 0;
2293 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2294 // external symbols should go through the PLT.
2295 if (Subtarget->isTargetELF() &&
2296 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2297 OpFlags = X86II::MO_PLT;
2298 } else if (Subtarget->isPICStyleStubAny() &&
2299 (!Subtarget->getTargetTriple().isMacOSX() ||
2300 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2301 // PC-relative references to external symbols should go through $stub,
2302 // unless we're building with the leopard linker or later, which
2303 // automatically synthesizes these stubs.
2304 OpFlags = X86II::MO_DARWIN_STUB;
2307 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2311 // Returns a chain & a flag for retval copy to use.
2312 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2313 SmallVector<SDValue, 8> Ops;
2315 if (!IsSibcall && isTailCall) {
2316 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2317 DAG.getIntPtrConstant(0, true), InFlag);
2318 InFlag = Chain.getValue(1);
2321 Ops.push_back(Chain);
2322 Ops.push_back(Callee);
2325 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2327 // Add argument registers to the end of the list so that they are known live
2329 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2330 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2331 RegsToPass[i].second.getValueType()));
2333 // Add an implicit use GOT pointer in EBX.
2334 if (!isTailCall && Subtarget->isPICStyleGOT())
2335 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2337 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2338 if (Is64Bit && isVarArg && !IsWin64)
2339 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2341 if (InFlag.getNode())
2342 Ops.push_back(InFlag);
2346 //// If this is the first return lowered for this function, add the regs
2347 //// to the liveout set for the function.
2348 // This isn't right, although it's probably harmless on x86; liveouts
2349 // should be computed from returns not tail calls. Consider a void
2350 // function making a tail call to a function returning int.
2351 return DAG.getNode(X86ISD::TC_RETURN, dl,
2352 NodeTys, &Ops[0], Ops.size());
2355 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2356 InFlag = Chain.getValue(1);
2358 // Create the CALLSEQ_END node.
2359 unsigned NumBytesForCalleeToPush;
2360 if (Subtarget->IsCalleePop(isVarArg, CallConv))
2361 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2362 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2363 // If this is a call to a struct-return function, the callee
2364 // pops the hidden struct pointer, so we have to push it back.
2365 // This is common for Darwin/X86, Linux & Mingw32 targets.
2366 NumBytesForCalleeToPush = 4;
2368 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2370 // Returns a flag for retval copy to use.
2372 Chain = DAG.getCALLSEQ_END(Chain,
2373 DAG.getIntPtrConstant(NumBytes, true),
2374 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2377 InFlag = Chain.getValue(1);
2380 // Handle result values, copying them out of physregs into vregs that we
2382 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2383 Ins, dl, DAG, InVals);
2387 //===----------------------------------------------------------------------===//
2388 // Fast Calling Convention (tail call) implementation
2389 //===----------------------------------------------------------------------===//
2391 // Like std call, callee cleans arguments, convention except that ECX is
2392 // reserved for storing the tail called function address. Only 2 registers are
2393 // free for argument passing (inreg). Tail call optimization is performed
2395 // * tailcallopt is enabled
2396 // * caller/callee are fastcc
2397 // On X86_64 architecture with GOT-style position independent code only local
2398 // (within module) calls are supported at the moment.
2399 // To keep the stack aligned according to platform abi the function
2400 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2401 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2402 // If a tail called function callee has more arguments than the caller the
2403 // caller needs to make sure that there is room to move the RETADDR to. This is
2404 // achieved by reserving an area the size of the argument delta right after the
2405 // original REtADDR, but before the saved framepointer or the spilled registers
2406 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2418 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2419 /// for a 16 byte align requirement.
2421 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2422 SelectionDAG& DAG) const {
2423 MachineFunction &MF = DAG.getMachineFunction();
2424 const TargetMachine &TM = MF.getTarget();
2425 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2426 unsigned StackAlignment = TFI.getStackAlignment();
2427 uint64_t AlignMask = StackAlignment - 1;
2428 int64_t Offset = StackSize;
2429 uint64_t SlotSize = TD->getPointerSize();
2430 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2431 // Number smaller than 12 so just add the difference.
2432 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2434 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2435 Offset = ((~AlignMask) & Offset) + StackAlignment +
2436 (StackAlignment-SlotSize);
2441 /// MatchingStackOffset - Return true if the given stack call argument is
2442 /// already available in the same position (relatively) of the caller's
2443 /// incoming argument stack.
2445 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2446 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2447 const X86InstrInfo *TII) {
2448 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2450 if (Arg.getOpcode() == ISD::CopyFromReg) {
2451 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2452 if (!TargetRegisterInfo::isVirtualRegister(VR))
2454 MachineInstr *Def = MRI->getVRegDef(VR);
2457 if (!Flags.isByVal()) {
2458 if (!TII->isLoadFromStackSlot(Def, FI))
2461 unsigned Opcode = Def->getOpcode();
2462 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2463 Def->getOperand(1).isFI()) {
2464 FI = Def->getOperand(1).getIndex();
2465 Bytes = Flags.getByValSize();
2469 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2470 if (Flags.isByVal())
2471 // ByVal argument is passed in as a pointer but it's now being
2472 // dereferenced. e.g.
2473 // define @foo(%struct.X* %A) {
2474 // tail call @bar(%struct.X* byval %A)
2477 SDValue Ptr = Ld->getBasePtr();
2478 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2481 FI = FINode->getIndex();
2485 assert(FI != INT_MAX);
2486 if (!MFI->isFixedObjectIndex(FI))
2488 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2491 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2492 /// for tail call optimization. Targets which want to do tail call
2493 /// optimization should implement this function.
2495 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2496 CallingConv::ID CalleeCC,
2498 bool isCalleeStructRet,
2499 bool isCallerStructRet,
2500 const SmallVectorImpl<ISD::OutputArg> &Outs,
2501 const SmallVectorImpl<SDValue> &OutVals,
2502 const SmallVectorImpl<ISD::InputArg> &Ins,
2503 SelectionDAG& DAG) const {
2504 if (!IsTailCallConvention(CalleeCC) &&
2505 CalleeCC != CallingConv::C)
2508 // If -tailcallopt is specified, make fastcc functions tail-callable.
2509 const MachineFunction &MF = DAG.getMachineFunction();
2510 const Function *CallerF = DAG.getMachineFunction().getFunction();
2511 CallingConv::ID CallerCC = CallerF->getCallingConv();
2512 bool CCMatch = CallerCC == CalleeCC;
2514 if (GuaranteedTailCallOpt) {
2515 if (IsTailCallConvention(CalleeCC) && CCMatch)
2520 // Look for obvious safe cases to perform tail call optimization that do not
2521 // require ABI changes. This is what gcc calls sibcall.
2523 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2524 // emit a special epilogue.
2525 if (RegInfo->needsStackRealignment(MF))
2528 // Do not sibcall optimize vararg calls unless the call site is not passing
2530 if (isVarArg && !Outs.empty())
2533 // Also avoid sibcall optimization if either caller or callee uses struct
2534 // return semantics.
2535 if (isCalleeStructRet || isCallerStructRet)
2538 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2539 // Therefore if it's not used by the call it is not safe to optimize this into
2541 bool Unused = false;
2542 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2549 SmallVector<CCValAssign, 16> RVLocs;
2550 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2551 RVLocs, *DAG.getContext());
2552 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2553 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2554 CCValAssign &VA = RVLocs[i];
2555 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2560 // If the calling conventions do not match, then we'd better make sure the
2561 // results are returned in the same way as what the caller expects.
2563 SmallVector<CCValAssign, 16> RVLocs1;
2564 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2565 RVLocs1, *DAG.getContext());
2566 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2568 SmallVector<CCValAssign, 16> RVLocs2;
2569 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2570 RVLocs2, *DAG.getContext());
2571 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2573 if (RVLocs1.size() != RVLocs2.size())
2575 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2576 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2578 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2580 if (RVLocs1[i].isRegLoc()) {
2581 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2584 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2590 // If the callee takes no arguments then go on to check the results of the
2592 if (!Outs.empty()) {
2593 // Check if stack adjustment is needed. For now, do not do this if any
2594 // argument is passed on the stack.
2595 SmallVector<CCValAssign, 16> ArgLocs;
2596 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2597 ArgLocs, *DAG.getContext());
2599 // Allocate shadow area for Win64
2600 if (Subtarget->isTargetWin64()) {
2601 CCInfo.AllocateStack(32, 8);
2604 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2605 if (CCInfo.getNextStackOffset()) {
2606 MachineFunction &MF = DAG.getMachineFunction();
2607 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2610 // Check if the arguments are already laid out in the right way as
2611 // the caller's fixed stack objects.
2612 MachineFrameInfo *MFI = MF.getFrameInfo();
2613 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2614 const X86InstrInfo *TII =
2615 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2616 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2617 CCValAssign &VA = ArgLocs[i];
2618 SDValue Arg = OutVals[i];
2619 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2620 if (VA.getLocInfo() == CCValAssign::Indirect)
2622 if (!VA.isRegLoc()) {
2623 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2630 // If the tailcall address may be in a register, then make sure it's
2631 // possible to register allocate for it. In 32-bit, the call address can
2632 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2633 // callee-saved registers are restored. These happen to be the same
2634 // registers used to pass 'inreg' arguments so watch out for those.
2635 if (!Subtarget->is64Bit() &&
2636 !isa<GlobalAddressSDNode>(Callee) &&
2637 !isa<ExternalSymbolSDNode>(Callee)) {
2638 unsigned NumInRegs = 0;
2639 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2640 CCValAssign &VA = ArgLocs[i];
2643 unsigned Reg = VA.getLocReg();
2646 case X86::EAX: case X86::EDX: case X86::ECX:
2647 if (++NumInRegs == 3)
2655 // An stdcall caller is expected to clean up its arguments; the callee
2656 // isn't going to do that.
2657 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2664 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2665 return X86::createFastISel(funcInfo);
2669 //===----------------------------------------------------------------------===//
2670 // Other Lowering Hooks
2671 //===----------------------------------------------------------------------===//
2673 static bool MayFoldLoad(SDValue Op) {
2674 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2677 static bool MayFoldIntoStore(SDValue Op) {
2678 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2681 static bool isTargetShuffle(unsigned Opcode) {
2683 default: return false;
2684 case X86ISD::PSHUFD:
2685 case X86ISD::PSHUFHW:
2686 case X86ISD::PSHUFLW:
2687 case X86ISD::SHUFPD:
2688 case X86ISD::PALIGN:
2689 case X86ISD::SHUFPS:
2690 case X86ISD::MOVLHPS:
2691 case X86ISD::MOVLHPD:
2692 case X86ISD::MOVHLPS:
2693 case X86ISD::MOVLPS:
2694 case X86ISD::MOVLPD:
2695 case X86ISD::MOVSHDUP:
2696 case X86ISD::MOVSLDUP:
2697 case X86ISD::MOVDDUP:
2700 case X86ISD::UNPCKLPS:
2701 case X86ISD::UNPCKLPD:
2702 case X86ISD::VUNPCKLPS:
2703 case X86ISD::VUNPCKLPD:
2704 case X86ISD::VUNPCKLPSY:
2705 case X86ISD::VUNPCKLPDY:
2706 case X86ISD::PUNPCKLWD:
2707 case X86ISD::PUNPCKLBW:
2708 case X86ISD::PUNPCKLDQ:
2709 case X86ISD::PUNPCKLQDQ:
2710 case X86ISD::UNPCKHPS:
2711 case X86ISD::UNPCKHPD:
2712 case X86ISD::PUNPCKHWD:
2713 case X86ISD::PUNPCKHBW:
2714 case X86ISD::PUNPCKHDQ:
2715 case X86ISD::PUNPCKHQDQ:
2721 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2722 SDValue V1, SelectionDAG &DAG) {
2724 default: llvm_unreachable("Unknown x86 shuffle node");
2725 case X86ISD::MOVSHDUP:
2726 case X86ISD::MOVSLDUP:
2727 case X86ISD::MOVDDUP:
2728 return DAG.getNode(Opc, dl, VT, V1);
2734 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2735 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2737 default: llvm_unreachable("Unknown x86 shuffle node");
2738 case X86ISD::PSHUFD:
2739 case X86ISD::PSHUFHW:
2740 case X86ISD::PSHUFLW:
2741 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2747 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2748 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2750 default: llvm_unreachable("Unknown x86 shuffle node");
2751 case X86ISD::PALIGN:
2752 case X86ISD::SHUFPD:
2753 case X86ISD::SHUFPS:
2754 return DAG.getNode(Opc, dl, VT, V1, V2,
2755 DAG.getConstant(TargetMask, MVT::i8));
2760 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2761 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2763 default: llvm_unreachable("Unknown x86 shuffle node");
2764 case X86ISD::MOVLHPS:
2765 case X86ISD::MOVLHPD:
2766 case X86ISD::MOVHLPS:
2767 case X86ISD::MOVLPS:
2768 case X86ISD::MOVLPD:
2771 case X86ISD::UNPCKLPS:
2772 case X86ISD::UNPCKLPD:
2773 case X86ISD::VUNPCKLPS:
2774 case X86ISD::VUNPCKLPD:
2775 case X86ISD::VUNPCKLPSY:
2776 case X86ISD::VUNPCKLPDY:
2777 case X86ISD::PUNPCKLWD:
2778 case X86ISD::PUNPCKLBW:
2779 case X86ISD::PUNPCKLDQ:
2780 case X86ISD::PUNPCKLQDQ:
2781 case X86ISD::UNPCKHPS:
2782 case X86ISD::UNPCKHPD:
2783 case X86ISD::PUNPCKHWD:
2784 case X86ISD::PUNPCKHBW:
2785 case X86ISD::PUNPCKHDQ:
2786 case X86ISD::PUNPCKHQDQ:
2787 return DAG.getNode(Opc, dl, VT, V1, V2);
2792 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2793 MachineFunction &MF = DAG.getMachineFunction();
2794 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2795 int ReturnAddrIndex = FuncInfo->getRAIndex();
2797 if (ReturnAddrIndex == 0) {
2798 // Set up a frame object for the return address.
2799 uint64_t SlotSize = TD->getPointerSize();
2800 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2802 FuncInfo->setRAIndex(ReturnAddrIndex);
2805 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2809 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2810 bool hasSymbolicDisplacement) {
2811 // Offset should fit into 32 bit immediate field.
2812 if (!isInt<32>(Offset))
2815 // If we don't have a symbolic displacement - we don't have any extra
2817 if (!hasSymbolicDisplacement)
2820 // FIXME: Some tweaks might be needed for medium code model.
2821 if (M != CodeModel::Small && M != CodeModel::Kernel)
2824 // For small code model we assume that latest object is 16MB before end of 31
2825 // bits boundary. We may also accept pretty large negative constants knowing
2826 // that all objects are in the positive half of address space.
2827 if (M == CodeModel::Small && Offset < 16*1024*1024)
2830 // For kernel code model we know that all object resist in the negative half
2831 // of 32bits address space. We may not accept negative offsets, since they may
2832 // be just off and we may accept pretty large positive ones.
2833 if (M == CodeModel::Kernel && Offset > 0)
2839 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2840 /// specific condition code, returning the condition code and the LHS/RHS of the
2841 /// comparison to make.
2842 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2843 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2845 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2846 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2847 // X > -1 -> X == 0, jump !sign.
2848 RHS = DAG.getConstant(0, RHS.getValueType());
2849 return X86::COND_NS;
2850 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2851 // X < 0 -> X == 0, jump on sign.
2853 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2855 RHS = DAG.getConstant(0, RHS.getValueType());
2856 return X86::COND_LE;
2860 switch (SetCCOpcode) {
2861 default: llvm_unreachable("Invalid integer condition!");
2862 case ISD::SETEQ: return X86::COND_E;
2863 case ISD::SETGT: return X86::COND_G;
2864 case ISD::SETGE: return X86::COND_GE;
2865 case ISD::SETLT: return X86::COND_L;
2866 case ISD::SETLE: return X86::COND_LE;
2867 case ISD::SETNE: return X86::COND_NE;
2868 case ISD::SETULT: return X86::COND_B;
2869 case ISD::SETUGT: return X86::COND_A;
2870 case ISD::SETULE: return X86::COND_BE;
2871 case ISD::SETUGE: return X86::COND_AE;
2875 // First determine if it is required or is profitable to flip the operands.
2877 // If LHS is a foldable load, but RHS is not, flip the condition.
2878 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2879 !ISD::isNON_EXTLoad(RHS.getNode())) {
2880 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2881 std::swap(LHS, RHS);
2884 switch (SetCCOpcode) {
2890 std::swap(LHS, RHS);
2894 // On a floating point condition, the flags are set as follows:
2896 // 0 | 0 | 0 | X > Y
2897 // 0 | 0 | 1 | X < Y
2898 // 1 | 0 | 0 | X == Y
2899 // 1 | 1 | 1 | unordered
2900 switch (SetCCOpcode) {
2901 default: llvm_unreachable("Condcode should be pre-legalized away");
2903 case ISD::SETEQ: return X86::COND_E;
2904 case ISD::SETOLT: // flipped
2906 case ISD::SETGT: return X86::COND_A;
2907 case ISD::SETOLE: // flipped
2909 case ISD::SETGE: return X86::COND_AE;
2910 case ISD::SETUGT: // flipped
2912 case ISD::SETLT: return X86::COND_B;
2913 case ISD::SETUGE: // flipped
2915 case ISD::SETLE: return X86::COND_BE;
2917 case ISD::SETNE: return X86::COND_NE;
2918 case ISD::SETUO: return X86::COND_P;
2919 case ISD::SETO: return X86::COND_NP;
2921 case ISD::SETUNE: return X86::COND_INVALID;
2925 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2926 /// code. Current x86 isa includes the following FP cmov instructions:
2927 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2928 static bool hasFPCMov(unsigned X86CC) {
2944 /// isFPImmLegal - Returns true if the target can instruction select the
2945 /// specified FP immediate natively. If false, the legalizer will
2946 /// materialize the FP immediate as a load from a constant pool.
2947 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2948 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2949 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2955 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2956 /// the specified range (L, H].
2957 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2958 return (Val < 0) || (Val >= Low && Val < Hi);
2961 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2962 /// specified value.
2963 static bool isUndefOrEqual(int Val, int CmpVal) {
2964 if (Val < 0 || Val == CmpVal)
2969 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2970 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2971 /// the second operand.
2972 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2973 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2974 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2975 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2976 return (Mask[0] < 2 && Mask[1] < 2);
2980 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2981 SmallVector<int, 8> M;
2983 return ::isPSHUFDMask(M, N->getValueType(0));
2986 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2987 /// is suitable for input to PSHUFHW.
2988 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2989 if (VT != MVT::v8i16)
2992 // Lower quadword copied in order or undef.
2993 for (int i = 0; i != 4; ++i)
2994 if (Mask[i] >= 0 && Mask[i] != i)
2997 // Upper quadword shuffled.
2998 for (int i = 4; i != 8; ++i)
2999 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3005 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3006 SmallVector<int, 8> M;
3008 return ::isPSHUFHWMask(M, N->getValueType(0));
3011 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3012 /// is suitable for input to PSHUFLW.
3013 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3014 if (VT != MVT::v8i16)
3017 // Upper quadword copied in order.
3018 for (int i = 4; i != 8; ++i)
3019 if (Mask[i] >= 0 && Mask[i] != i)
3022 // Lower quadword shuffled.
3023 for (int i = 0; i != 4; ++i)
3030 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3031 SmallVector<int, 8> M;
3033 return ::isPSHUFLWMask(M, N->getValueType(0));
3036 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3037 /// is suitable for input to PALIGNR.
3038 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3040 int i, e = VT.getVectorNumElements();
3042 // Do not handle v2i64 / v2f64 shuffles with palignr.
3043 if (e < 4 || !hasSSSE3)
3046 for (i = 0; i != e; ++i)
3050 // All undef, not a palignr.
3054 // Determine if it's ok to perform a palignr with only the LHS, since we
3055 // don't have access to the actual shuffle elements to see if RHS is undef.
3056 bool Unary = Mask[i] < (int)e;
3057 bool NeedsUnary = false;
3059 int s = Mask[i] - i;
3061 // Check the rest of the elements to see if they are consecutive.
3062 for (++i; i != e; ++i) {
3067 Unary = Unary && (m < (int)e);
3068 NeedsUnary = NeedsUnary || (m < s);
3070 if (NeedsUnary && !Unary)
3072 if (Unary && m != ((s+i) & (e-1)))
3074 if (!Unary && m != (s+i))
3080 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3081 SmallVector<int, 8> M;
3083 return ::isPALIGNRMask(M, N->getValueType(0), true);
3086 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3087 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3088 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3089 int NumElems = VT.getVectorNumElements();
3090 if (NumElems != 2 && NumElems != 4)
3093 int Half = NumElems / 2;
3094 for (int i = 0; i < Half; ++i)
3095 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3097 for (int i = Half; i < NumElems; ++i)
3098 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3104 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3105 SmallVector<int, 8> M;
3107 return ::isSHUFPMask(M, N->getValueType(0));
3110 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3111 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3112 /// half elements to come from vector 1 (which would equal the dest.) and
3113 /// the upper half to come from vector 2.
3114 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3115 int NumElems = VT.getVectorNumElements();
3117 if (NumElems != 2 && NumElems != 4)
3120 int Half = NumElems / 2;
3121 for (int i = 0; i < Half; ++i)
3122 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3124 for (int i = Half; i < NumElems; ++i)
3125 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3130 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3131 SmallVector<int, 8> M;
3133 return isCommutedSHUFPMask(M, N->getValueType(0));
3136 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3137 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3138 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3139 if (N->getValueType(0).getVectorNumElements() != 4)
3142 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3143 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3144 isUndefOrEqual(N->getMaskElt(1), 7) &&
3145 isUndefOrEqual(N->getMaskElt(2), 2) &&
3146 isUndefOrEqual(N->getMaskElt(3), 3);
3149 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3150 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3152 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3153 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3158 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3159 isUndefOrEqual(N->getMaskElt(1), 3) &&
3160 isUndefOrEqual(N->getMaskElt(2), 2) &&
3161 isUndefOrEqual(N->getMaskElt(3), 3);
3164 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3165 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3166 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3167 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3169 if (NumElems != 2 && NumElems != 4)
3172 for (unsigned i = 0; i < NumElems/2; ++i)
3173 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3176 for (unsigned i = NumElems/2; i < NumElems; ++i)
3177 if (!isUndefOrEqual(N->getMaskElt(i), i))
3183 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3184 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3185 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3186 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3188 if ((NumElems != 2 && NumElems != 4)
3189 || N->getValueType(0).getSizeInBits() > 128)
3192 for (unsigned i = 0; i < NumElems/2; ++i)
3193 if (!isUndefOrEqual(N->getMaskElt(i), i))
3196 for (unsigned i = 0; i < NumElems/2; ++i)
3197 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3203 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3204 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3205 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3206 bool V2IsSplat = false) {
3207 int NumElts = VT.getVectorNumElements();
3208 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3211 // Handle vector lengths > 128 bits. Define a "section" as a set of
3212 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3214 unsigned NumSections = VT.getSizeInBits() / 128;
3215 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3216 unsigned NumSectionElts = NumElts / NumSections;
3219 unsigned End = NumSectionElts;
3220 for (unsigned s = 0; s < NumSections; ++s) {
3221 for (unsigned i = Start, j = s * NumSectionElts;
3225 int BitI1 = Mask[i+1];
3226 if (!isUndefOrEqual(BitI, j))
3229 if (!isUndefOrEqual(BitI1, NumElts))
3232 if (!isUndefOrEqual(BitI1, j + NumElts))
3236 // Process the next 128 bits.
3237 Start += NumSectionElts;
3238 End += NumSectionElts;
3244 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3245 SmallVector<int, 8> M;
3247 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3250 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3251 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3252 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3253 bool V2IsSplat = false) {
3254 int NumElts = VT.getVectorNumElements();
3255 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3258 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3260 int BitI1 = Mask[i+1];
3261 if (!isUndefOrEqual(BitI, j + NumElts/2))
3264 if (isUndefOrEqual(BitI1, NumElts))
3267 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3274 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3275 SmallVector<int, 8> M;
3277 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3280 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3281 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3283 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3284 int NumElems = VT.getVectorNumElements();
3285 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3288 // Handle vector lengths > 128 bits. Define a "section" as a set of
3289 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3291 unsigned NumSections = VT.getSizeInBits() / 128;
3292 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3293 unsigned NumSectionElts = NumElems / NumSections;
3295 for (unsigned s = 0; s < NumSections; ++s) {
3296 for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3297 i != NumSectionElts * (s + 1);
3300 int BitI1 = Mask[i+1];
3302 if (!isUndefOrEqual(BitI, j))
3304 if (!isUndefOrEqual(BitI1, j))
3312 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3313 SmallVector<int, 8> M;
3315 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3318 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3319 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3321 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3322 int NumElems = VT.getVectorNumElements();
3323 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3326 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3328 int BitI1 = Mask[i+1];
3329 if (!isUndefOrEqual(BitI, j))
3331 if (!isUndefOrEqual(BitI1, j))
3337 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3338 SmallVector<int, 8> M;
3340 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3343 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3344 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3345 /// MOVSD, and MOVD, i.e. setting the lowest element.
3346 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3347 if (VT.getVectorElementType().getSizeInBits() < 32)
3350 int NumElts = VT.getVectorNumElements();
3352 if (!isUndefOrEqual(Mask[0], NumElts))
3355 for (int i = 1; i < NumElts; ++i)
3356 if (!isUndefOrEqual(Mask[i], i))
3362 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3363 SmallVector<int, 8> M;
3365 return ::isMOVLMask(M, N->getValueType(0));
3368 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3369 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3370 /// element of vector 2 and the other elements to come from vector 1 in order.
3371 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3372 bool V2IsSplat = false, bool V2IsUndef = false) {
3373 int NumOps = VT.getVectorNumElements();
3374 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3377 if (!isUndefOrEqual(Mask[0], 0))
3380 for (int i = 1; i < NumOps; ++i)
3381 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3382 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3383 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3389 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3390 bool V2IsUndef = false) {
3391 SmallVector<int, 8> M;
3393 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3396 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3397 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3398 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3399 if (N->getValueType(0).getVectorNumElements() != 4)
3402 // Expect 1, 1, 3, 3
3403 for (unsigned i = 0; i < 2; ++i) {
3404 int Elt = N->getMaskElt(i);
3405 if (Elt >= 0 && Elt != 1)
3410 for (unsigned i = 2; i < 4; ++i) {
3411 int Elt = N->getMaskElt(i);
3412 if (Elt >= 0 && Elt != 3)
3417 // Don't use movshdup if it can be done with a shufps.
3418 // FIXME: verify that matching u, u, 3, 3 is what we want.
3422 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3423 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3424 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3425 if (N->getValueType(0).getVectorNumElements() != 4)
3428 // Expect 0, 0, 2, 2
3429 for (unsigned i = 0; i < 2; ++i)
3430 if (N->getMaskElt(i) > 0)
3434 for (unsigned i = 2; i < 4; ++i) {
3435 int Elt = N->getMaskElt(i);
3436 if (Elt >= 0 && Elt != 2)
3441 // Don't use movsldup if it can be done with a shufps.
3445 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3446 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3447 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3448 int e = N->getValueType(0).getVectorNumElements() / 2;
3450 for (int i = 0; i < e; ++i)
3451 if (!isUndefOrEqual(N->getMaskElt(i), i))
3453 for (int i = 0; i < e; ++i)
3454 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3459 /// isVEXTRACTF128Index - Return true if the specified
3460 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3461 /// suitable for input to VEXTRACTF128.
3462 bool X86::isVEXTRACTF128Index(SDNode *N) {
3463 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3466 // The index should be aligned on a 128-bit boundary.
3468 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3470 unsigned VL = N->getValueType(0).getVectorNumElements();
3471 unsigned VBits = N->getValueType(0).getSizeInBits();
3472 unsigned ElSize = VBits / VL;
3473 bool Result = (Index * ElSize) % 128 == 0;
3478 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3479 /// operand specifies a subvector insert that is suitable for input to
3481 bool X86::isVINSERTF128Index(SDNode *N) {
3482 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3485 // The index should be aligned on a 128-bit boundary.
3487 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3489 unsigned VL = N->getValueType(0).getVectorNumElements();
3490 unsigned VBits = N->getValueType(0).getSizeInBits();
3491 unsigned ElSize = VBits / VL;
3492 bool Result = (Index * ElSize) % 128 == 0;
3497 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3498 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3499 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3500 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3501 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3503 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3505 for (int i = 0; i < NumOperands; ++i) {
3506 int Val = SVOp->getMaskElt(NumOperands-i-1);
3507 if (Val < 0) Val = 0;
3508 if (Val >= NumOperands) Val -= NumOperands;
3510 if (i != NumOperands - 1)
3516 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3517 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3518 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3519 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3521 // 8 nodes, but we only care about the last 4.
3522 for (unsigned i = 7; i >= 4; --i) {
3523 int Val = SVOp->getMaskElt(i);
3532 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3533 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3534 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3535 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3537 // 8 nodes, but we only care about the first 4.
3538 for (int i = 3; i >= 0; --i) {
3539 int Val = SVOp->getMaskElt(i);
3548 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3549 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3550 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3551 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3552 EVT VVT = N->getValueType(0);
3553 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3557 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3558 Val = SVOp->getMaskElt(i);
3562 return (Val - i) * EltSize;
3565 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3566 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3568 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3569 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3570 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3573 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3575 EVT VecVT = N->getOperand(0).getValueType();
3576 EVT ElVT = VecVT.getVectorElementType();
3578 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3580 return Index / NumElemsPerChunk;
3583 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3584 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3586 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3587 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3588 llvm_unreachable("Illegal insert subvector for VINSERTF128");
3591 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3593 EVT VecVT = N->getValueType(0);
3594 EVT ElVT = VecVT.getVectorElementType();
3596 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3598 return Index / NumElemsPerChunk;
3601 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3603 bool X86::isZeroNode(SDValue Elt) {
3604 return ((isa<ConstantSDNode>(Elt) &&
3605 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3606 (isa<ConstantFPSDNode>(Elt) &&
3607 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3610 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3611 /// their permute mask.
3612 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3613 SelectionDAG &DAG) {
3614 EVT VT = SVOp->getValueType(0);
3615 unsigned NumElems = VT.getVectorNumElements();
3616 SmallVector<int, 8> MaskVec;
3618 for (unsigned i = 0; i != NumElems; ++i) {
3619 int idx = SVOp->getMaskElt(i);
3621 MaskVec.push_back(idx);
3622 else if (idx < (int)NumElems)
3623 MaskVec.push_back(idx + NumElems);
3625 MaskVec.push_back(idx - NumElems);
3627 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3628 SVOp->getOperand(0), &MaskVec[0]);
3631 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3632 /// the two vector operands have swapped position.
3633 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3634 unsigned NumElems = VT.getVectorNumElements();
3635 for (unsigned i = 0; i != NumElems; ++i) {
3639 else if (idx < (int)NumElems)
3640 Mask[i] = idx + NumElems;
3642 Mask[i] = idx - NumElems;
3646 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3647 /// match movhlps. The lower half elements should come from upper half of
3648 /// V1 (and in order), and the upper half elements should come from the upper
3649 /// half of V2 (and in order).
3650 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3651 if (Op->getValueType(0).getVectorNumElements() != 4)
3653 for (unsigned i = 0, e = 2; i != e; ++i)
3654 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3656 for (unsigned i = 2; i != 4; ++i)
3657 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3662 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3663 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3665 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3666 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3668 N = N->getOperand(0).getNode();
3669 if (!ISD::isNON_EXTLoad(N))
3672 *LD = cast<LoadSDNode>(N);
3676 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3677 /// match movlp{s|d}. The lower half elements should come from lower half of
3678 /// V1 (and in order), and the upper half elements should come from the upper
3679 /// half of V2 (and in order). And since V1 will become the source of the
3680 /// MOVLP, it must be either a vector load or a scalar load to vector.
3681 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3682 ShuffleVectorSDNode *Op) {
3683 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3685 // Is V2 is a vector load, don't do this transformation. We will try to use
3686 // load folding shufps op.
3687 if (ISD::isNON_EXTLoad(V2))
3690 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3692 if (NumElems != 2 && NumElems != 4)
3694 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3695 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3697 for (unsigned i = NumElems/2; i != NumElems; ++i)
3698 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3703 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3705 static bool isSplatVector(SDNode *N) {
3706 if (N->getOpcode() != ISD::BUILD_VECTOR)
3709 SDValue SplatValue = N->getOperand(0);
3710 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3711 if (N->getOperand(i) != SplatValue)
3716 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3717 /// to an zero vector.
3718 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3719 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3720 SDValue V1 = N->getOperand(0);
3721 SDValue V2 = N->getOperand(1);
3722 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3723 for (unsigned i = 0; i != NumElems; ++i) {
3724 int Idx = N->getMaskElt(i);
3725 if (Idx >= (int)NumElems) {
3726 unsigned Opc = V2.getOpcode();
3727 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3729 if (Opc != ISD::BUILD_VECTOR ||
3730 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3732 } else if (Idx >= 0) {
3733 unsigned Opc = V1.getOpcode();
3734 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3736 if (Opc != ISD::BUILD_VECTOR ||
3737 !X86::isZeroNode(V1.getOperand(Idx)))
3744 /// getZeroVector - Returns a vector of specified type with all zero elements.
3746 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3748 assert(VT.isVector() && "Expected a vector type");
3750 // Always build SSE zero vectors as <4 x i32> bitcasted
3751 // to their dest type. This ensures they get CSE'd.
3753 if (VT.getSizeInBits() == 128) { // SSE
3754 if (HasSSE2) { // SSE2
3755 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3756 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3758 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3759 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3761 } else if (VT.getSizeInBits() == 256) { // AVX
3762 // 256-bit logic and arithmetic instructions in AVX are
3763 // all floating-point, no support for integer ops. Default
3764 // to emitting fp zeroed vectors then.
3765 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3766 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3767 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3769 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3772 /// getOnesVector - Returns a vector of specified type with all bits set.
3774 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3775 assert(VT.isVector() && "Expected a vector type");
3777 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3778 // type. This ensures they get CSE'd.
3779 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3781 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3782 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3786 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3787 /// that point to V2 points to its first element.
3788 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3789 EVT VT = SVOp->getValueType(0);
3790 unsigned NumElems = VT.getVectorNumElements();
3792 bool Changed = false;
3793 SmallVector<int, 8> MaskVec;
3794 SVOp->getMask(MaskVec);
3796 for (unsigned i = 0; i != NumElems; ++i) {
3797 if (MaskVec[i] > (int)NumElems) {
3798 MaskVec[i] = NumElems;
3803 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3804 SVOp->getOperand(1), &MaskVec[0]);
3805 return SDValue(SVOp, 0);
3808 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3809 /// operation of specified width.
3810 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3812 unsigned NumElems = VT.getVectorNumElements();
3813 SmallVector<int, 8> Mask;
3814 Mask.push_back(NumElems);
3815 for (unsigned i = 1; i != NumElems; ++i)
3817 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3820 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3821 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3823 unsigned NumElems = VT.getVectorNumElements();
3824 SmallVector<int, 8> Mask;
3825 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3827 Mask.push_back(i + NumElems);
3829 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3832 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3833 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3835 unsigned NumElems = VT.getVectorNumElements();
3836 unsigned Half = NumElems/2;
3837 SmallVector<int, 8> Mask;
3838 for (unsigned i = 0; i != Half; ++i) {
3839 Mask.push_back(i + Half);
3840 Mask.push_back(i + NumElems + Half);
3842 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3845 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3846 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3847 EVT PVT = MVT::v4f32;
3848 EVT VT = SV->getValueType(0);
3849 DebugLoc dl = SV->getDebugLoc();
3850 SDValue V1 = SV->getOperand(0);
3851 int NumElems = VT.getVectorNumElements();
3852 int EltNo = SV->getSplatIndex();
3854 // unpack elements to the correct location
3855 while (NumElems > 4) {
3856 if (EltNo < NumElems/2) {
3857 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3859 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3860 EltNo -= NumElems/2;
3865 // Perform the splat.
3866 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3867 V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3868 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3869 return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3872 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3873 /// vector of zero or undef vector. This produces a shuffle where the low
3874 /// element of V2 is swizzled into the zero/undef vector, landing at element
3875 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3876 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3877 bool isZero, bool HasSSE2,
3878 SelectionDAG &DAG) {
3879 EVT VT = V2.getValueType();
3881 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3882 unsigned NumElems = VT.getVectorNumElements();
3883 SmallVector<int, 16> MaskVec;
3884 for (unsigned i = 0; i != NumElems; ++i)
3885 // If this is the insertion idx, put the low elt of V2 here.
3886 MaskVec.push_back(i == Idx ? NumElems : i);
3887 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3890 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3891 /// element of the result of the vector shuffle.
3892 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3895 return SDValue(); // Limit search depth.
3897 SDValue V = SDValue(N, 0);
3898 EVT VT = V.getValueType();
3899 unsigned Opcode = V.getOpcode();
3901 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3902 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3903 Index = SV->getMaskElt(Index);
3906 return DAG.getUNDEF(VT.getVectorElementType());
3908 int NumElems = VT.getVectorNumElements();
3909 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3910 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3913 // Recurse into target specific vector shuffles to find scalars.
3914 if (isTargetShuffle(Opcode)) {
3915 int NumElems = VT.getVectorNumElements();
3916 SmallVector<unsigned, 16> ShuffleMask;
3920 case X86ISD::SHUFPS:
3921 case X86ISD::SHUFPD:
3922 ImmN = N->getOperand(N->getNumOperands()-1);
3923 DecodeSHUFPSMask(NumElems,
3924 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3927 case X86ISD::PUNPCKHBW:
3928 case X86ISD::PUNPCKHWD:
3929 case X86ISD::PUNPCKHDQ:
3930 case X86ISD::PUNPCKHQDQ:
3931 DecodePUNPCKHMask(NumElems, ShuffleMask);
3933 case X86ISD::UNPCKHPS:
3934 case X86ISD::UNPCKHPD:
3935 DecodeUNPCKHPMask(NumElems, ShuffleMask);
3937 case X86ISD::PUNPCKLBW:
3938 case X86ISD::PUNPCKLWD:
3939 case X86ISD::PUNPCKLDQ:
3940 case X86ISD::PUNPCKLQDQ:
3941 DecodePUNPCKLMask(VT, ShuffleMask);
3943 case X86ISD::UNPCKLPS:
3944 case X86ISD::UNPCKLPD:
3945 case X86ISD::VUNPCKLPS:
3946 case X86ISD::VUNPCKLPD:
3947 case X86ISD::VUNPCKLPSY:
3948 case X86ISD::VUNPCKLPDY:
3949 DecodeUNPCKLPMask(VT, ShuffleMask);
3951 case X86ISD::MOVHLPS:
3952 DecodeMOVHLPSMask(NumElems, ShuffleMask);
3954 case X86ISD::MOVLHPS:
3955 DecodeMOVLHPSMask(NumElems, ShuffleMask);
3957 case X86ISD::PSHUFD:
3958 ImmN = N->getOperand(N->getNumOperands()-1);
3959 DecodePSHUFMask(NumElems,
3960 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3963 case X86ISD::PSHUFHW:
3964 ImmN = N->getOperand(N->getNumOperands()-1);
3965 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3968 case X86ISD::PSHUFLW:
3969 ImmN = N->getOperand(N->getNumOperands()-1);
3970 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3974 case X86ISD::MOVSD: {
3975 // The index 0 always comes from the first element of the second source,
3976 // this is why MOVSS and MOVSD are used in the first place. The other
3977 // elements come from the other positions of the first source vector.
3978 unsigned OpNum = (Index == 0) ? 1 : 0;
3979 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3983 assert("not implemented for target shuffle node");
3987 Index = ShuffleMask[Index];
3989 return DAG.getUNDEF(VT.getVectorElementType());
3991 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3992 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3996 // Actual nodes that may contain scalar elements
3997 if (Opcode == ISD::BITCAST) {
3998 V = V.getOperand(0);
3999 EVT SrcVT = V.getValueType();
4000 unsigned NumElems = VT.getVectorNumElements();
4002 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4006 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4007 return (Index == 0) ? V.getOperand(0)
4008 : DAG.getUNDEF(VT.getVectorElementType());
4010 if (V.getOpcode() == ISD::BUILD_VECTOR)
4011 return V.getOperand(Index);
4016 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4017 /// shuffle operation which come from a consecutively from a zero. The
4018 /// search can start in two different directions, from left or right.
4020 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4021 bool ZerosFromLeft, SelectionDAG &DAG) {
4024 while (i < NumElems) {
4025 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4026 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4027 if (!(Elt.getNode() &&
4028 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4036 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4037 /// MaskE correspond consecutively to elements from one of the vector operands,
4038 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4040 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4041 int OpIdx, int NumElems, unsigned &OpNum) {
4042 bool SeenV1 = false;
4043 bool SeenV2 = false;
4045 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4046 int Idx = SVOp->getMaskElt(i);
4047 // Ignore undef indicies
4056 // Only accept consecutive elements from the same vector
4057 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4061 OpNum = SeenV1 ? 0 : 1;
4065 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4066 /// logical left shift of a vector.
4067 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4068 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4069 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4070 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4071 false /* check zeros from right */, DAG);
4077 // Considering the elements in the mask that are not consecutive zeros,
4078 // check if they consecutively come from only one of the source vectors.
4080 // V1 = {X, A, B, C} 0
4082 // vector_shuffle V1, V2 <1, 2, 3, X>
4084 if (!isShuffleMaskConsecutive(SVOp,
4085 0, // Mask Start Index
4086 NumElems-NumZeros-1, // Mask End Index
4087 NumZeros, // Where to start looking in the src vector
4088 NumElems, // Number of elements in vector
4089 OpSrc)) // Which source operand ?
4094 ShVal = SVOp->getOperand(OpSrc);
4098 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4099 /// logical left shift of a vector.
4100 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4101 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4102 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4103 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4104 true /* check zeros from left */, DAG);
4110 // Considering the elements in the mask that are not consecutive zeros,
4111 // check if they consecutively come from only one of the source vectors.
4113 // 0 { A, B, X, X } = V2
4115 // vector_shuffle V1, V2 <X, X, 4, 5>
4117 if (!isShuffleMaskConsecutive(SVOp,
4118 NumZeros, // Mask Start Index
4119 NumElems-1, // Mask End Index
4120 0, // Where to start looking in the src vector
4121 NumElems, // Number of elements in vector
4122 OpSrc)) // Which source operand ?
4127 ShVal = SVOp->getOperand(OpSrc);
4131 /// isVectorShift - Returns true if the shuffle can be implemented as a
4132 /// logical left or right shift of a vector.
4133 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4134 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4135 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4136 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4142 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4144 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4145 unsigned NumNonZero, unsigned NumZero,
4147 const TargetLowering &TLI) {
4151 DebugLoc dl = Op.getDebugLoc();
4154 for (unsigned i = 0; i < 16; ++i) {
4155 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4156 if (ThisIsNonZero && First) {
4158 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4160 V = DAG.getUNDEF(MVT::v8i16);
4165 SDValue ThisElt(0, 0), LastElt(0, 0);
4166 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4167 if (LastIsNonZero) {
4168 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4169 MVT::i16, Op.getOperand(i-1));
4171 if (ThisIsNonZero) {
4172 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4173 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4174 ThisElt, DAG.getConstant(8, MVT::i8));
4176 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4180 if (ThisElt.getNode())
4181 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4182 DAG.getIntPtrConstant(i/2));
4186 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4189 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4191 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4192 unsigned NumNonZero, unsigned NumZero,
4194 const TargetLowering &TLI) {
4198 DebugLoc dl = Op.getDebugLoc();
4201 for (unsigned i = 0; i < 8; ++i) {
4202 bool isNonZero = (NonZeros & (1 << i)) != 0;
4206 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4208 V = DAG.getUNDEF(MVT::v8i16);
4211 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4212 MVT::v8i16, V, Op.getOperand(i),
4213 DAG.getIntPtrConstant(i));
4220 /// getVShift - Return a vector logical shift node.
4222 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4223 unsigned NumBits, SelectionDAG &DAG,
4224 const TargetLowering &TLI, DebugLoc dl) {
4225 EVT ShVT = MVT::v2i64;
4226 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4227 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4228 return DAG.getNode(ISD::BITCAST, dl, VT,
4229 DAG.getNode(Opc, dl, ShVT, SrcOp,
4230 DAG.getConstant(NumBits,
4231 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4235 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4236 SelectionDAG &DAG) const {
4238 // Check if the scalar load can be widened into a vector load. And if
4239 // the address is "base + cst" see if the cst can be "absorbed" into
4240 // the shuffle mask.
4241 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4242 SDValue Ptr = LD->getBasePtr();
4243 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4245 EVT PVT = LD->getValueType(0);
4246 if (PVT != MVT::i32 && PVT != MVT::f32)
4251 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4252 FI = FINode->getIndex();
4254 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4255 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4256 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4257 Offset = Ptr.getConstantOperandVal(1);
4258 Ptr = Ptr.getOperand(0);
4263 SDValue Chain = LD->getChain();
4264 // Make sure the stack object alignment is at least 16.
4265 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4266 if (DAG.InferPtrAlignment(Ptr) < 16) {
4267 if (MFI->isFixedObjectIndex(FI)) {
4268 // Can't change the alignment. FIXME: It's possible to compute
4269 // the exact stack offset and reference FI + adjust offset instead.
4270 // If someone *really* cares about this. That's the way to implement it.
4273 MFI->setObjectAlignment(FI, 16);
4277 // (Offset % 16) must be multiple of 4. Then address is then
4278 // Ptr + (Offset & ~15).
4281 if ((Offset % 16) & 3)
4283 int64_t StartOffset = Offset & ~15;
4285 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4286 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4288 int EltNo = (Offset - StartOffset) >> 2;
4289 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4290 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4291 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4292 LD->getPointerInfo().getWithOffset(StartOffset),
4294 // Canonicalize it to a v4i32 shuffle.
4295 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4296 return DAG.getNode(ISD::BITCAST, dl, VT,
4297 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4298 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4304 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4305 /// vector of type 'VT', see if the elements can be replaced by a single large
4306 /// load which has the same value as a build_vector whose operands are 'elts'.
4308 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4310 /// FIXME: we'd also like to handle the case where the last elements are zero
4311 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4312 /// There's even a handy isZeroNode for that purpose.
4313 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4314 DebugLoc &DL, SelectionDAG &DAG) {
4315 EVT EltVT = VT.getVectorElementType();
4316 unsigned NumElems = Elts.size();
4318 LoadSDNode *LDBase = NULL;
4319 unsigned LastLoadedElt = -1U;
4321 // For each element in the initializer, see if we've found a load or an undef.
4322 // If we don't find an initial load element, or later load elements are
4323 // non-consecutive, bail out.
4324 for (unsigned i = 0; i < NumElems; ++i) {
4325 SDValue Elt = Elts[i];
4327 if (!Elt.getNode() ||
4328 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4331 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4333 LDBase = cast<LoadSDNode>(Elt.getNode());
4337 if (Elt.getOpcode() == ISD::UNDEF)
4340 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4341 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4346 // If we have found an entire vector of loads and undefs, then return a large
4347 // load of the entire vector width starting at the base pointer. If we found
4348 // consecutive loads for the low half, generate a vzext_load node.
4349 if (LastLoadedElt == NumElems - 1) {
4350 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4351 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4352 LDBase->getPointerInfo(),
4353 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4354 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4355 LDBase->getPointerInfo(),
4356 LDBase->isVolatile(), LDBase->isNonTemporal(),
4357 LDBase->getAlignment());
4358 } else if (NumElems == 4 && LastLoadedElt == 1) {
4359 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4360 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4361 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4363 LDBase->getMemOperand());
4364 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4370 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4371 DebugLoc dl = Op.getDebugLoc();
4373 EVT VT = Op.getValueType();
4374 EVT ExtVT = VT.getVectorElementType();
4376 unsigned NumElems = Op.getNumOperands();
4378 // For AVX-length vectors, build the individual 128-bit pieces and
4379 // use shuffles to put them in place.
4380 if (VT.getSizeInBits() > 256 &&
4381 Subtarget->hasAVX() &&
4382 !ISD::isBuildVectorAllZeros(Op.getNode())) {
4383 SmallVector<SDValue, 8> V;
4385 for (unsigned i = 0; i < NumElems; ++i) {
4386 V[i] = Op.getOperand(i);
4389 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4391 // Build the lower subvector.
4392 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4393 // Build the upper subvector.
4394 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4397 return ConcatVectors(Lower, Upper, DAG);
4400 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4401 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4402 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4403 // is present, so AllOnes is ignored.
4404 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4405 (Op.getValueType().getSizeInBits() != 256 &&
4406 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4407 // Canonicalize this to <4 x i32> (SSE) to
4408 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4409 // eliminated on x86-32 hosts.
4410 if (Op.getValueType() == MVT::v4i32)
4413 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4414 return getOnesVector(Op.getValueType(), DAG, dl);
4415 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4418 unsigned EVTBits = ExtVT.getSizeInBits();
4420 unsigned NumZero = 0;
4421 unsigned NumNonZero = 0;
4422 unsigned NonZeros = 0;
4423 bool IsAllConstants = true;
4424 SmallSet<SDValue, 8> Values;
4425 for (unsigned i = 0; i < NumElems; ++i) {
4426 SDValue Elt = Op.getOperand(i);
4427 if (Elt.getOpcode() == ISD::UNDEF)
4430 if (Elt.getOpcode() != ISD::Constant &&
4431 Elt.getOpcode() != ISD::ConstantFP)
4432 IsAllConstants = false;
4433 if (X86::isZeroNode(Elt))
4436 NonZeros |= (1 << i);
4441 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4442 if (NumNonZero == 0)
4443 return DAG.getUNDEF(VT);
4445 // Special case for single non-zero, non-undef, element.
4446 if (NumNonZero == 1) {
4447 unsigned Idx = CountTrailingZeros_32(NonZeros);
4448 SDValue Item = Op.getOperand(Idx);
4450 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4451 // the value are obviously zero, truncate the value to i32 and do the
4452 // insertion that way. Only do this if the value is non-constant or if the
4453 // value is a constant being inserted into element 0. It is cheaper to do
4454 // a constant pool load than it is to do a movd + shuffle.
4455 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4456 (!IsAllConstants || Idx == 0)) {
4457 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4459 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4460 EVT VecVT = MVT::v4i32;
4461 unsigned VecElts = 4;
4463 // Truncate the value (which may itself be a constant) to i32, and
4464 // convert it to a vector with movd (S2V+shuffle to zero extend).
4465 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4466 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4467 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4468 Subtarget->hasSSE2(), DAG);
4470 // Now we have our 32-bit value zero extended in the low element of
4471 // a vector. If Idx != 0, swizzle it into place.
4473 SmallVector<int, 4> Mask;
4474 Mask.push_back(Idx);
4475 for (unsigned i = 1; i != VecElts; ++i)
4477 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4478 DAG.getUNDEF(Item.getValueType()),
4481 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4485 // If we have a constant or non-constant insertion into the low element of
4486 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4487 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4488 // depending on what the source datatype is.
4491 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4492 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4493 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4494 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4495 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4496 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4498 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4499 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4500 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4501 EVT MiddleVT = MVT::v4i32;
4502 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4503 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4504 Subtarget->hasSSE2(), DAG);
4505 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4509 // Is it a vector logical left shift?
4510 if (NumElems == 2 && Idx == 1 &&
4511 X86::isZeroNode(Op.getOperand(0)) &&
4512 !X86::isZeroNode(Op.getOperand(1))) {
4513 unsigned NumBits = VT.getSizeInBits();
4514 return getVShift(true, VT,
4515 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4516 VT, Op.getOperand(1)),
4517 NumBits/2, DAG, *this, dl);
4520 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4523 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4524 // is a non-constant being inserted into an element other than the low one,
4525 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4526 // movd/movss) to move this into the low element, then shuffle it into
4528 if (EVTBits == 32) {
4529 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4531 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4532 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4533 Subtarget->hasSSE2(), DAG);
4534 SmallVector<int, 8> MaskVec;
4535 for (unsigned i = 0; i < NumElems; i++)
4536 MaskVec.push_back(i == Idx ? 0 : 1);
4537 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4541 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4542 if (Values.size() == 1) {
4543 if (EVTBits == 32) {
4544 // Instead of a shuffle like this:
4545 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4546 // Check if it's possible to issue this instead.
4547 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4548 unsigned Idx = CountTrailingZeros_32(NonZeros);
4549 SDValue Item = Op.getOperand(Idx);
4550 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4551 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4556 // A vector full of immediates; various special cases are already
4557 // handled, so this is best done with a single constant-pool load.
4561 // Let legalizer expand 2-wide build_vectors.
4562 if (EVTBits == 64) {
4563 if (NumNonZero == 1) {
4564 // One half is zero or undef.
4565 unsigned Idx = CountTrailingZeros_32(NonZeros);
4566 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4567 Op.getOperand(Idx));
4568 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4569 Subtarget->hasSSE2(), DAG);
4574 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4575 if (EVTBits == 8 && NumElems == 16) {
4576 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4578 if (V.getNode()) return V;
4581 if (EVTBits == 16 && NumElems == 8) {
4582 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4584 if (V.getNode()) return V;
4587 // If element VT is == 32 bits, turn it into a number of shuffles.
4588 SmallVector<SDValue, 8> V;
4590 if (NumElems == 4 && NumZero > 0) {
4591 for (unsigned i = 0; i < 4; ++i) {
4592 bool isZero = !(NonZeros & (1 << i));
4594 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4596 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4599 for (unsigned i = 0; i < 2; ++i) {
4600 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4603 V[i] = V[i*2]; // Must be a zero vector.
4606 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4609 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4612 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4617 SmallVector<int, 8> MaskVec;
4618 bool Reverse = (NonZeros & 0x3) == 2;
4619 for (unsigned i = 0; i < 2; ++i)
4620 MaskVec.push_back(Reverse ? 1-i : i);
4621 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4622 for (unsigned i = 0; i < 2; ++i)
4623 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4624 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4627 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4628 // Check for a build vector of consecutive loads.
4629 for (unsigned i = 0; i < NumElems; ++i)
4630 V[i] = Op.getOperand(i);
4632 // Check for elements which are consecutive loads.
4633 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4637 // For SSE 4.1, use insertps to put the high elements into the low element.
4638 if (getSubtarget()->hasSSE41()) {
4640 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4641 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4643 Result = DAG.getUNDEF(VT);
4645 for (unsigned i = 1; i < NumElems; ++i) {
4646 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4647 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4648 Op.getOperand(i), DAG.getIntPtrConstant(i));
4653 // Otherwise, expand into a number of unpckl*, start by extending each of
4654 // our (non-undef) elements to the full vector width with the element in the
4655 // bottom slot of the vector (which generates no code for SSE).
4656 for (unsigned i = 0; i < NumElems; ++i) {
4657 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4658 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4660 V[i] = DAG.getUNDEF(VT);
4663 // Next, we iteratively mix elements, e.g. for v4f32:
4664 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4665 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4666 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4667 unsigned EltStride = NumElems >> 1;
4668 while (EltStride != 0) {
4669 for (unsigned i = 0; i < EltStride; ++i) {
4670 // If V[i+EltStride] is undef and this is the first round of mixing,
4671 // then it is safe to just drop this shuffle: V[i] is already in the
4672 // right place, the one element (since it's the first round) being
4673 // inserted as undef can be dropped. This isn't safe for successive
4674 // rounds because they will permute elements within both vectors.
4675 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4676 EltStride == NumElems/2)
4679 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4689 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4690 // We support concatenate two MMX registers and place them in a MMX
4691 // register. This is better than doing a stack convert.
4692 DebugLoc dl = Op.getDebugLoc();
4693 EVT ResVT = Op.getValueType();
4694 assert(Op.getNumOperands() == 2);
4695 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4696 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4698 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4699 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4700 InVec = Op.getOperand(1);
4701 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4702 unsigned NumElts = ResVT.getVectorNumElements();
4703 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4704 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4705 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4707 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4708 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4709 Mask[0] = 0; Mask[1] = 2;
4710 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4712 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4715 // v8i16 shuffles - Prefer shuffles in the following order:
4716 // 1. [all] pshuflw, pshufhw, optional move
4717 // 2. [ssse3] 1 x pshufb
4718 // 3. [ssse3] 2 x pshufb + 1 x por
4719 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4721 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4722 SelectionDAG &DAG) const {
4723 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4724 SDValue V1 = SVOp->getOperand(0);
4725 SDValue V2 = SVOp->getOperand(1);
4726 DebugLoc dl = SVOp->getDebugLoc();
4727 SmallVector<int, 8> MaskVals;
4729 // Determine if more than 1 of the words in each of the low and high quadwords
4730 // of the result come from the same quadword of one of the two inputs. Undef
4731 // mask values count as coming from any quadword, for better codegen.
4732 SmallVector<unsigned, 4> LoQuad(4);
4733 SmallVector<unsigned, 4> HiQuad(4);
4734 BitVector InputQuads(4);
4735 for (unsigned i = 0; i < 8; ++i) {
4736 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4737 int EltIdx = SVOp->getMaskElt(i);
4738 MaskVals.push_back(EltIdx);
4747 InputQuads.set(EltIdx / 4);
4750 int BestLoQuad = -1;
4751 unsigned MaxQuad = 1;
4752 for (unsigned i = 0; i < 4; ++i) {
4753 if (LoQuad[i] > MaxQuad) {
4755 MaxQuad = LoQuad[i];
4759 int BestHiQuad = -1;
4761 for (unsigned i = 0; i < 4; ++i) {
4762 if (HiQuad[i] > MaxQuad) {
4764 MaxQuad = HiQuad[i];
4768 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4769 // of the two input vectors, shuffle them into one input vector so only a
4770 // single pshufb instruction is necessary. If There are more than 2 input
4771 // quads, disable the next transformation since it does not help SSSE3.
4772 bool V1Used = InputQuads[0] || InputQuads[1];
4773 bool V2Used = InputQuads[2] || InputQuads[3];
4774 if (Subtarget->hasSSSE3()) {
4775 if (InputQuads.count() == 2 && V1Used && V2Used) {
4776 BestLoQuad = InputQuads.find_first();
4777 BestHiQuad = InputQuads.find_next(BestLoQuad);
4779 if (InputQuads.count() > 2) {
4785 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4786 // the shuffle mask. If a quad is scored as -1, that means that it contains
4787 // words from all 4 input quadwords.
4789 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4790 SmallVector<int, 8> MaskV;
4791 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4792 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4793 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4794 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4795 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4796 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4798 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4799 // source words for the shuffle, to aid later transformations.
4800 bool AllWordsInNewV = true;
4801 bool InOrder[2] = { true, true };
4802 for (unsigned i = 0; i != 8; ++i) {
4803 int idx = MaskVals[i];
4805 InOrder[i/4] = false;
4806 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4808 AllWordsInNewV = false;
4812 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4813 if (AllWordsInNewV) {
4814 for (int i = 0; i != 8; ++i) {
4815 int idx = MaskVals[i];
4818 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4819 if ((idx != i) && idx < 4)
4821 if ((idx != i) && idx > 3)
4830 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4831 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4832 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4833 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4834 unsigned TargetMask = 0;
4835 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4836 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4837 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4838 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4839 V1 = NewV.getOperand(0);
4840 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4844 // If we have SSSE3, and all words of the result are from 1 input vector,
4845 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4846 // is present, fall back to case 4.
4847 if (Subtarget->hasSSSE3()) {
4848 SmallVector<SDValue,16> pshufbMask;
4850 // If we have elements from both input vectors, set the high bit of the
4851 // shuffle mask element to zero out elements that come from V2 in the V1
4852 // mask, and elements that come from V1 in the V2 mask, so that the two
4853 // results can be OR'd together.
4854 bool TwoInputs = V1Used && V2Used;
4855 for (unsigned i = 0; i != 8; ++i) {
4856 int EltIdx = MaskVals[i] * 2;
4857 if (TwoInputs && (EltIdx >= 16)) {
4858 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4859 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4862 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4863 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4865 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4866 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4867 DAG.getNode(ISD::BUILD_VECTOR, dl,
4868 MVT::v16i8, &pshufbMask[0], 16));
4870 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4872 // Calculate the shuffle mask for the second input, shuffle it, and
4873 // OR it with the first shuffled input.
4875 for (unsigned i = 0; i != 8; ++i) {
4876 int EltIdx = MaskVals[i] * 2;
4878 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4879 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4882 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4883 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4885 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4886 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4887 DAG.getNode(ISD::BUILD_VECTOR, dl,
4888 MVT::v16i8, &pshufbMask[0], 16));
4889 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4890 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4893 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4894 // and update MaskVals with new element order.
4895 BitVector InOrder(8);
4896 if (BestLoQuad >= 0) {
4897 SmallVector<int, 8> MaskV;
4898 for (int i = 0; i != 4; ++i) {
4899 int idx = MaskVals[i];
4901 MaskV.push_back(-1);
4903 } else if ((idx / 4) == BestLoQuad) {
4904 MaskV.push_back(idx & 3);
4907 MaskV.push_back(-1);
4910 for (unsigned i = 4; i != 8; ++i)
4912 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4915 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4916 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4918 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4922 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4923 // and update MaskVals with the new element order.
4924 if (BestHiQuad >= 0) {
4925 SmallVector<int, 8> MaskV;
4926 for (unsigned i = 0; i != 4; ++i)
4928 for (unsigned i = 4; i != 8; ++i) {
4929 int idx = MaskVals[i];
4931 MaskV.push_back(-1);
4933 } else if ((idx / 4) == BestHiQuad) {
4934 MaskV.push_back((idx & 3) + 4);
4937 MaskV.push_back(-1);
4940 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4943 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4944 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4946 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4950 // In case BestHi & BestLo were both -1, which means each quadword has a word
4951 // from each of the four input quadwords, calculate the InOrder bitvector now
4952 // before falling through to the insert/extract cleanup.
4953 if (BestLoQuad == -1 && BestHiQuad == -1) {
4955 for (int i = 0; i != 8; ++i)
4956 if (MaskVals[i] < 0 || MaskVals[i] == i)
4960 // The other elements are put in the right place using pextrw and pinsrw.
4961 for (unsigned i = 0; i != 8; ++i) {
4964 int EltIdx = MaskVals[i];
4967 SDValue ExtOp = (EltIdx < 8)
4968 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4969 DAG.getIntPtrConstant(EltIdx))
4970 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4971 DAG.getIntPtrConstant(EltIdx - 8));
4972 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4973 DAG.getIntPtrConstant(i));
4978 // v16i8 shuffles - Prefer shuffles in the following order:
4979 // 1. [ssse3] 1 x pshufb
4980 // 2. [ssse3] 2 x pshufb + 1 x por
4981 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4983 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4985 const X86TargetLowering &TLI) {
4986 SDValue V1 = SVOp->getOperand(0);
4987 SDValue V2 = SVOp->getOperand(1);
4988 DebugLoc dl = SVOp->getDebugLoc();
4989 SmallVector<int, 16> MaskVals;
4990 SVOp->getMask(MaskVals);
4992 // If we have SSSE3, case 1 is generated when all result bytes come from
4993 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4994 // present, fall back to case 3.
4995 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4998 for (unsigned i = 0; i < 16; ++i) {
4999 int EltIdx = MaskVals[i];
5008 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5009 if (TLI.getSubtarget()->hasSSSE3()) {
5010 SmallVector<SDValue,16> pshufbMask;
5012 // If all result elements are from one input vector, then only translate
5013 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5015 // Otherwise, we have elements from both input vectors, and must zero out
5016 // elements that come from V2 in the first mask, and V1 in the second mask
5017 // so that we can OR them together.
5018 bool TwoInputs = !(V1Only || V2Only);
5019 for (unsigned i = 0; i != 16; ++i) {
5020 int EltIdx = MaskVals[i];
5021 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5022 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5025 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5027 // If all the elements are from V2, assign it to V1 and return after
5028 // building the first pshufb.
5031 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5032 DAG.getNode(ISD::BUILD_VECTOR, dl,
5033 MVT::v16i8, &pshufbMask[0], 16));
5037 // Calculate the shuffle mask for the second input, shuffle it, and
5038 // OR it with the first shuffled input.
5040 for (unsigned i = 0; i != 16; ++i) {
5041 int EltIdx = MaskVals[i];
5043 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5046 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5048 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5049 DAG.getNode(ISD::BUILD_VECTOR, dl,
5050 MVT::v16i8, &pshufbMask[0], 16));
5051 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5054 // No SSSE3 - Calculate in place words and then fix all out of place words
5055 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5056 // the 16 different words that comprise the two doublequadword input vectors.
5057 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5058 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5059 SDValue NewV = V2Only ? V2 : V1;
5060 for (int i = 0; i != 8; ++i) {
5061 int Elt0 = MaskVals[i*2];
5062 int Elt1 = MaskVals[i*2+1];
5064 // This word of the result is all undef, skip it.
5065 if (Elt0 < 0 && Elt1 < 0)
5068 // This word of the result is already in the correct place, skip it.
5069 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5071 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5074 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5075 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5078 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5079 // using a single extract together, load it and store it.
5080 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5081 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5082 DAG.getIntPtrConstant(Elt1 / 2));
5083 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5084 DAG.getIntPtrConstant(i));
5088 // If Elt1 is defined, extract it from the appropriate source. If the
5089 // source byte is not also odd, shift the extracted word left 8 bits
5090 // otherwise clear the bottom 8 bits if we need to do an or.
5092 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5093 DAG.getIntPtrConstant(Elt1 / 2));
5094 if ((Elt1 & 1) == 0)
5095 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5097 TLI.getShiftAmountTy(InsElt.getValueType())));
5099 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5100 DAG.getConstant(0xFF00, MVT::i16));
5102 // If Elt0 is defined, extract it from the appropriate source. If the
5103 // source byte is not also even, shift the extracted word right 8 bits. If
5104 // Elt1 was also defined, OR the extracted values together before
5105 // inserting them in the result.
5107 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5108 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5109 if ((Elt0 & 1) != 0)
5110 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5112 TLI.getShiftAmountTy(InsElt0.getValueType())));
5114 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5115 DAG.getConstant(0x00FF, MVT::i16));
5116 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5119 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5120 DAG.getIntPtrConstant(i));
5122 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5125 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5126 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5127 /// done when every pair / quad of shuffle mask elements point to elements in
5128 /// the right sequence. e.g.
5129 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5131 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5132 SelectionDAG &DAG, DebugLoc dl) {
5133 EVT VT = SVOp->getValueType(0);
5134 SDValue V1 = SVOp->getOperand(0);
5135 SDValue V2 = SVOp->getOperand(1);
5136 unsigned NumElems = VT.getVectorNumElements();
5137 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5139 switch (VT.getSimpleVT().SimpleTy) {
5140 default: assert(false && "Unexpected!");
5141 case MVT::v4f32: NewVT = MVT::v2f64; break;
5142 case MVT::v4i32: NewVT = MVT::v2i64; break;
5143 case MVT::v8i16: NewVT = MVT::v4i32; break;
5144 case MVT::v16i8: NewVT = MVT::v4i32; break;
5147 int Scale = NumElems / NewWidth;
5148 SmallVector<int, 8> MaskVec;
5149 for (unsigned i = 0; i < NumElems; i += Scale) {
5151 for (int j = 0; j < Scale; ++j) {
5152 int EltIdx = SVOp->getMaskElt(i+j);
5156 StartIdx = EltIdx - (EltIdx % Scale);
5157 if (EltIdx != StartIdx + j)
5161 MaskVec.push_back(-1);
5163 MaskVec.push_back(StartIdx / Scale);
5166 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5167 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5168 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5171 /// getVZextMovL - Return a zero-extending vector move low node.
5173 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5174 SDValue SrcOp, SelectionDAG &DAG,
5175 const X86Subtarget *Subtarget, DebugLoc dl) {
5176 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5177 LoadSDNode *LD = NULL;
5178 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5179 LD = dyn_cast<LoadSDNode>(SrcOp);
5181 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5183 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5184 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5185 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5186 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5187 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5189 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5190 return DAG.getNode(ISD::BITCAST, dl, VT,
5191 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5192 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5200 return DAG.getNode(ISD::BITCAST, dl, VT,
5201 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5202 DAG.getNode(ISD::BITCAST, dl,
5206 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5209 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5210 SDValue V1 = SVOp->getOperand(0);
5211 SDValue V2 = SVOp->getOperand(1);
5212 DebugLoc dl = SVOp->getDebugLoc();
5213 EVT VT = SVOp->getValueType(0);
5215 SmallVector<std::pair<int, int>, 8> Locs;
5217 SmallVector<int, 8> Mask1(4U, -1);
5218 SmallVector<int, 8> PermMask;
5219 SVOp->getMask(PermMask);
5223 for (unsigned i = 0; i != 4; ++i) {
5224 int Idx = PermMask[i];
5226 Locs[i] = std::make_pair(-1, -1);
5228 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5230 Locs[i] = std::make_pair(0, NumLo);
5234 Locs[i] = std::make_pair(1, NumHi);
5236 Mask1[2+NumHi] = Idx;
5242 if (NumLo <= 2 && NumHi <= 2) {
5243 // If no more than two elements come from either vector. This can be
5244 // implemented with two shuffles. First shuffle gather the elements.
5245 // The second shuffle, which takes the first shuffle as both of its
5246 // vector operands, put the elements into the right order.
5247 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5249 SmallVector<int, 8> Mask2(4U, -1);
5251 for (unsigned i = 0; i != 4; ++i) {
5252 if (Locs[i].first == -1)
5255 unsigned Idx = (i < 2) ? 0 : 4;
5256 Idx += Locs[i].first * 2 + Locs[i].second;
5261 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5262 } else if (NumLo == 3 || NumHi == 3) {
5263 // Otherwise, we must have three elements from one vector, call it X, and
5264 // one element from the other, call it Y. First, use a shufps to build an
5265 // intermediate vector with the one element from Y and the element from X
5266 // that will be in the same half in the final destination (the indexes don't
5267 // matter). Then, use a shufps to build the final vector, taking the half
5268 // containing the element from Y from the intermediate, and the other half
5271 // Normalize it so the 3 elements come from V1.
5272 CommuteVectorShuffleMask(PermMask, VT);
5276 // Find the element from V2.
5278 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5279 int Val = PermMask[HiIndex];
5286 Mask1[0] = PermMask[HiIndex];
5288 Mask1[2] = PermMask[HiIndex^1];
5290 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5293 Mask1[0] = PermMask[0];
5294 Mask1[1] = PermMask[1];
5295 Mask1[2] = HiIndex & 1 ? 6 : 4;
5296 Mask1[3] = HiIndex & 1 ? 4 : 6;
5297 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5299 Mask1[0] = HiIndex & 1 ? 2 : 0;
5300 Mask1[1] = HiIndex & 1 ? 0 : 2;
5301 Mask1[2] = PermMask[2];
5302 Mask1[3] = PermMask[3];
5307 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5311 // Break it into (shuffle shuffle_hi, shuffle_lo).
5314 SmallVector<int,8> LoMask(4U, -1);
5315 SmallVector<int,8> HiMask(4U, -1);
5317 SmallVector<int,8> *MaskPtr = &LoMask;
5318 unsigned MaskIdx = 0;
5321 for (unsigned i = 0; i != 4; ++i) {
5328 int Idx = PermMask[i];
5330 Locs[i] = std::make_pair(-1, -1);
5331 } else if (Idx < 4) {
5332 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5333 (*MaskPtr)[LoIdx] = Idx;
5336 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5337 (*MaskPtr)[HiIdx] = Idx;
5342 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5343 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5344 SmallVector<int, 8> MaskOps;
5345 for (unsigned i = 0; i != 4; ++i) {
5346 if (Locs[i].first == -1) {
5347 MaskOps.push_back(-1);
5349 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5350 MaskOps.push_back(Idx);
5353 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5356 static bool MayFoldVectorLoad(SDValue V) {
5357 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5358 V = V.getOperand(0);
5359 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5360 V = V.getOperand(0);
5366 // FIXME: the version above should always be used. Since there's
5367 // a bug where several vector shuffles can't be folded because the
5368 // DAG is not updated during lowering and a node claims to have two
5369 // uses while it only has one, use this version, and let isel match
5370 // another instruction if the load really happens to have more than
5371 // one use. Remove this version after this bug get fixed.
5372 // rdar://8434668, PR8156
5373 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5374 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5375 V = V.getOperand(0);
5376 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5377 V = V.getOperand(0);
5378 if (ISD::isNormalLoad(V.getNode()))
5383 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5384 /// a vector extract, and if both can be later optimized into a single load.
5385 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5386 /// here because otherwise a target specific shuffle node is going to be
5387 /// emitted for this shuffle, and the optimization not done.
5388 /// FIXME: This is probably not the best approach, but fix the problem
5389 /// until the right path is decided.
5391 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5392 const TargetLowering &TLI) {
5393 EVT VT = V.getValueType();
5394 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5396 // Be sure that the vector shuffle is present in a pattern like this:
5397 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5401 SDNode *N = *V.getNode()->use_begin();
5402 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5405 SDValue EltNo = N->getOperand(1);
5406 if (!isa<ConstantSDNode>(EltNo))
5409 // If the bit convert changed the number of elements, it is unsafe
5410 // to examine the mask.
5411 bool HasShuffleIntoBitcast = false;
5412 if (V.getOpcode() == ISD::BITCAST) {
5413 EVT SrcVT = V.getOperand(0).getValueType();
5414 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5416 V = V.getOperand(0);
5417 HasShuffleIntoBitcast = true;
5420 // Select the input vector, guarding against out of range extract vector.
5421 unsigned NumElems = VT.getVectorNumElements();
5422 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5423 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5424 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5426 // Skip one more bit_convert if necessary
5427 if (V.getOpcode() == ISD::BITCAST)
5428 V = V.getOperand(0);
5430 if (ISD::isNormalLoad(V.getNode())) {
5431 // Is the original load suitable?
5432 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5434 // FIXME: avoid the multi-use bug that is preventing lots of
5435 // of foldings to be detected, this is still wrong of course, but
5436 // give the temporary desired behavior, and if it happens that
5437 // the load has real more uses, during isel it will not fold, and
5438 // will generate poor code.
5439 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5442 if (!HasShuffleIntoBitcast)
5445 // If there's a bitcast before the shuffle, check if the load type and
5446 // alignment is valid.
5447 unsigned Align = LN0->getAlignment();
5449 TLI.getTargetData()->getABITypeAlignment(
5450 VT.getTypeForEVT(*DAG.getContext()));
5452 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5460 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5461 EVT VT = Op.getValueType();
5463 // Canonizalize to v2f64.
5464 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5465 return DAG.getNode(ISD::BITCAST, dl, VT,
5466 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5471 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5473 SDValue V1 = Op.getOperand(0);
5474 SDValue V2 = Op.getOperand(1);
5475 EVT VT = Op.getValueType();
5477 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5479 if (HasSSE2 && VT == MVT::v2f64)
5480 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5483 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5487 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5488 SDValue V1 = Op.getOperand(0);
5489 SDValue V2 = Op.getOperand(1);
5490 EVT VT = Op.getValueType();
5492 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5493 "unsupported shuffle type");
5495 if (V2.getOpcode() == ISD::UNDEF)
5499 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5503 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5504 SDValue V1 = Op.getOperand(0);
5505 SDValue V2 = Op.getOperand(1);
5506 EVT VT = Op.getValueType();
5507 unsigned NumElems = VT.getVectorNumElements();
5509 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5510 // operand of these instructions is only memory, so check if there's a
5511 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5513 bool CanFoldLoad = false;
5515 // Trivial case, when V2 comes from a load.
5516 if (MayFoldVectorLoad(V2))
5519 // When V1 is a load, it can be folded later into a store in isel, example:
5520 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5522 // (MOVLPSmr addr:$src1, VR128:$src2)
5523 // So, recognize this potential and also use MOVLPS or MOVLPD
5524 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5527 // Both of them can't be memory operations though.
5528 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5529 CanFoldLoad = false;
5532 if (HasSSE2 && NumElems == 2)
5533 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5536 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5539 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5540 // movl and movlp will both match v2i64, but v2i64 is never matched by
5541 // movl earlier because we make it strict to avoid messing with the movlp load
5542 // folding logic (see the code above getMOVLP call). Match it here then,
5543 // this is horrible, but will stay like this until we move all shuffle
5544 // matching to x86 specific nodes. Note that for the 1st condition all
5545 // types are matched with movsd.
5546 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5547 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5549 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5552 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5554 // Invert the operand order and use SHUFPS to match it.
5555 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5556 X86::getShuffleSHUFImmediate(SVOp), DAG);
5559 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5560 switch(VT.getSimpleVT().SimpleTy) {
5561 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5562 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5564 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5566 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5567 case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5568 case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5569 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5570 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5572 llvm_unreachable("Unknown type for unpckl");
5577 static inline unsigned getUNPCKHOpcode(EVT VT) {
5578 switch(VT.getSimpleVT().SimpleTy) {
5579 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5580 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5581 case MVT::v4f32: return X86ISD::UNPCKHPS;
5582 case MVT::v2f64: return X86ISD::UNPCKHPD;
5583 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5584 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5586 llvm_unreachable("Unknown type for unpckh");
5592 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5593 const TargetLowering &TLI,
5594 const X86Subtarget *Subtarget) {
5595 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5596 EVT VT = Op.getValueType();
5597 DebugLoc dl = Op.getDebugLoc();
5598 SDValue V1 = Op.getOperand(0);
5599 SDValue V2 = Op.getOperand(1);
5601 if (isZeroShuffle(SVOp))
5602 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5604 // Handle splat operations
5605 if (SVOp->isSplat()) {
5606 // Special case, this is the only place now where it's
5607 // allowed to return a vector_shuffle operation without
5608 // using a target specific node, because *hopefully* it
5609 // will be optimized away by the dag combiner.
5610 if (VT.getVectorNumElements() <= 4 &&
5611 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5614 // Handle splats by matching through known masks
5615 if (VT.getVectorNumElements() <= 4)
5618 // Canonicalize all of the remaining to v4f32.
5619 return PromoteSplat(SVOp, DAG);
5622 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5624 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5625 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5626 if (NewOp.getNode())
5627 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5628 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5629 // FIXME: Figure out a cleaner way to do this.
5630 // Try to make use of movq to zero out the top part.
5631 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5632 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5633 if (NewOp.getNode()) {
5634 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5635 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5636 DAG, Subtarget, dl);
5638 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5639 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5640 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5641 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5642 DAG, Subtarget, dl);
5649 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5650 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5651 SDValue V1 = Op.getOperand(0);
5652 SDValue V2 = Op.getOperand(1);
5653 EVT VT = Op.getValueType();
5654 DebugLoc dl = Op.getDebugLoc();
5655 unsigned NumElems = VT.getVectorNumElements();
5656 bool isMMX = VT.getSizeInBits() == 64;
5657 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5658 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5659 bool V1IsSplat = false;
5660 bool V2IsSplat = false;
5661 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5662 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5663 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5664 MachineFunction &MF = DAG.getMachineFunction();
5665 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5667 // Shuffle operations on MMX not supported.
5671 // Vector shuffle lowering takes 3 steps:
5673 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5674 // narrowing and commutation of operands should be handled.
5675 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5677 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5678 // so the shuffle can be broken into other shuffles and the legalizer can
5679 // try the lowering again.
5681 // The general ideia is that no vector_shuffle operation should be left to
5682 // be matched during isel, all of them must be converted to a target specific
5685 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5686 // narrowing and commutation of operands should be handled. The actual code
5687 // doesn't include all of those, work in progress...
5688 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5689 if (NewOp.getNode())
5692 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5693 // unpckh_undef). Only use pshufd if speed is more important than size.
5694 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5695 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5696 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5697 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5698 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5699 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5701 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5702 RelaxedMayFoldVectorLoad(V1))
5703 return getMOVDDup(Op, dl, V1, DAG);
5705 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5706 return getMOVHighToLow(Op, dl, DAG);
5708 // Use to match splats
5709 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5710 (VT == MVT::v2f64 || VT == MVT::v2i64))
5711 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5713 if (X86::isPSHUFDMask(SVOp)) {
5714 // The actual implementation will match the mask in the if above and then
5715 // during isel it can match several different instructions, not only pshufd
5716 // as its name says, sad but true, emulate the behavior for now...
5717 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5718 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5720 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5722 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5723 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5725 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5726 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5729 if (VT == MVT::v4f32)
5730 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5734 // Check if this can be converted into a logical shift.
5735 bool isLeft = false;
5738 bool isShift = getSubtarget()->hasSSE2() &&
5739 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5740 if (isShift && ShVal.hasOneUse()) {
5741 // If the shifted value has multiple uses, it may be cheaper to use
5742 // v_set0 + movlhps or movhlps, etc.
5743 EVT EltVT = VT.getVectorElementType();
5744 ShAmt *= EltVT.getSizeInBits();
5745 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5748 if (X86::isMOVLMask(SVOp)) {
5751 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5752 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5753 if (!X86::isMOVLPMask(SVOp)) {
5754 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5755 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5757 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5758 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5762 // FIXME: fold these into legal mask.
5763 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5764 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5766 if (X86::isMOVHLPSMask(SVOp))
5767 return getMOVHighToLow(Op, dl, DAG);
5769 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5770 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5772 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5773 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5775 if (X86::isMOVLPMask(SVOp))
5776 return getMOVLP(Op, dl, DAG, HasSSE2);
5778 if (ShouldXformToMOVHLPS(SVOp) ||
5779 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5780 return CommuteVectorShuffle(SVOp, DAG);
5783 // No better options. Use a vshl / vsrl.
5784 EVT EltVT = VT.getVectorElementType();
5785 ShAmt *= EltVT.getSizeInBits();
5786 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5789 bool Commuted = false;
5790 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5791 // 1,1,1,1 -> v8i16 though.
5792 V1IsSplat = isSplatVector(V1.getNode());
5793 V2IsSplat = isSplatVector(V2.getNode());
5795 // Canonicalize the splat or undef, if present, to be on the RHS.
5796 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5797 Op = CommuteVectorShuffle(SVOp, DAG);
5798 SVOp = cast<ShuffleVectorSDNode>(Op);
5799 V1 = SVOp->getOperand(0);
5800 V2 = SVOp->getOperand(1);
5801 std::swap(V1IsSplat, V2IsSplat);
5802 std::swap(V1IsUndef, V2IsUndef);
5806 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5807 // Shuffling low element of v1 into undef, just return v1.
5810 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5811 // the instruction selector will not match, so get a canonical MOVL with
5812 // swapped operands to undo the commute.
5813 return getMOVL(DAG, dl, VT, V2, V1);
5816 if (X86::isUNPCKLMask(SVOp))
5817 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5818 dl, VT, V1, V2, DAG);
5820 if (X86::isUNPCKHMask(SVOp))
5821 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5824 // Normalize mask so all entries that point to V2 points to its first
5825 // element then try to match unpck{h|l} again. If match, return a
5826 // new vector_shuffle with the corrected mask.
5827 SDValue NewMask = NormalizeMask(SVOp, DAG);
5828 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5829 if (NSVOp != SVOp) {
5830 if (X86::isUNPCKLMask(NSVOp, true)) {
5832 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5839 // Commute is back and try unpck* again.
5840 // FIXME: this seems wrong.
5841 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5842 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5844 if (X86::isUNPCKLMask(NewSVOp))
5845 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5846 dl, VT, V2, V1, DAG);
5848 if (X86::isUNPCKHMask(NewSVOp))
5849 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5852 // Normalize the node to match x86 shuffle ops if needed
5853 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5854 return CommuteVectorShuffle(SVOp, DAG);
5856 // The checks below are all present in isShuffleMaskLegal, but they are
5857 // inlined here right now to enable us to directly emit target specific
5858 // nodes, and remove one by one until they don't return Op anymore.
5859 SmallVector<int, 16> M;
5862 if (isPALIGNRMask(M, VT, HasSSSE3))
5863 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5864 X86::getShufflePALIGNRImmediate(SVOp),
5867 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5868 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5869 if (VT == MVT::v2f64) {
5870 X86ISD::NodeType Opcode =
5871 getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5872 return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5874 if (VT == MVT::v2i64)
5875 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5878 if (isPSHUFHWMask(M, VT))
5879 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5880 X86::getShufflePSHUFHWImmediate(SVOp),
5883 if (isPSHUFLWMask(M, VT))
5884 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5885 X86::getShufflePSHUFLWImmediate(SVOp),
5888 if (isSHUFPMask(M, VT)) {
5889 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5890 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5891 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5893 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5894 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5898 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5899 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5900 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5901 dl, VT, V1, V1, DAG);
5902 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5903 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5904 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5906 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5907 if (VT == MVT::v8i16) {
5908 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5909 if (NewOp.getNode())
5913 if (VT == MVT::v16i8) {
5914 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5915 if (NewOp.getNode())
5919 // Handle all 4 wide cases with a number of shuffles.
5921 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5927 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5928 SelectionDAG &DAG) const {
5929 EVT VT = Op.getValueType();
5930 DebugLoc dl = Op.getDebugLoc();
5931 if (VT.getSizeInBits() == 8) {
5932 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5933 Op.getOperand(0), Op.getOperand(1));
5934 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5935 DAG.getValueType(VT));
5936 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5937 } else if (VT.getSizeInBits() == 16) {
5938 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5939 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5941 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5942 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5943 DAG.getNode(ISD::BITCAST, dl,
5947 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5948 Op.getOperand(0), Op.getOperand(1));
5949 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5950 DAG.getValueType(VT));
5951 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5952 } else if (VT == MVT::f32) {
5953 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5954 // the result back to FR32 register. It's only worth matching if the
5955 // result has a single use which is a store or a bitcast to i32. And in
5956 // the case of a store, it's not worth it if the index is a constant 0,
5957 // because a MOVSSmr can be used instead, which is smaller and faster.
5958 if (!Op.hasOneUse())
5960 SDNode *User = *Op.getNode()->use_begin();
5961 if ((User->getOpcode() != ISD::STORE ||
5962 (isa<ConstantSDNode>(Op.getOperand(1)) &&
5963 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5964 (User->getOpcode() != ISD::BITCAST ||
5965 User->getValueType(0) != MVT::i32))
5967 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5968 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5971 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5972 } else if (VT == MVT::i32) {
5973 // ExtractPS works with constant index.
5974 if (isa<ConstantSDNode>(Op.getOperand(1)))
5982 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5983 SelectionDAG &DAG) const {
5984 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5987 SDValue Vec = Op.getOperand(0);
5988 EVT VecVT = Vec.getValueType();
5990 // If this is a 256-bit vector result, first extract the 128-bit
5991 // vector and then extract from the 128-bit vector.
5992 if (VecVT.getSizeInBits() > 128) {
5993 DebugLoc dl = Op.getNode()->getDebugLoc();
5994 unsigned NumElems = VecVT.getVectorNumElements();
5995 SDValue Idx = Op.getOperand(1);
5997 if (!isa<ConstantSDNode>(Idx))
6000 unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6001 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6003 // Get the 128-bit vector.
6004 bool Upper = IdxVal >= ExtractNumElems;
6005 Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6008 SDValue ScaledIdx = Idx;
6010 ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6011 DAG.getConstant(ExtractNumElems,
6012 Idx.getValueType()));
6013 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6017 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6019 if (Subtarget->hasSSE41()) {
6020 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6025 EVT VT = Op.getValueType();
6026 DebugLoc dl = Op.getDebugLoc();
6027 // TODO: handle v16i8.
6028 if (VT.getSizeInBits() == 16) {
6029 SDValue Vec = Op.getOperand(0);
6030 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6032 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6033 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6034 DAG.getNode(ISD::BITCAST, dl,
6037 // Transform it so it match pextrw which produces a 32-bit result.
6038 EVT EltVT = MVT::i32;
6039 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6040 Op.getOperand(0), Op.getOperand(1));
6041 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6042 DAG.getValueType(VT));
6043 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6044 } else if (VT.getSizeInBits() == 32) {
6045 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6049 // SHUFPS the element to the lowest double word, then movss.
6050 int Mask[4] = { Idx, -1, -1, -1 };
6051 EVT VVT = Op.getOperand(0).getValueType();
6052 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6053 DAG.getUNDEF(VVT), Mask);
6054 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6055 DAG.getIntPtrConstant(0));
6056 } else if (VT.getSizeInBits() == 64) {
6057 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6058 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6059 // to match extract_elt for f64.
6060 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6064 // UNPCKHPD the element to the lowest double word, then movsd.
6065 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6066 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6067 int Mask[2] = { 1, -1 };
6068 EVT VVT = Op.getOperand(0).getValueType();
6069 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6070 DAG.getUNDEF(VVT), Mask);
6071 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6072 DAG.getIntPtrConstant(0));
6079 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6080 SelectionDAG &DAG) const {
6081 EVT VT = Op.getValueType();
6082 EVT EltVT = VT.getVectorElementType();
6083 DebugLoc dl = Op.getDebugLoc();
6085 SDValue N0 = Op.getOperand(0);
6086 SDValue N1 = Op.getOperand(1);
6087 SDValue N2 = Op.getOperand(2);
6089 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6090 isa<ConstantSDNode>(N2)) {
6092 if (VT == MVT::v8i16)
6093 Opc = X86ISD::PINSRW;
6094 else if (VT == MVT::v16i8)
6095 Opc = X86ISD::PINSRB;
6097 Opc = X86ISD::PINSRB;
6099 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6101 if (N1.getValueType() != MVT::i32)
6102 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6103 if (N2.getValueType() != MVT::i32)
6104 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6105 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6106 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6107 // Bits [7:6] of the constant are the source select. This will always be
6108 // zero here. The DAG Combiner may combine an extract_elt index into these
6109 // bits. For example (insert (extract, 3), 2) could be matched by putting
6110 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6111 // Bits [5:4] of the constant are the destination select. This is the
6112 // value of the incoming immediate.
6113 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6114 // combine either bitwise AND or insert of float 0.0 to set these bits.
6115 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6116 // Create this as a scalar to vector..
6117 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6118 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6119 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6120 // PINSR* works with constant index.
6127 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6128 EVT VT = Op.getValueType();
6129 EVT EltVT = VT.getVectorElementType();
6131 DebugLoc dl = Op.getDebugLoc();
6132 SDValue N0 = Op.getOperand(0);
6133 SDValue N1 = Op.getOperand(1);
6134 SDValue N2 = Op.getOperand(2);
6136 // If this is a 256-bit vector result, first insert into a 128-bit
6137 // vector and then insert into the 256-bit vector.
6138 if (VT.getSizeInBits() > 128) {
6139 if (!isa<ConstantSDNode>(N2))
6142 // Get the 128-bit vector.
6143 unsigned NumElems = VT.getVectorNumElements();
6144 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6145 bool Upper = IdxVal >= NumElems / 2;
6147 SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6150 SDValue ScaledN2 = N2;
6152 ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6153 DAG.getConstant(NumElems /
6154 (VT.getSizeInBits() / 128),
6155 N2.getValueType()));
6156 Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6159 // Insert the 128-bit vector
6160 // FIXME: Why UNDEF?
6161 return Insert128BitVector(N0, Op, N2, DAG, dl);
6164 if (Subtarget->hasSSE41())
6165 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6167 if (EltVT == MVT::i8)
6170 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6171 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6172 // as its second argument.
6173 if (N1.getValueType() != MVT::i32)
6174 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6175 if (N2.getValueType() != MVT::i32)
6176 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6177 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6183 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6184 LLVMContext *Context = DAG.getContext();
6185 DebugLoc dl = Op.getDebugLoc();
6186 EVT OpVT = Op.getValueType();
6188 // If this is a 256-bit vector result, first insert into a 128-bit
6189 // vector and then insert into the 256-bit vector.
6190 if (OpVT.getSizeInBits() > 128) {
6191 // Insert into a 128-bit vector.
6192 EVT VT128 = EVT::getVectorVT(*Context,
6193 OpVT.getVectorElementType(),
6194 OpVT.getVectorNumElements() / 2);
6196 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6198 // Insert the 128-bit vector.
6199 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6200 DAG.getConstant(0, MVT::i32),
6204 if (Op.getValueType() == MVT::v1i64 &&
6205 Op.getOperand(0).getValueType() == MVT::i64)
6206 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6208 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6209 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6210 "Expected an SSE type!");
6211 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6212 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6215 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
6216 // a simple subregister reference or explicit instructions to grab
6217 // upper bits of a vector.
6219 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6220 if (Subtarget->hasAVX()) {
6221 DebugLoc dl = Op.getNode()->getDebugLoc();
6222 SDValue Vec = Op.getNode()->getOperand(0);
6223 SDValue Idx = Op.getNode()->getOperand(1);
6225 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6226 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6227 return Extract128BitVector(Vec, Idx, DAG, dl);
6233 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
6234 // simple superregister reference or explicit instructions to insert
6235 // the upper bits of a vector.
6237 X86TargetLowering::LowerINSERT_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 SubVec = Op.getNode()->getOperand(1);
6242 SDValue Idx = Op.getNode()->getOperand(2);
6244 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6245 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6246 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6252 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6253 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6254 // one of the above mentioned nodes. It has to be wrapped because otherwise
6255 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6256 // be used to form addressing mode. These wrapped nodes will be selected
6259 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6260 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6262 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6264 unsigned char OpFlag = 0;
6265 unsigned WrapperKind = X86ISD::Wrapper;
6266 CodeModel::Model M = getTargetMachine().getCodeModel();
6268 if (Subtarget->isPICStyleRIPRel() &&
6269 (M == CodeModel::Small || M == CodeModel::Kernel))
6270 WrapperKind = X86ISD::WrapperRIP;
6271 else if (Subtarget->isPICStyleGOT())
6272 OpFlag = X86II::MO_GOTOFF;
6273 else if (Subtarget->isPICStyleStubPIC())
6274 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6276 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6278 CP->getOffset(), OpFlag);
6279 DebugLoc DL = CP->getDebugLoc();
6280 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6281 // With PIC, the address is actually $g + Offset.
6283 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6284 DAG.getNode(X86ISD::GlobalBaseReg,
6285 DebugLoc(), getPointerTy()),
6292 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6293 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6295 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6297 unsigned char OpFlag = 0;
6298 unsigned WrapperKind = X86ISD::Wrapper;
6299 CodeModel::Model M = getTargetMachine().getCodeModel();
6301 if (Subtarget->isPICStyleRIPRel() &&
6302 (M == CodeModel::Small || M == CodeModel::Kernel))
6303 WrapperKind = X86ISD::WrapperRIP;
6304 else if (Subtarget->isPICStyleGOT())
6305 OpFlag = X86II::MO_GOTOFF;
6306 else if (Subtarget->isPICStyleStubPIC())
6307 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6309 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6311 DebugLoc DL = JT->getDebugLoc();
6312 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6314 // With PIC, the address is actually $g + Offset.
6316 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6317 DAG.getNode(X86ISD::GlobalBaseReg,
6318 DebugLoc(), getPointerTy()),
6325 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6326 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6328 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6330 unsigned char OpFlag = 0;
6331 unsigned WrapperKind = X86ISD::Wrapper;
6332 CodeModel::Model M = getTargetMachine().getCodeModel();
6334 if (Subtarget->isPICStyleRIPRel() &&
6335 (M == CodeModel::Small || M == CodeModel::Kernel))
6336 WrapperKind = X86ISD::WrapperRIP;
6337 else if (Subtarget->isPICStyleGOT())
6338 OpFlag = X86II::MO_GOTOFF;
6339 else if (Subtarget->isPICStyleStubPIC())
6340 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6342 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6344 DebugLoc DL = Op.getDebugLoc();
6345 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6348 // With PIC, the address is actually $g + Offset.
6349 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6350 !Subtarget->is64Bit()) {
6351 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6352 DAG.getNode(X86ISD::GlobalBaseReg,
6353 DebugLoc(), getPointerTy()),
6361 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6362 // Create the TargetBlockAddressAddress node.
6363 unsigned char OpFlags =
6364 Subtarget->ClassifyBlockAddressReference();
6365 CodeModel::Model M = getTargetMachine().getCodeModel();
6366 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6367 DebugLoc dl = Op.getDebugLoc();
6368 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6369 /*isTarget=*/true, OpFlags);
6371 if (Subtarget->isPICStyleRIPRel() &&
6372 (M == CodeModel::Small || M == CodeModel::Kernel))
6373 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6375 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6377 // With PIC, the address is actually $g + Offset.
6378 if (isGlobalRelativeToPICBase(OpFlags)) {
6379 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6380 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6388 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6390 SelectionDAG &DAG) const {
6391 // Create the TargetGlobalAddress node, folding in the constant
6392 // offset if it is legal.
6393 unsigned char OpFlags =
6394 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6395 CodeModel::Model M = getTargetMachine().getCodeModel();
6397 if (OpFlags == X86II::MO_NO_FLAG &&
6398 X86::isOffsetSuitableForCodeModel(Offset, M)) {
6399 // A direct static reference to a global.
6400 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6403 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6406 if (Subtarget->isPICStyleRIPRel() &&
6407 (M == CodeModel::Small || M == CodeModel::Kernel))
6408 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6410 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6412 // With PIC, the address is actually $g + Offset.
6413 if (isGlobalRelativeToPICBase(OpFlags)) {
6414 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6415 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6419 // For globals that require a load from a stub to get the address, emit the
6421 if (isGlobalStubReference(OpFlags))
6422 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6423 MachinePointerInfo::getGOT(), false, false, 0);
6425 // If there was a non-zero offset that we didn't fold, create an explicit
6428 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6429 DAG.getConstant(Offset, getPointerTy()));
6435 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6436 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6437 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6438 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6442 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6443 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6444 unsigned char OperandFlags) {
6445 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6446 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6447 DebugLoc dl = GA->getDebugLoc();
6448 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6449 GA->getValueType(0),
6453 SDValue Ops[] = { Chain, TGA, *InFlag };
6454 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6456 SDValue Ops[] = { Chain, TGA };
6457 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6460 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6461 MFI->setAdjustsStack(true);
6463 SDValue Flag = Chain.getValue(1);
6464 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6467 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6469 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6472 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6473 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6474 DAG.getNode(X86ISD::GlobalBaseReg,
6475 DebugLoc(), PtrVT), InFlag);
6476 InFlag = Chain.getValue(1);
6478 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6481 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6483 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6485 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6486 X86::RAX, X86II::MO_TLSGD);
6489 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6490 // "local exec" model.
6491 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6492 const EVT PtrVT, TLSModel::Model model,
6494 DebugLoc dl = GA->getDebugLoc();
6496 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6497 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6498 is64Bit ? 257 : 256));
6500 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6501 DAG.getIntPtrConstant(0),
6502 MachinePointerInfo(Ptr), false, false, 0);
6504 unsigned char OperandFlags = 0;
6505 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6507 unsigned WrapperKind = X86ISD::Wrapper;
6508 if (model == TLSModel::LocalExec) {
6509 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6510 } else if (is64Bit) {
6511 assert(model == TLSModel::InitialExec);
6512 OperandFlags = X86II::MO_GOTTPOFF;
6513 WrapperKind = X86ISD::WrapperRIP;
6515 assert(model == TLSModel::InitialExec);
6516 OperandFlags = X86II::MO_INDNTPOFF;
6519 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6521 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6522 GA->getValueType(0),
6523 GA->getOffset(), OperandFlags);
6524 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6526 if (model == TLSModel::InitialExec)
6527 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6528 MachinePointerInfo::getGOT(), false, false, 0);
6530 // The address of the thread local variable is the add of the thread
6531 // pointer with the offset of the variable.
6532 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6536 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6538 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6539 const GlobalValue *GV = GA->getGlobal();
6541 if (Subtarget->isTargetELF()) {
6542 // TODO: implement the "local dynamic" model
6543 // TODO: implement the "initial exec"model for pic executables
6545 // If GV is an alias then use the aliasee for determining
6546 // thread-localness.
6547 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6548 GV = GA->resolveAliasedGlobal(false);
6550 TLSModel::Model model
6551 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6554 case TLSModel::GeneralDynamic:
6555 case TLSModel::LocalDynamic: // not implemented
6556 if (Subtarget->is64Bit())
6557 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6558 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6560 case TLSModel::InitialExec:
6561 case TLSModel::LocalExec:
6562 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6563 Subtarget->is64Bit());
6565 } else if (Subtarget->isTargetDarwin()) {
6566 // Darwin only has one model of TLS. Lower to that.
6567 unsigned char OpFlag = 0;
6568 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6569 X86ISD::WrapperRIP : X86ISD::Wrapper;
6571 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6573 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6574 !Subtarget->is64Bit();
6576 OpFlag = X86II::MO_TLVP_PIC_BASE;
6578 OpFlag = X86II::MO_TLVP;
6579 DebugLoc DL = Op.getDebugLoc();
6580 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6581 GA->getValueType(0),
6582 GA->getOffset(), OpFlag);
6583 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6585 // With PIC32, the address is actually $g + Offset.
6587 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6588 DAG.getNode(X86ISD::GlobalBaseReg,
6589 DebugLoc(), getPointerTy()),
6592 // Lowering the machine isd will make sure everything is in the right
6594 SDValue Chain = DAG.getEntryNode();
6595 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6596 SDValue Args[] = { Chain, Offset };
6597 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6599 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6600 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6601 MFI->setAdjustsStack(true);
6603 // And our return value (tls address) is in the standard call return value
6605 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6606 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6610 "TLS not implemented for this target.");
6612 llvm_unreachable("Unreachable");
6617 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6618 /// take a 2 x i32 value to shift plus a shift amount.
6619 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6620 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6621 EVT VT = Op.getValueType();
6622 unsigned VTBits = VT.getSizeInBits();
6623 DebugLoc dl = Op.getDebugLoc();
6624 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6625 SDValue ShOpLo = Op.getOperand(0);
6626 SDValue ShOpHi = Op.getOperand(1);
6627 SDValue ShAmt = Op.getOperand(2);
6628 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6629 DAG.getConstant(VTBits - 1, MVT::i8))
6630 : DAG.getConstant(0, VT);
6633 if (Op.getOpcode() == ISD::SHL_PARTS) {
6634 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6635 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6637 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6638 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6641 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6642 DAG.getConstant(VTBits, MVT::i8));
6643 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6644 AndNode, DAG.getConstant(0, MVT::i8));
6647 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6648 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6649 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6651 if (Op.getOpcode() == ISD::SHL_PARTS) {
6652 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6653 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6655 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6656 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6659 SDValue Ops[2] = { Lo, Hi };
6660 return DAG.getMergeValues(Ops, 2, dl);
6663 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6664 SelectionDAG &DAG) const {
6665 EVT SrcVT = Op.getOperand(0).getValueType();
6667 if (SrcVT.isVector())
6670 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6671 "Unknown SINT_TO_FP to lower!");
6673 // These are really Legal; return the operand so the caller accepts it as
6675 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6677 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6678 Subtarget->is64Bit()) {
6682 DebugLoc dl = Op.getDebugLoc();
6683 unsigned Size = SrcVT.getSizeInBits()/8;
6684 MachineFunction &MF = DAG.getMachineFunction();
6685 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6686 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6687 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6689 MachinePointerInfo::getFixedStack(SSFI),
6691 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6694 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6696 SelectionDAG &DAG) const {
6698 DebugLoc DL = Op.getDebugLoc();
6700 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6702 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6704 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6706 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6708 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6709 MachineMemOperand *MMO =
6710 DAG.getMachineFunction()
6711 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6712 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6714 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6715 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6717 Tys, Ops, array_lengthof(Ops),
6721 Chain = Result.getValue(1);
6722 SDValue InFlag = Result.getValue(2);
6724 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6725 // shouldn't be necessary except that RFP cannot be live across
6726 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6727 MachineFunction &MF = DAG.getMachineFunction();
6728 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6729 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6730 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6731 Tys = DAG.getVTList(MVT::Other);
6733 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6735 MachineMemOperand *MMO =
6736 DAG.getMachineFunction()
6737 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6738 MachineMemOperand::MOStore, SSFISize, SSFISize);
6740 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6741 Ops, array_lengthof(Ops),
6742 Op.getValueType(), MMO);
6743 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6744 MachinePointerInfo::getFixedStack(SSFI),
6751 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6752 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6753 SelectionDAG &DAG) const {
6754 // This algorithm is not obvious. Here it is in C code, more or less:
6756 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6757 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6758 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6760 // Copy ints to xmm registers.
6761 __m128i xh = _mm_cvtsi32_si128( hi );
6762 __m128i xl = _mm_cvtsi32_si128( lo );
6764 // Combine into low half of a single xmm register.
6765 __m128i x = _mm_unpacklo_epi32( xh, xl );
6769 // Merge in appropriate exponents to give the integer bits the right
6771 x = _mm_unpacklo_epi32( x, exp );
6773 // Subtract away the biases to deal with the IEEE-754 double precision
6775 d = _mm_sub_pd( (__m128d) x, bias );
6777 // All conversions up to here are exact. The correctly rounded result is
6778 // calculated using the current rounding mode using the following
6780 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6781 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6782 // store doesn't really need to be here (except
6783 // maybe to zero the other double)
6788 DebugLoc dl = Op.getDebugLoc();
6789 LLVMContext *Context = DAG.getContext();
6791 // Build some magic constants.
6792 std::vector<Constant*> CV0;
6793 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6794 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6795 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6796 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6797 Constant *C0 = ConstantVector::get(CV0);
6798 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6800 std::vector<Constant*> CV1;
6802 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6804 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6805 Constant *C1 = ConstantVector::get(CV1);
6806 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6808 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6809 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6811 DAG.getIntPtrConstant(1)));
6812 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6813 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6815 DAG.getIntPtrConstant(0)));
6816 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6817 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6818 MachinePointerInfo::getConstantPool(),
6820 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6821 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6822 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6823 MachinePointerInfo::getConstantPool(),
6825 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6827 // Add the halves; easiest way is to swap them into another reg first.
6828 int ShufMask[2] = { 1, -1 };
6829 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6830 DAG.getUNDEF(MVT::v2f64), ShufMask);
6831 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6832 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6833 DAG.getIntPtrConstant(0));
6836 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6837 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6838 SelectionDAG &DAG) const {
6839 DebugLoc dl = Op.getDebugLoc();
6840 // FP constant to bias correct the final result.
6841 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6844 // Load the 32-bit value into an XMM register.
6845 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6846 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6848 DAG.getIntPtrConstant(0)));
6850 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6851 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6852 DAG.getIntPtrConstant(0));
6854 // Or the load with the bias.
6855 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6856 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6857 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6859 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6860 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6861 MVT::v2f64, Bias)));
6862 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6863 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6864 DAG.getIntPtrConstant(0));
6866 // Subtract the bias.
6867 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6869 // Handle final rounding.
6870 EVT DestVT = Op.getValueType();
6872 if (DestVT.bitsLT(MVT::f64)) {
6873 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6874 DAG.getIntPtrConstant(0));
6875 } else if (DestVT.bitsGT(MVT::f64)) {
6876 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6879 // Handle final rounding.
6883 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6884 SelectionDAG &DAG) const {
6885 SDValue N0 = Op.getOperand(0);
6886 DebugLoc dl = Op.getDebugLoc();
6888 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6889 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6890 // the optimization here.
6891 if (DAG.SignBitIsZero(N0))
6892 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6894 EVT SrcVT = N0.getValueType();
6895 EVT DstVT = Op.getValueType();
6896 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6897 return LowerUINT_TO_FP_i64(Op, DAG);
6898 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6899 return LowerUINT_TO_FP_i32(Op, DAG);
6901 // Make a 64-bit buffer, and use it to build an FILD.
6902 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6903 if (SrcVT == MVT::i32) {
6904 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6905 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6906 getPointerTy(), StackSlot, WordOff);
6907 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6908 StackSlot, MachinePointerInfo(),
6910 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6911 OffsetSlot, MachinePointerInfo(),
6913 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6917 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6918 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6919 StackSlot, MachinePointerInfo(),
6921 // For i64 source, we need to add the appropriate power of 2 if the input
6922 // was negative. This is the same as the optimization in
6923 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6924 // we must be careful to do the computation in x87 extended precision, not
6925 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6926 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6927 MachineMemOperand *MMO =
6928 DAG.getMachineFunction()
6929 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6930 MachineMemOperand::MOLoad, 8, 8);
6932 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6933 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6934 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6937 APInt FF(32, 0x5F800000ULL);
6939 // Check whether the sign bit is set.
6940 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6941 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6944 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6945 SDValue FudgePtr = DAG.getConstantPool(
6946 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6949 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6950 SDValue Zero = DAG.getIntPtrConstant(0);
6951 SDValue Four = DAG.getIntPtrConstant(4);
6952 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6954 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6956 // Load the value out, extending it from f32 to f80.
6957 // FIXME: Avoid the extend by constructing the right constant pool?
6958 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
6959 FudgePtr, MachinePointerInfo::getConstantPool(),
6960 MVT::f32, false, false, 4);
6961 // Extend everything to 80 bits to force it to be done on x87.
6962 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6963 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6966 std::pair<SDValue,SDValue> X86TargetLowering::
6967 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6968 DebugLoc DL = Op.getDebugLoc();
6970 EVT DstTy = Op.getValueType();
6973 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6977 assert(DstTy.getSimpleVT() <= MVT::i64 &&
6978 DstTy.getSimpleVT() >= MVT::i16 &&
6979 "Unknown FP_TO_SINT to lower!");
6981 // These are really Legal.
6982 if (DstTy == MVT::i32 &&
6983 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6984 return std::make_pair(SDValue(), SDValue());
6985 if (Subtarget->is64Bit() &&
6986 DstTy == MVT::i64 &&
6987 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6988 return std::make_pair(SDValue(), SDValue());
6990 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6992 MachineFunction &MF = DAG.getMachineFunction();
6993 unsigned MemSize = DstTy.getSizeInBits()/8;
6994 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6995 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7000 switch (DstTy.getSimpleVT().SimpleTy) {
7001 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7002 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7003 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7004 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7007 SDValue Chain = DAG.getEntryNode();
7008 SDValue Value = Op.getOperand(0);
7009 EVT TheVT = Op.getOperand(0).getValueType();
7010 if (isScalarFPTypeInSSEReg(TheVT)) {
7011 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7012 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7013 MachinePointerInfo::getFixedStack(SSFI),
7015 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7017 Chain, StackSlot, DAG.getValueType(TheVT)
7020 MachineMemOperand *MMO =
7021 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7022 MachineMemOperand::MOLoad, MemSize, MemSize);
7023 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7025 Chain = Value.getValue(1);
7026 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7027 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7030 MachineMemOperand *MMO =
7031 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7032 MachineMemOperand::MOStore, MemSize, MemSize);
7034 // Build the FP_TO_INT*_IN_MEM
7035 SDValue Ops[] = { Chain, Value, StackSlot };
7036 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7037 Ops, 3, DstTy, MMO);
7039 return std::make_pair(FIST, StackSlot);
7042 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7043 SelectionDAG &DAG) const {
7044 if (Op.getValueType().isVector())
7047 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7048 SDValue FIST = Vals.first, StackSlot = Vals.second;
7049 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7050 if (FIST.getNode() == 0) return Op;
7053 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7054 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7057 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7058 SelectionDAG &DAG) const {
7059 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7060 SDValue FIST = Vals.first, StackSlot = Vals.second;
7061 assert(FIST.getNode() && "Unexpected failure");
7064 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7065 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7068 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7069 SelectionDAG &DAG) const {
7070 LLVMContext *Context = DAG.getContext();
7071 DebugLoc dl = Op.getDebugLoc();
7072 EVT VT = Op.getValueType();
7075 EltVT = VT.getVectorElementType();
7076 std::vector<Constant*> CV;
7077 if (EltVT == MVT::f64) {
7078 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7082 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7088 Constant *C = ConstantVector::get(CV);
7089 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7090 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7091 MachinePointerInfo::getConstantPool(),
7093 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7096 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7097 LLVMContext *Context = DAG.getContext();
7098 DebugLoc dl = Op.getDebugLoc();
7099 EVT VT = Op.getValueType();
7102 EltVT = VT.getVectorElementType();
7103 std::vector<Constant*> CV;
7104 if (EltVT == MVT::f64) {
7105 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7109 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7115 Constant *C = ConstantVector::get(CV);
7116 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7117 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7118 MachinePointerInfo::getConstantPool(),
7120 if (VT.isVector()) {
7121 return DAG.getNode(ISD::BITCAST, dl, VT,
7122 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7123 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7125 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7127 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7131 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7132 LLVMContext *Context = DAG.getContext();
7133 SDValue Op0 = Op.getOperand(0);
7134 SDValue Op1 = Op.getOperand(1);
7135 DebugLoc dl = Op.getDebugLoc();
7136 EVT VT = Op.getValueType();
7137 EVT SrcVT = Op1.getValueType();
7139 // If second operand is smaller, extend it first.
7140 if (SrcVT.bitsLT(VT)) {
7141 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7144 // And if it is bigger, shrink it first.
7145 if (SrcVT.bitsGT(VT)) {
7146 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7150 // At this point the operands and the result should have the same
7151 // type, and that won't be f80 since that is not custom lowered.
7153 // First get the sign bit of second operand.
7154 std::vector<Constant*> CV;
7155 if (SrcVT == MVT::f64) {
7156 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7157 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7159 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7160 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7161 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7162 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7164 Constant *C = ConstantVector::get(CV);
7165 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7166 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7167 MachinePointerInfo::getConstantPool(),
7169 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7171 // Shift sign bit right or left if the two operands have different types.
7172 if (SrcVT.bitsGT(VT)) {
7173 // Op0 is MVT::f32, Op1 is MVT::f64.
7174 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7175 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7176 DAG.getConstant(32, MVT::i32));
7177 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7178 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7179 DAG.getIntPtrConstant(0));
7182 // Clear first operand sign bit.
7184 if (VT == MVT::f64) {
7185 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7186 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7188 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7189 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7190 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7191 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7193 C = ConstantVector::get(CV);
7194 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7195 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7196 MachinePointerInfo::getConstantPool(),
7198 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7200 // Or the value with the sign bit.
7201 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7204 /// Emit nodes that will be selected as "test Op0,Op0", or something
7206 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7207 SelectionDAG &DAG) const {
7208 DebugLoc dl = Op.getDebugLoc();
7210 // CF and OF aren't always set the way we want. Determine which
7211 // of these we need.
7212 bool NeedCF = false;
7213 bool NeedOF = false;
7216 case X86::COND_A: case X86::COND_AE:
7217 case X86::COND_B: case X86::COND_BE:
7220 case X86::COND_G: case X86::COND_GE:
7221 case X86::COND_L: case X86::COND_LE:
7222 case X86::COND_O: case X86::COND_NO:
7227 // See if we can use the EFLAGS value from the operand instead of
7228 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7229 // we prove that the arithmetic won't overflow, we can't use OF or CF.
7230 if (Op.getResNo() != 0 || NeedOF || NeedCF)
7231 // Emit a CMP with 0, which is the TEST pattern.
7232 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7233 DAG.getConstant(0, Op.getValueType()));
7235 unsigned Opcode = 0;
7236 unsigned NumOperands = 0;
7237 switch (Op.getNode()->getOpcode()) {
7239 // Due to an isel shortcoming, be conservative if this add is likely to be
7240 // selected as part of a load-modify-store instruction. When the root node
7241 // in a match is a store, isel doesn't know how to remap non-chain non-flag
7242 // uses of other nodes in the match, such as the ADD in this case. This
7243 // leads to the ADD being left around and reselected, with the result being
7244 // two adds in the output. Alas, even if none our users are stores, that
7245 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
7246 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
7247 // climbing the DAG back to the root, and it doesn't seem to be worth the
7249 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7250 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7251 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7254 if (ConstantSDNode *C =
7255 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7256 // An add of one will be selected as an INC.
7257 if (C->getAPIntValue() == 1) {
7258 Opcode = X86ISD::INC;
7263 // An add of negative one (subtract of one) will be selected as a DEC.
7264 if (C->getAPIntValue().isAllOnesValue()) {
7265 Opcode = X86ISD::DEC;
7271 // Otherwise use a regular EFLAGS-setting add.
7272 Opcode = X86ISD::ADD;
7276 // If the primary and result isn't used, don't bother using X86ISD::AND,
7277 // because a TEST instruction will be better.
7278 bool NonFlagUse = false;
7279 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7280 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7282 unsigned UOpNo = UI.getOperandNo();
7283 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7284 // Look pass truncate.
7285 UOpNo = User->use_begin().getOperandNo();
7286 User = *User->use_begin();
7289 if (User->getOpcode() != ISD::BRCOND &&
7290 User->getOpcode() != ISD::SETCC &&
7291 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7304 // Due to the ISEL shortcoming noted above, be conservative if this op is
7305 // likely to be selected as part of a load-modify-store instruction.
7306 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7307 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7308 if (UI->getOpcode() == ISD::STORE)
7311 // Otherwise use a regular EFLAGS-setting instruction.
7312 switch (Op.getNode()->getOpcode()) {
7313 default: llvm_unreachable("unexpected operator!");
7314 case ISD::SUB: Opcode = X86ISD::SUB; break;
7315 case ISD::OR: Opcode = X86ISD::OR; break;
7316 case ISD::XOR: Opcode = X86ISD::XOR; break;
7317 case ISD::AND: Opcode = X86ISD::AND; break;
7329 return SDValue(Op.getNode(), 1);
7336 // Emit a CMP with 0, which is the TEST pattern.
7337 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7338 DAG.getConstant(0, Op.getValueType()));
7340 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7341 SmallVector<SDValue, 4> Ops;
7342 for (unsigned i = 0; i != NumOperands; ++i)
7343 Ops.push_back(Op.getOperand(i));
7345 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7346 DAG.ReplaceAllUsesWith(Op, New);
7347 return SDValue(New.getNode(), 1);
7350 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7352 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7353 SelectionDAG &DAG) const {
7354 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7355 if (C->getAPIntValue() == 0)
7356 return EmitTest(Op0, X86CC, DAG);
7358 DebugLoc dl = Op0.getDebugLoc();
7359 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7362 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7363 /// if it's possible.
7364 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7365 DebugLoc dl, SelectionDAG &DAG) const {
7366 SDValue Op0 = And.getOperand(0);
7367 SDValue Op1 = And.getOperand(1);
7368 if (Op0.getOpcode() == ISD::TRUNCATE)
7369 Op0 = Op0.getOperand(0);
7370 if (Op1.getOpcode() == ISD::TRUNCATE)
7371 Op1 = Op1.getOperand(0);
7374 if (Op1.getOpcode() == ISD::SHL)
7375 std::swap(Op0, Op1);
7376 if (Op0.getOpcode() == ISD::SHL) {
7377 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7378 if (And00C->getZExtValue() == 1) {
7379 // If we looked past a truncate, check that it's only truncating away
7381 unsigned BitWidth = Op0.getValueSizeInBits();
7382 unsigned AndBitWidth = And.getValueSizeInBits();
7383 if (BitWidth > AndBitWidth) {
7384 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7385 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7386 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7390 RHS = Op0.getOperand(1);
7392 } else if (Op1.getOpcode() == ISD::Constant) {
7393 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7394 SDValue AndLHS = Op0;
7395 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7396 LHS = AndLHS.getOperand(0);
7397 RHS = AndLHS.getOperand(1);
7401 if (LHS.getNode()) {
7402 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
7403 // instruction. Since the shift amount is in-range-or-undefined, we know
7404 // that doing a bittest on the i32 value is ok. We extend to i32 because
7405 // the encoding for the i16 version is larger than the i32 version.
7406 // Also promote i16 to i32 for performance / code size reason.
7407 if (LHS.getValueType() == MVT::i8 ||
7408 LHS.getValueType() == MVT::i16)
7409 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7411 // If the operand types disagree, extend the shift amount to match. Since
7412 // BT ignores high bits (like shifts) we can use anyextend.
7413 if (LHS.getValueType() != RHS.getValueType())
7414 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7416 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7417 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7418 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7419 DAG.getConstant(Cond, MVT::i8), BT);
7425 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7426 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7427 SDValue Op0 = Op.getOperand(0);
7428 SDValue Op1 = Op.getOperand(1);
7429 DebugLoc dl = Op.getDebugLoc();
7430 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7432 // Optimize to BT if possible.
7433 // Lower (X & (1 << N)) == 0 to BT(X, N).
7434 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7435 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7436 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7437 Op1.getOpcode() == ISD::Constant &&
7438 cast<ConstantSDNode>(Op1)->isNullValue() &&
7439 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7440 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7441 if (NewSetCC.getNode())
7445 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
7447 if (Op1.getOpcode() == ISD::Constant &&
7448 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7449 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7450 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7452 // If the input is a setcc, then reuse the input setcc or use a new one with
7453 // the inverted condition.
7454 if (Op0.getOpcode() == X86ISD::SETCC) {
7455 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7456 bool Invert = (CC == ISD::SETNE) ^
7457 cast<ConstantSDNode>(Op1)->isNullValue();
7458 if (!Invert) return Op0;
7460 CCode = X86::GetOppositeBranchCondition(CCode);
7461 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7462 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7466 bool isFP = Op1.getValueType().isFloatingPoint();
7467 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7468 if (X86CC == X86::COND_INVALID)
7471 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7472 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7473 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7476 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7478 SDValue Op0 = Op.getOperand(0);
7479 SDValue Op1 = Op.getOperand(1);
7480 SDValue CC = Op.getOperand(2);
7481 EVT VT = Op.getValueType();
7482 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7483 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7484 DebugLoc dl = Op.getDebugLoc();
7488 EVT VT0 = Op0.getValueType();
7489 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7490 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7493 switch (SetCCOpcode) {
7496 case ISD::SETEQ: SSECC = 0; break;
7498 case ISD::SETGT: Swap = true; // Fallthrough
7500 case ISD::SETOLT: SSECC = 1; break;
7502 case ISD::SETGE: Swap = true; // Fallthrough
7504 case ISD::SETOLE: SSECC = 2; break;
7505 case ISD::SETUO: SSECC = 3; break;
7507 case ISD::SETNE: SSECC = 4; break;
7508 case ISD::SETULE: Swap = true;
7509 case ISD::SETUGE: SSECC = 5; break;
7510 case ISD::SETULT: Swap = true;
7511 case ISD::SETUGT: SSECC = 6; break;
7512 case ISD::SETO: SSECC = 7; break;
7515 std::swap(Op0, Op1);
7517 // In the two special cases we can't handle, emit two comparisons.
7519 if (SetCCOpcode == ISD::SETUEQ) {
7521 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7522 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7523 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7525 else if (SetCCOpcode == ISD::SETONE) {
7527 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7528 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7529 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7531 llvm_unreachable("Illegal FP comparison");
7533 // Handle all other FP comparisons here.
7534 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7537 // We are handling one of the integer comparisons here. Since SSE only has
7538 // GT and EQ comparisons for integer, swapping operands and multiple
7539 // operations may be required for some comparisons.
7540 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7541 bool Swap = false, Invert = false, FlipSigns = false;
7543 switch (VT.getSimpleVT().SimpleTy) {
7545 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7546 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7547 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7548 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7551 switch (SetCCOpcode) {
7553 case ISD::SETNE: Invert = true;
7554 case ISD::SETEQ: Opc = EQOpc; break;
7555 case ISD::SETLT: Swap = true;
7556 case ISD::SETGT: Opc = GTOpc; break;
7557 case ISD::SETGE: Swap = true;
7558 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7559 case ISD::SETULT: Swap = true;
7560 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7561 case ISD::SETUGE: Swap = true;
7562 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7565 std::swap(Op0, Op1);
7567 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7568 // bits of the inputs before performing those operations.
7570 EVT EltVT = VT.getVectorElementType();
7571 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7573 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7574 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7576 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7577 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7580 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7582 // If the logical-not of the result is required, perform that now.
7584 Result = DAG.getNOT(dl, Result, VT);
7589 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7590 static bool isX86LogicalCmp(SDValue Op) {
7591 unsigned Opc = Op.getNode()->getOpcode();
7592 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7594 if (Op.getResNo() == 1 &&
7595 (Opc == X86ISD::ADD ||
7596 Opc == X86ISD::SUB ||
7597 Opc == X86ISD::ADC ||
7598 Opc == X86ISD::SBB ||
7599 Opc == X86ISD::SMUL ||
7600 Opc == X86ISD::UMUL ||
7601 Opc == X86ISD::INC ||
7602 Opc == X86ISD::DEC ||
7603 Opc == X86ISD::OR ||
7604 Opc == X86ISD::XOR ||
7605 Opc == X86ISD::AND))
7608 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7614 static bool isZero(SDValue V) {
7615 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7616 return C && C->isNullValue();
7619 static bool isAllOnes(SDValue V) {
7620 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7621 return C && C->isAllOnesValue();
7624 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7625 bool addTest = true;
7626 SDValue Cond = Op.getOperand(0);
7627 SDValue Op1 = Op.getOperand(1);
7628 SDValue Op2 = Op.getOperand(2);
7629 DebugLoc DL = Op.getDebugLoc();
7632 if (Cond.getOpcode() == ISD::SETCC) {
7633 SDValue NewCond = LowerSETCC(Cond, DAG);
7634 if (NewCond.getNode())
7638 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7639 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7640 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7641 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7642 if (Cond.getOpcode() == X86ISD::SETCC &&
7643 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7644 isZero(Cond.getOperand(1).getOperand(1))) {
7645 SDValue Cmp = Cond.getOperand(1);
7647 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7649 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7650 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7651 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7653 SDValue CmpOp0 = Cmp.getOperand(0);
7654 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7655 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7657 SDValue Res = // Res = 0 or -1.
7658 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7659 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7661 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7662 Res = DAG.getNOT(DL, Res, Res.getValueType());
7664 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7665 if (N2C == 0 || !N2C->isNullValue())
7666 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7671 // Look past (and (setcc_carry (cmp ...)), 1).
7672 if (Cond.getOpcode() == ISD::AND &&
7673 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7674 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7675 if (C && C->getAPIntValue() == 1)
7676 Cond = Cond.getOperand(0);
7679 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7680 // setting operand in place of the X86ISD::SETCC.
7681 if (Cond.getOpcode() == X86ISD::SETCC ||
7682 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7683 CC = Cond.getOperand(0);
7685 SDValue Cmp = Cond.getOperand(1);
7686 unsigned Opc = Cmp.getOpcode();
7687 EVT VT = Op.getValueType();
7689 bool IllegalFPCMov = false;
7690 if (VT.isFloatingPoint() && !VT.isVector() &&
7691 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7692 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7694 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7695 Opc == X86ISD::BT) { // FIXME
7702 // Look pass the truncate.
7703 if (Cond.getOpcode() == ISD::TRUNCATE)
7704 Cond = Cond.getOperand(0);
7706 // We know the result of AND is compared against zero. Try to match
7708 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7709 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7710 if (NewSetCC.getNode()) {
7711 CC = NewSetCC.getOperand(0);
7712 Cond = NewSetCC.getOperand(1);
7719 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7720 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7723 // a < b ? -1 : 0 -> RES = ~setcc_carry
7724 // a < b ? 0 : -1 -> RES = setcc_carry
7725 // a >= b ? -1 : 0 -> RES = setcc_carry
7726 // a >= b ? 0 : -1 -> RES = ~setcc_carry
7727 if (Cond.getOpcode() == X86ISD::CMP) {
7728 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7730 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7731 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7732 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7733 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7734 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7735 return DAG.getNOT(DL, Res, Res.getValueType());
7740 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7741 // condition is true.
7742 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7743 SDValue Ops[] = { Op2, Op1, CC, Cond };
7744 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7747 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7748 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7749 // from the AND / OR.
7750 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7751 Opc = Op.getOpcode();
7752 if (Opc != ISD::OR && Opc != ISD::AND)
7754 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7755 Op.getOperand(0).hasOneUse() &&
7756 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7757 Op.getOperand(1).hasOneUse());
7760 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7761 // 1 and that the SETCC node has a single use.
7762 static bool isXor1OfSetCC(SDValue Op) {
7763 if (Op.getOpcode() != ISD::XOR)
7765 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7766 if (N1C && N1C->getAPIntValue() == 1) {
7767 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7768 Op.getOperand(0).hasOneUse();
7773 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7774 bool addTest = true;
7775 SDValue Chain = Op.getOperand(0);
7776 SDValue Cond = Op.getOperand(1);
7777 SDValue Dest = Op.getOperand(2);
7778 DebugLoc dl = Op.getDebugLoc();
7781 if (Cond.getOpcode() == ISD::SETCC) {
7782 SDValue NewCond = LowerSETCC(Cond, DAG);
7783 if (NewCond.getNode())
7787 // FIXME: LowerXALUO doesn't handle these!!
7788 else if (Cond.getOpcode() == X86ISD::ADD ||
7789 Cond.getOpcode() == X86ISD::SUB ||
7790 Cond.getOpcode() == X86ISD::SMUL ||
7791 Cond.getOpcode() == X86ISD::UMUL)
7792 Cond = LowerXALUO(Cond, DAG);
7795 // Look pass (and (setcc_carry (cmp ...)), 1).
7796 if (Cond.getOpcode() == ISD::AND &&
7797 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7798 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7799 if (C && C->getAPIntValue() == 1)
7800 Cond = Cond.getOperand(0);
7803 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7804 // setting operand in place of the X86ISD::SETCC.
7805 if (Cond.getOpcode() == X86ISD::SETCC ||
7806 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7807 CC = Cond.getOperand(0);
7809 SDValue Cmp = Cond.getOperand(1);
7810 unsigned Opc = Cmp.getOpcode();
7811 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7812 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7816 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7820 // These can only come from an arithmetic instruction with overflow,
7821 // e.g. SADDO, UADDO.
7822 Cond = Cond.getNode()->getOperand(1);
7829 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7830 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7831 if (CondOpc == ISD::OR) {
7832 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7833 // two branches instead of an explicit OR instruction with a
7835 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7836 isX86LogicalCmp(Cmp)) {
7837 CC = Cond.getOperand(0).getOperand(0);
7838 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7839 Chain, Dest, CC, Cmp);
7840 CC = Cond.getOperand(1).getOperand(0);
7844 } else { // ISD::AND
7845 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7846 // two branches instead of an explicit AND instruction with a
7847 // separate test. However, we only do this if this block doesn't
7848 // have a fall-through edge, because this requires an explicit
7849 // jmp when the condition is false.
7850 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7851 isX86LogicalCmp(Cmp) &&
7852 Op.getNode()->hasOneUse()) {
7853 X86::CondCode CCode =
7854 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7855 CCode = X86::GetOppositeBranchCondition(CCode);
7856 CC = DAG.getConstant(CCode, MVT::i8);
7857 SDNode *User = *Op.getNode()->use_begin();
7858 // Look for an unconditional branch following this conditional branch.
7859 // We need this because we need to reverse the successors in order
7860 // to implement FCMP_OEQ.
7861 if (User->getOpcode() == ISD::BR) {
7862 SDValue FalseBB = User->getOperand(1);
7864 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7865 assert(NewBR == User);
7869 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7870 Chain, Dest, CC, Cmp);
7871 X86::CondCode CCode =
7872 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7873 CCode = X86::GetOppositeBranchCondition(CCode);
7874 CC = DAG.getConstant(CCode, MVT::i8);
7880 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7881 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7882 // It should be transformed during dag combiner except when the condition
7883 // is set by a arithmetics with overflow node.
7884 X86::CondCode CCode =
7885 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7886 CCode = X86::GetOppositeBranchCondition(CCode);
7887 CC = DAG.getConstant(CCode, MVT::i8);
7888 Cond = Cond.getOperand(0).getOperand(1);
7894 // Look pass the truncate.
7895 if (Cond.getOpcode() == ISD::TRUNCATE)
7896 Cond = Cond.getOperand(0);
7898 // We know the result of AND is compared against zero. Try to match
7900 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7901 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7902 if (NewSetCC.getNode()) {
7903 CC = NewSetCC.getOperand(0);
7904 Cond = NewSetCC.getOperand(1);
7911 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7912 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7914 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7915 Chain, Dest, CC, Cond);
7919 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7920 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7921 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7922 // that the guard pages used by the OS virtual memory manager are allocated in
7923 // correct sequence.
7925 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7926 SelectionDAG &DAG) const {
7927 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7928 "This should be used only on Windows targets");
7929 assert(!Subtarget->isTargetEnvMacho());
7930 DebugLoc dl = Op.getDebugLoc();
7933 SDValue Chain = Op.getOperand(0);
7934 SDValue Size = Op.getOperand(1);
7935 // FIXME: Ensure alignment here
7939 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7940 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
7942 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
7943 Flag = Chain.getValue(1);
7945 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7947 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7948 Flag = Chain.getValue(1);
7950 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7952 SDValue Ops1[2] = { Chain.getValue(0), Chain };
7953 return DAG.getMergeValues(Ops1, 2, dl);
7956 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7957 MachineFunction &MF = DAG.getMachineFunction();
7958 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7960 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7961 DebugLoc DL = Op.getDebugLoc();
7963 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7964 // vastart just stores the address of the VarArgsFrameIndex slot into the
7965 // memory location argument.
7966 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7968 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7969 MachinePointerInfo(SV), false, false, 0);
7973 // gp_offset (0 - 6 * 8)
7974 // fp_offset (48 - 48 + 8 * 16)
7975 // overflow_arg_area (point to parameters coming in memory).
7977 SmallVector<SDValue, 8> MemOps;
7978 SDValue FIN = Op.getOperand(1);
7980 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7981 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7983 FIN, MachinePointerInfo(SV), false, false, 0);
7984 MemOps.push_back(Store);
7987 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7988 FIN, DAG.getIntPtrConstant(4));
7989 Store = DAG.getStore(Op.getOperand(0), DL,
7990 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7992 FIN, MachinePointerInfo(SV, 4), false, false, 0);
7993 MemOps.push_back(Store);
7995 // Store ptr to overflow_arg_area
7996 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7997 FIN, DAG.getIntPtrConstant(4));
7998 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8000 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8001 MachinePointerInfo(SV, 8),
8003 MemOps.push_back(Store);
8005 // Store ptr to reg_save_area.
8006 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8007 FIN, DAG.getIntPtrConstant(8));
8008 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8010 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8011 MachinePointerInfo(SV, 16), false, false, 0);
8012 MemOps.push_back(Store);
8013 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8014 &MemOps[0], MemOps.size());
8017 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8018 assert(Subtarget->is64Bit() &&
8019 "LowerVAARG only handles 64-bit va_arg!");
8020 assert((Subtarget->isTargetLinux() ||
8021 Subtarget->isTargetDarwin()) &&
8022 "Unhandled target in LowerVAARG");
8023 assert(Op.getNode()->getNumOperands() == 4);
8024 SDValue Chain = Op.getOperand(0);
8025 SDValue SrcPtr = Op.getOperand(1);
8026 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8027 unsigned Align = Op.getConstantOperandVal(3);
8028 DebugLoc dl = Op.getDebugLoc();
8030 EVT ArgVT = Op.getNode()->getValueType(0);
8031 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8032 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8035 // Decide which area this value should be read from.
8036 // TODO: Implement the AMD64 ABI in its entirety. This simple
8037 // selection mechanism works only for the basic types.
8038 if (ArgVT == MVT::f80) {
8039 llvm_unreachable("va_arg for f80 not yet implemented");
8040 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8041 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
8042 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8043 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
8045 llvm_unreachable("Unhandled argument type in LowerVAARG");
8049 // Sanity Check: Make sure using fp_offset makes sense.
8050 assert(!UseSoftFloat &&
8051 !(DAG.getMachineFunction()
8052 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8053 Subtarget->hasXMM());
8056 // Insert VAARG_64 node into the DAG
8057 // VAARG_64 returns two values: Variable Argument Address, Chain
8058 SmallVector<SDValue, 11> InstOps;
8059 InstOps.push_back(Chain);
8060 InstOps.push_back(SrcPtr);
8061 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8062 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8063 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8064 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8065 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8066 VTs, &InstOps[0], InstOps.size(),
8068 MachinePointerInfo(SV),
8073 Chain = VAARG.getValue(1);
8075 // Load the next argument and return it
8076 return DAG.getLoad(ArgVT, dl,
8079 MachinePointerInfo(),
8083 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8084 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8085 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8086 SDValue Chain = Op.getOperand(0);
8087 SDValue DstPtr = Op.getOperand(1);
8088 SDValue SrcPtr = Op.getOperand(2);
8089 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8090 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8091 DebugLoc DL = Op.getDebugLoc();
8093 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8094 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8096 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8100 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8101 DebugLoc dl = Op.getDebugLoc();
8102 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8104 default: return SDValue(); // Don't custom lower most intrinsics.
8105 // Comparison intrinsics.
8106 case Intrinsic::x86_sse_comieq_ss:
8107 case Intrinsic::x86_sse_comilt_ss:
8108 case Intrinsic::x86_sse_comile_ss:
8109 case Intrinsic::x86_sse_comigt_ss:
8110 case Intrinsic::x86_sse_comige_ss:
8111 case Intrinsic::x86_sse_comineq_ss:
8112 case Intrinsic::x86_sse_ucomieq_ss:
8113 case Intrinsic::x86_sse_ucomilt_ss:
8114 case Intrinsic::x86_sse_ucomile_ss:
8115 case Intrinsic::x86_sse_ucomigt_ss:
8116 case Intrinsic::x86_sse_ucomige_ss:
8117 case Intrinsic::x86_sse_ucomineq_ss:
8118 case Intrinsic::x86_sse2_comieq_sd:
8119 case Intrinsic::x86_sse2_comilt_sd:
8120 case Intrinsic::x86_sse2_comile_sd:
8121 case Intrinsic::x86_sse2_comigt_sd:
8122 case Intrinsic::x86_sse2_comige_sd:
8123 case Intrinsic::x86_sse2_comineq_sd:
8124 case Intrinsic::x86_sse2_ucomieq_sd:
8125 case Intrinsic::x86_sse2_ucomilt_sd:
8126 case Intrinsic::x86_sse2_ucomile_sd:
8127 case Intrinsic::x86_sse2_ucomigt_sd:
8128 case Intrinsic::x86_sse2_ucomige_sd:
8129 case Intrinsic::x86_sse2_ucomineq_sd: {
8131 ISD::CondCode CC = ISD::SETCC_INVALID;
8134 case Intrinsic::x86_sse_comieq_ss:
8135 case Intrinsic::x86_sse2_comieq_sd:
8139 case Intrinsic::x86_sse_comilt_ss:
8140 case Intrinsic::x86_sse2_comilt_sd:
8144 case Intrinsic::x86_sse_comile_ss:
8145 case Intrinsic::x86_sse2_comile_sd:
8149 case Intrinsic::x86_sse_comigt_ss:
8150 case Intrinsic::x86_sse2_comigt_sd:
8154 case Intrinsic::x86_sse_comige_ss:
8155 case Intrinsic::x86_sse2_comige_sd:
8159 case Intrinsic::x86_sse_comineq_ss:
8160 case Intrinsic::x86_sse2_comineq_sd:
8164 case Intrinsic::x86_sse_ucomieq_ss:
8165 case Intrinsic::x86_sse2_ucomieq_sd:
8166 Opc = X86ISD::UCOMI;
8169 case Intrinsic::x86_sse_ucomilt_ss:
8170 case Intrinsic::x86_sse2_ucomilt_sd:
8171 Opc = X86ISD::UCOMI;
8174 case Intrinsic::x86_sse_ucomile_ss:
8175 case Intrinsic::x86_sse2_ucomile_sd:
8176 Opc = X86ISD::UCOMI;
8179 case Intrinsic::x86_sse_ucomigt_ss:
8180 case Intrinsic::x86_sse2_ucomigt_sd:
8181 Opc = X86ISD::UCOMI;
8184 case Intrinsic::x86_sse_ucomige_ss:
8185 case Intrinsic::x86_sse2_ucomige_sd:
8186 Opc = X86ISD::UCOMI;
8189 case Intrinsic::x86_sse_ucomineq_ss:
8190 case Intrinsic::x86_sse2_ucomineq_sd:
8191 Opc = X86ISD::UCOMI;
8196 SDValue LHS = Op.getOperand(1);
8197 SDValue RHS = Op.getOperand(2);
8198 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8199 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8200 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8201 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8202 DAG.getConstant(X86CC, MVT::i8), Cond);
8203 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8205 // ptest and testp intrinsics. The intrinsic these come from are designed to
8206 // return an integer value, not just an instruction so lower it to the ptest
8207 // or testp pattern and a setcc for the result.
8208 case Intrinsic::x86_sse41_ptestz:
8209 case Intrinsic::x86_sse41_ptestc:
8210 case Intrinsic::x86_sse41_ptestnzc:
8211 case Intrinsic::x86_avx_ptestz_256:
8212 case Intrinsic::x86_avx_ptestc_256:
8213 case Intrinsic::x86_avx_ptestnzc_256:
8214 case Intrinsic::x86_avx_vtestz_ps:
8215 case Intrinsic::x86_avx_vtestc_ps:
8216 case Intrinsic::x86_avx_vtestnzc_ps:
8217 case Intrinsic::x86_avx_vtestz_pd:
8218 case Intrinsic::x86_avx_vtestc_pd:
8219 case Intrinsic::x86_avx_vtestnzc_pd:
8220 case Intrinsic::x86_avx_vtestz_ps_256:
8221 case Intrinsic::x86_avx_vtestc_ps_256:
8222 case Intrinsic::x86_avx_vtestnzc_ps_256:
8223 case Intrinsic::x86_avx_vtestz_pd_256:
8224 case Intrinsic::x86_avx_vtestc_pd_256:
8225 case Intrinsic::x86_avx_vtestnzc_pd_256: {
8226 bool IsTestPacked = false;
8229 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8230 case Intrinsic::x86_avx_vtestz_ps:
8231 case Intrinsic::x86_avx_vtestz_pd:
8232 case Intrinsic::x86_avx_vtestz_ps_256:
8233 case Intrinsic::x86_avx_vtestz_pd_256:
8234 IsTestPacked = true; // Fallthrough
8235 case Intrinsic::x86_sse41_ptestz:
8236 case Intrinsic::x86_avx_ptestz_256:
8238 X86CC = X86::COND_E;
8240 case Intrinsic::x86_avx_vtestc_ps:
8241 case Intrinsic::x86_avx_vtestc_pd:
8242 case Intrinsic::x86_avx_vtestc_ps_256:
8243 case Intrinsic::x86_avx_vtestc_pd_256:
8244 IsTestPacked = true; // Fallthrough
8245 case Intrinsic::x86_sse41_ptestc:
8246 case Intrinsic::x86_avx_ptestc_256:
8248 X86CC = X86::COND_B;
8250 case Intrinsic::x86_avx_vtestnzc_ps:
8251 case Intrinsic::x86_avx_vtestnzc_pd:
8252 case Intrinsic::x86_avx_vtestnzc_ps_256:
8253 case Intrinsic::x86_avx_vtestnzc_pd_256:
8254 IsTestPacked = true; // Fallthrough
8255 case Intrinsic::x86_sse41_ptestnzc:
8256 case Intrinsic::x86_avx_ptestnzc_256:
8258 X86CC = X86::COND_A;
8262 SDValue LHS = Op.getOperand(1);
8263 SDValue RHS = Op.getOperand(2);
8264 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8265 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8266 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8267 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8268 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8271 // Fix vector shift instructions where the last operand is a non-immediate
8273 case Intrinsic::x86_sse2_pslli_w:
8274 case Intrinsic::x86_sse2_pslli_d:
8275 case Intrinsic::x86_sse2_pslli_q:
8276 case Intrinsic::x86_sse2_psrli_w:
8277 case Intrinsic::x86_sse2_psrli_d:
8278 case Intrinsic::x86_sse2_psrli_q:
8279 case Intrinsic::x86_sse2_psrai_w:
8280 case Intrinsic::x86_sse2_psrai_d:
8281 case Intrinsic::x86_mmx_pslli_w:
8282 case Intrinsic::x86_mmx_pslli_d:
8283 case Intrinsic::x86_mmx_pslli_q:
8284 case Intrinsic::x86_mmx_psrli_w:
8285 case Intrinsic::x86_mmx_psrli_d:
8286 case Intrinsic::x86_mmx_psrli_q:
8287 case Intrinsic::x86_mmx_psrai_w:
8288 case Intrinsic::x86_mmx_psrai_d: {
8289 SDValue ShAmt = Op.getOperand(2);
8290 if (isa<ConstantSDNode>(ShAmt))
8293 unsigned NewIntNo = 0;
8294 EVT ShAmtVT = MVT::v4i32;
8296 case Intrinsic::x86_sse2_pslli_w:
8297 NewIntNo = Intrinsic::x86_sse2_psll_w;
8299 case Intrinsic::x86_sse2_pslli_d:
8300 NewIntNo = Intrinsic::x86_sse2_psll_d;
8302 case Intrinsic::x86_sse2_pslli_q:
8303 NewIntNo = Intrinsic::x86_sse2_psll_q;
8305 case Intrinsic::x86_sse2_psrli_w:
8306 NewIntNo = Intrinsic::x86_sse2_psrl_w;
8308 case Intrinsic::x86_sse2_psrli_d:
8309 NewIntNo = Intrinsic::x86_sse2_psrl_d;
8311 case Intrinsic::x86_sse2_psrli_q:
8312 NewIntNo = Intrinsic::x86_sse2_psrl_q;
8314 case Intrinsic::x86_sse2_psrai_w:
8315 NewIntNo = Intrinsic::x86_sse2_psra_w;
8317 case Intrinsic::x86_sse2_psrai_d:
8318 NewIntNo = Intrinsic::x86_sse2_psra_d;
8321 ShAmtVT = MVT::v2i32;
8323 case Intrinsic::x86_mmx_pslli_w:
8324 NewIntNo = Intrinsic::x86_mmx_psll_w;
8326 case Intrinsic::x86_mmx_pslli_d:
8327 NewIntNo = Intrinsic::x86_mmx_psll_d;
8329 case Intrinsic::x86_mmx_pslli_q:
8330 NewIntNo = Intrinsic::x86_mmx_psll_q;
8332 case Intrinsic::x86_mmx_psrli_w:
8333 NewIntNo = Intrinsic::x86_mmx_psrl_w;
8335 case Intrinsic::x86_mmx_psrli_d:
8336 NewIntNo = Intrinsic::x86_mmx_psrl_d;
8338 case Intrinsic::x86_mmx_psrli_q:
8339 NewIntNo = Intrinsic::x86_mmx_psrl_q;
8341 case Intrinsic::x86_mmx_psrai_w:
8342 NewIntNo = Intrinsic::x86_mmx_psra_w;
8344 case Intrinsic::x86_mmx_psrai_d:
8345 NewIntNo = Intrinsic::x86_mmx_psra_d;
8347 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8353 // The vector shift intrinsics with scalars uses 32b shift amounts but
8354 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8358 ShOps[1] = DAG.getConstant(0, MVT::i32);
8359 if (ShAmtVT == MVT::v4i32) {
8360 ShOps[2] = DAG.getUNDEF(MVT::i32);
8361 ShOps[3] = DAG.getUNDEF(MVT::i32);
8362 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8364 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8365 // FIXME this must be lowered to get rid of the invalid type.
8368 EVT VT = Op.getValueType();
8369 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8370 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8371 DAG.getConstant(NewIntNo, MVT::i32),
8372 Op.getOperand(1), ShAmt);
8377 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8378 SelectionDAG &DAG) const {
8379 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8380 MFI->setReturnAddressIsTaken(true);
8382 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8383 DebugLoc dl = Op.getDebugLoc();
8386 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8388 DAG.getConstant(TD->getPointerSize(),
8389 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8390 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8391 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8393 MachinePointerInfo(), false, false, 0);
8396 // Just load the return address.
8397 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8398 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8399 RetAddrFI, MachinePointerInfo(), false, false, 0);
8402 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8403 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8404 MFI->setFrameAddressIsTaken(true);
8406 EVT VT = Op.getValueType();
8407 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
8408 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8409 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8410 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8412 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8413 MachinePointerInfo(),
8418 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8419 SelectionDAG &DAG) const {
8420 return DAG.getIntPtrConstant(2*TD->getPointerSize());
8423 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8424 MachineFunction &MF = DAG.getMachineFunction();
8425 SDValue Chain = Op.getOperand(0);
8426 SDValue Offset = Op.getOperand(1);
8427 SDValue Handler = Op.getOperand(2);
8428 DebugLoc dl = Op.getDebugLoc();
8430 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8431 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8433 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8435 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8436 DAG.getIntPtrConstant(TD->getPointerSize()));
8437 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8438 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8440 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8441 MF.getRegInfo().addLiveOut(StoreAddrReg);
8443 return DAG.getNode(X86ISD::EH_RETURN, dl,
8445 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8448 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8449 SelectionDAG &DAG) const {
8450 SDValue Root = Op.getOperand(0);
8451 SDValue Trmp = Op.getOperand(1); // trampoline
8452 SDValue FPtr = Op.getOperand(2); // nested function
8453 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8454 DebugLoc dl = Op.getDebugLoc();
8456 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8458 if (Subtarget->is64Bit()) {
8459 SDValue OutChains[6];
8461 // Large code-model.
8462 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8463 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8465 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8466 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8468 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8470 // Load the pointer to the nested function into R11.
8471 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8472 SDValue Addr = Trmp;
8473 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8474 Addr, MachinePointerInfo(TrmpAddr),
8477 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8478 DAG.getConstant(2, MVT::i64));
8479 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8480 MachinePointerInfo(TrmpAddr, 2),
8483 // Load the 'nest' parameter value into R10.
8484 // R10 is specified in X86CallingConv.td
8485 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8486 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8487 DAG.getConstant(10, MVT::i64));
8488 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8489 Addr, MachinePointerInfo(TrmpAddr, 10),
8492 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8493 DAG.getConstant(12, MVT::i64));
8494 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8495 MachinePointerInfo(TrmpAddr, 12),
8498 // Jump to the nested function.
8499 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8500 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8501 DAG.getConstant(20, MVT::i64));
8502 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8503 Addr, MachinePointerInfo(TrmpAddr, 20),
8506 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8507 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8508 DAG.getConstant(22, MVT::i64));
8509 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8510 MachinePointerInfo(TrmpAddr, 22),
8514 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8515 return DAG.getMergeValues(Ops, 2, dl);
8517 const Function *Func =
8518 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8519 CallingConv::ID CC = Func->getCallingConv();
8524 llvm_unreachable("Unsupported calling convention");
8525 case CallingConv::C:
8526 case CallingConv::X86_StdCall: {
8527 // Pass 'nest' parameter in ECX.
8528 // Must be kept in sync with X86CallingConv.td
8531 // Check that ECX wasn't needed by an 'inreg' parameter.
8532 const FunctionType *FTy = Func->getFunctionType();
8533 const AttrListPtr &Attrs = Func->getAttributes();
8535 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8536 unsigned InRegCount = 0;
8539 for (FunctionType::param_iterator I = FTy->param_begin(),
8540 E = FTy->param_end(); I != E; ++I, ++Idx)
8541 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8542 // FIXME: should only count parameters that are lowered to integers.
8543 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8545 if (InRegCount > 2) {
8546 report_fatal_error("Nest register in use - reduce number of inreg"
8552 case CallingConv::X86_FastCall:
8553 case CallingConv::X86_ThisCall:
8554 case CallingConv::Fast:
8555 // Pass 'nest' parameter in EAX.
8556 // Must be kept in sync with X86CallingConv.td
8561 SDValue OutChains[4];
8564 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8565 DAG.getConstant(10, MVT::i32));
8566 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8568 // This is storing the opcode for MOV32ri.
8569 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8570 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8571 OutChains[0] = DAG.getStore(Root, dl,
8572 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8573 Trmp, MachinePointerInfo(TrmpAddr),
8576 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8577 DAG.getConstant(1, MVT::i32));
8578 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8579 MachinePointerInfo(TrmpAddr, 1),
8582 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8583 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8584 DAG.getConstant(5, MVT::i32));
8585 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8586 MachinePointerInfo(TrmpAddr, 5),
8589 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8590 DAG.getConstant(6, MVT::i32));
8591 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8592 MachinePointerInfo(TrmpAddr, 6),
8596 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8597 return DAG.getMergeValues(Ops, 2, dl);
8601 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8602 SelectionDAG &DAG) const {
8604 The rounding mode is in bits 11:10 of FPSR, and has the following
8611 FLT_ROUNDS, on the other hand, expects the following:
8618 To perform the conversion, we do:
8619 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8622 MachineFunction &MF = DAG.getMachineFunction();
8623 const TargetMachine &TM = MF.getTarget();
8624 const TargetFrameLowering &TFI = *TM.getFrameLowering();
8625 unsigned StackAlignment = TFI.getStackAlignment();
8626 EVT VT = Op.getValueType();
8627 DebugLoc DL = Op.getDebugLoc();
8629 // Save FP Control Word to stack slot
8630 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8631 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8634 MachineMemOperand *MMO =
8635 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8636 MachineMemOperand::MOStore, 2, 2);
8638 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8639 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8640 DAG.getVTList(MVT::Other),
8641 Ops, 2, MVT::i16, MMO);
8643 // Load FP Control Word from stack slot
8644 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8645 MachinePointerInfo(), false, false, 0);
8647 // Transform as necessary
8649 DAG.getNode(ISD::SRL, DL, MVT::i16,
8650 DAG.getNode(ISD::AND, DL, MVT::i16,
8651 CWD, DAG.getConstant(0x800, MVT::i16)),
8652 DAG.getConstant(11, MVT::i8));
8654 DAG.getNode(ISD::SRL, DL, MVT::i16,
8655 DAG.getNode(ISD::AND, DL, MVT::i16,
8656 CWD, DAG.getConstant(0x400, MVT::i16)),
8657 DAG.getConstant(9, MVT::i8));
8660 DAG.getNode(ISD::AND, DL, MVT::i16,
8661 DAG.getNode(ISD::ADD, DL, MVT::i16,
8662 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8663 DAG.getConstant(1, MVT::i16)),
8664 DAG.getConstant(3, MVT::i16));
8667 return DAG.getNode((VT.getSizeInBits() < 16 ?
8668 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8671 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8672 EVT VT = Op.getValueType();
8674 unsigned NumBits = VT.getSizeInBits();
8675 DebugLoc dl = Op.getDebugLoc();
8677 Op = Op.getOperand(0);
8678 if (VT == MVT::i8) {
8679 // Zero extend to i32 since there is not an i8 bsr.
8681 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8684 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8685 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8686 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8688 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8691 DAG.getConstant(NumBits+NumBits-1, OpVT),
8692 DAG.getConstant(X86::COND_E, MVT::i8),
8695 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8697 // Finally xor with NumBits-1.
8698 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8701 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8705 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8706 EVT VT = Op.getValueType();
8708 unsigned NumBits = VT.getSizeInBits();
8709 DebugLoc dl = Op.getDebugLoc();
8711 Op = Op.getOperand(0);
8712 if (VT == MVT::i8) {
8714 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8717 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8718 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8719 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8721 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8724 DAG.getConstant(NumBits, OpVT),
8725 DAG.getConstant(X86::COND_E, MVT::i8),
8728 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8731 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8735 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8736 EVT VT = Op.getValueType();
8737 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8738 DebugLoc dl = Op.getDebugLoc();
8740 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8741 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8742 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8743 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8744 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8746 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8747 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8748 // return AloBlo + AloBhi + AhiBlo;
8750 SDValue A = Op.getOperand(0);
8751 SDValue B = Op.getOperand(1);
8753 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8754 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8755 A, DAG.getConstant(32, MVT::i32));
8756 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8757 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8758 B, DAG.getConstant(32, MVT::i32));
8759 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8760 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8762 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8763 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8765 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8766 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8768 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8769 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8770 AloBhi, DAG.getConstant(32, MVT::i32));
8771 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8772 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8773 AhiBlo, DAG.getConstant(32, MVT::i32));
8774 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8775 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8779 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8781 EVT VT = Op.getValueType();
8782 DebugLoc dl = Op.getDebugLoc();
8783 SDValue R = Op.getOperand(0);
8784 SDValue Amt = Op.getOperand(1);
8786 LLVMContext *Context = DAG.getContext();
8789 if (!Subtarget->hasSSE2()) return SDValue();
8791 // Optimize shl/srl/sra with constant shift amount.
8792 if (isSplatVector(Amt.getNode())) {
8793 SDValue SclrAmt = Amt->getOperand(0);
8794 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8795 uint64_t ShiftAmt = C->getZExtValue();
8797 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8798 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8799 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8800 R, DAG.getConstant(ShiftAmt, MVT::i32));
8802 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
8803 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8804 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8805 R, DAG.getConstant(ShiftAmt, MVT::i32));
8807 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
8808 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8809 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8810 R, DAG.getConstant(ShiftAmt, MVT::i32));
8812 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
8813 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8814 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8815 R, DAG.getConstant(ShiftAmt, MVT::i32));
8817 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
8818 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8819 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8820 R, DAG.getConstant(ShiftAmt, MVT::i32));
8822 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
8823 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8824 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8825 R, DAG.getConstant(ShiftAmt, MVT::i32));
8827 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
8828 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8829 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8830 R, DAG.getConstant(ShiftAmt, MVT::i32));
8832 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
8833 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8834 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8835 R, DAG.getConstant(ShiftAmt, MVT::i32));
8839 // Lower SHL with variable shift amount.
8840 // Cannot lower SHL without SSE4.1 or later.
8841 if (!Subtarget->hasSSE41()) return SDValue();
8843 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
8844 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8845 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8846 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8848 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8850 std::vector<Constant*> CV(4, CI);
8851 Constant *C = ConstantVector::get(CV);
8852 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8853 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8854 MachinePointerInfo::getConstantPool(),
8857 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8858 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8859 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8860 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8862 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
8864 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8865 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8866 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8868 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8869 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8871 std::vector<Constant*> CVM1(16, CM1);
8872 std::vector<Constant*> CVM2(16, CM2);
8873 Constant *C = ConstantVector::get(CVM1);
8874 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8875 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8876 MachinePointerInfo::getConstantPool(),
8879 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8880 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8881 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8882 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8883 DAG.getConstant(4, MVT::i32));
8884 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8886 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8888 C = ConstantVector::get(CVM2);
8889 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8890 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8891 MachinePointerInfo::getConstantPool(),
8894 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8895 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8896 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8897 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8898 DAG.getConstant(2, MVT::i32));
8899 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8901 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8903 // return pblendv(r, r+r, a);
8904 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8905 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8911 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8912 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8913 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8914 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8915 // has only one use.
8916 SDNode *N = Op.getNode();
8917 SDValue LHS = N->getOperand(0);
8918 SDValue RHS = N->getOperand(1);
8919 unsigned BaseOp = 0;
8921 DebugLoc DL = Op.getDebugLoc();
8922 switch (Op.getOpcode()) {
8923 default: llvm_unreachable("Unknown ovf instruction!");
8925 // A subtract of one will be selected as a INC. Note that INC doesn't
8926 // set CF, so we can't do this for UADDO.
8927 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8929 BaseOp = X86ISD::INC;
8933 BaseOp = X86ISD::ADD;
8937 BaseOp = X86ISD::ADD;
8941 // A subtract of one will be selected as a DEC. Note that DEC doesn't
8942 // set CF, so we can't do this for USUBO.
8943 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8945 BaseOp = X86ISD::DEC;
8949 BaseOp = X86ISD::SUB;
8953 BaseOp = X86ISD::SUB;
8957 BaseOp = X86ISD::SMUL;
8960 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8961 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8963 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8966 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8967 DAG.getConstant(X86::COND_O, MVT::i32),
8968 SDValue(Sum.getNode(), 2));
8970 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8975 // Also sets EFLAGS.
8976 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8977 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8980 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8981 DAG.getConstant(Cond, MVT::i32),
8982 SDValue(Sum.getNode(), 1));
8984 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8988 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8989 DebugLoc dl = Op.getDebugLoc();
8991 if (!Subtarget->hasSSE2()) {
8992 SDValue Chain = Op.getOperand(0);
8993 SDValue Zero = DAG.getConstant(0,
8994 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8996 DAG.getRegister(X86::ESP, MVT::i32), // Base
8997 DAG.getTargetConstant(1, MVT::i8), // Scale
8998 DAG.getRegister(0, MVT::i32), // Index
8999 DAG.getTargetConstant(0, MVT::i32), // Disp
9000 DAG.getRegister(0, MVT::i32), // Segment.
9005 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9006 array_lengthof(Ops));
9007 return SDValue(Res, 0);
9010 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9012 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9014 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9015 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9016 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9017 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9019 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9020 if (!Op1 && !Op2 && !Op3 && Op4)
9021 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9023 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9024 if (Op1 && !Op2 && !Op3 && !Op4)
9025 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9027 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9029 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9032 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9033 EVT T = Op.getValueType();
9034 DebugLoc DL = Op.getDebugLoc();
9037 switch(T.getSimpleVT().SimpleTy) {
9039 assert(false && "Invalid value type!");
9040 case MVT::i8: Reg = X86::AL; size = 1; break;
9041 case MVT::i16: Reg = X86::AX; size = 2; break;
9042 case MVT::i32: Reg = X86::EAX; size = 4; break;
9044 assert(Subtarget->is64Bit() && "Node not type legal!");
9045 Reg = X86::RAX; size = 8;
9048 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9049 Op.getOperand(2), SDValue());
9050 SDValue Ops[] = { cpIn.getValue(0),
9053 DAG.getTargetConstant(size, MVT::i8),
9055 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9056 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9057 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9060 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9064 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9065 SelectionDAG &DAG) const {
9066 assert(Subtarget->is64Bit() && "Result not type legalized?");
9067 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9068 SDValue TheChain = Op.getOperand(0);
9069 DebugLoc dl = Op.getDebugLoc();
9070 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9071 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9072 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9074 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9075 DAG.getConstant(32, MVT::i8));
9077 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9080 return DAG.getMergeValues(Ops, 2, dl);
9083 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9084 SelectionDAG &DAG) const {
9085 EVT SrcVT = Op.getOperand(0).getValueType();
9086 EVT DstVT = Op.getValueType();
9087 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9088 Subtarget->hasMMX() && "Unexpected custom BITCAST");
9089 assert((DstVT == MVT::i64 ||
9090 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9091 "Unexpected custom BITCAST");
9092 // i64 <=> MMX conversions are Legal.
9093 if (SrcVT==MVT::i64 && DstVT.isVector())
9095 if (DstVT==MVT::i64 && SrcVT.isVector())
9097 // MMX <=> MMX conversions are Legal.
9098 if (SrcVT.isVector() && DstVT.isVector())
9100 // All other conversions need to be expanded.
9104 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9105 SDNode *Node = Op.getNode();
9106 DebugLoc dl = Node->getDebugLoc();
9107 EVT T = Node->getValueType(0);
9108 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9109 DAG.getConstant(0, T), Node->getOperand(2));
9110 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9111 cast<AtomicSDNode>(Node)->getMemoryVT(),
9112 Node->getOperand(0),
9113 Node->getOperand(1), negOp,
9114 cast<AtomicSDNode>(Node)->getSrcValue(),
9115 cast<AtomicSDNode>(Node)->getAlignment());
9118 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9119 EVT VT = Op.getNode()->getValueType(0);
9121 // Let legalize expand this if it isn't a legal type yet.
9122 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9125 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9128 bool ExtraOp = false;
9129 switch (Op.getOpcode()) {
9130 default: assert(0 && "Invalid code");
9131 case ISD::ADDC: Opc = X86ISD::ADD; break;
9132 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9133 case ISD::SUBC: Opc = X86ISD::SUB; break;
9134 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9138 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9140 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9141 Op.getOperand(1), Op.getOperand(2));
9144 /// LowerOperation - Provide custom lowering hooks for some operations.
9146 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9147 switch (Op.getOpcode()) {
9148 default: llvm_unreachable("Should not custom lower this!");
9149 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
9150 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
9151 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
9152 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
9153 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
9154 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
9155 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9156 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9157 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
9158 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
9159 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
9160 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9161 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9162 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9163 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
9164 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
9165 case ISD::SHL_PARTS:
9166 case ISD::SRA_PARTS:
9167 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
9168 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
9169 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
9170 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
9171 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
9172 case ISD::FABS: return LowerFABS(Op, DAG);
9173 case ISD::FNEG: return LowerFNEG(Op, DAG);
9174 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
9175 case ISD::SETCC: return LowerSETCC(Op, DAG);
9176 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
9177 case ISD::SELECT: return LowerSELECT(Op, DAG);
9178 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
9179 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
9180 case ISD::VASTART: return LowerVASTART(Op, DAG);
9181 case ISD::VAARG: return LowerVAARG(Op, DAG);
9182 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
9183 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9184 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9185 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9186 case ISD::FRAME_TO_ARGS_OFFSET:
9187 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9188 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9189 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
9190 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
9191 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9192 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
9193 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
9194 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
9197 case ISD::SHL: return LowerShift(Op, DAG);
9203 case ISD::UMULO: return LowerXALUO(Op, DAG);
9204 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
9205 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
9209 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9213 void X86TargetLowering::
9214 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9215 SelectionDAG &DAG, unsigned NewOp) const {
9216 EVT T = Node->getValueType(0);
9217 DebugLoc dl = Node->getDebugLoc();
9218 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9220 SDValue Chain = Node->getOperand(0);
9221 SDValue In1 = Node->getOperand(1);
9222 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9223 Node->getOperand(2), DAG.getIntPtrConstant(0));
9224 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9225 Node->getOperand(2), DAG.getIntPtrConstant(1));
9226 SDValue Ops[] = { Chain, In1, In2L, In2H };
9227 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9229 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9230 cast<MemSDNode>(Node)->getMemOperand());
9231 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9232 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9233 Results.push_back(Result.getValue(2));
9236 /// ReplaceNodeResults - Replace a node with an illegal result type
9237 /// with a new node built out of custom code.
9238 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9239 SmallVectorImpl<SDValue>&Results,
9240 SelectionDAG &DAG) const {
9241 DebugLoc dl = N->getDebugLoc();
9242 switch (N->getOpcode()) {
9244 assert(false && "Do not know how to custom type legalize this operation!");
9250 // We don't want to expand or promote these.
9252 case ISD::FP_TO_SINT: {
9253 std::pair<SDValue,SDValue> Vals =
9254 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9255 SDValue FIST = Vals.first, StackSlot = Vals.second;
9256 if (FIST.getNode() != 0) {
9257 EVT VT = N->getValueType(0);
9258 // Return a load from the stack slot.
9259 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9260 MachinePointerInfo(), false, false, 0));
9264 case ISD::READCYCLECOUNTER: {
9265 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9266 SDValue TheChain = N->getOperand(0);
9267 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9268 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9270 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9272 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9273 SDValue Ops[] = { eax, edx };
9274 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9275 Results.push_back(edx.getValue(1));
9278 case ISD::ATOMIC_CMP_SWAP: {
9279 EVT T = N->getValueType(0);
9280 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9281 SDValue cpInL, cpInH;
9282 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9283 DAG.getConstant(0, MVT::i32));
9284 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9285 DAG.getConstant(1, MVT::i32));
9286 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9287 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9289 SDValue swapInL, swapInH;
9290 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9291 DAG.getConstant(0, MVT::i32));
9292 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9293 DAG.getConstant(1, MVT::i32));
9294 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9296 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9297 swapInL.getValue(1));
9298 SDValue Ops[] = { swapInH.getValue(0),
9300 swapInH.getValue(1) };
9301 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9302 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9303 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9305 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9306 MVT::i32, Result.getValue(1));
9307 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9308 MVT::i32, cpOutL.getValue(2));
9309 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9310 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9311 Results.push_back(cpOutH.getValue(1));
9314 case ISD::ATOMIC_LOAD_ADD:
9315 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9317 case ISD::ATOMIC_LOAD_AND:
9318 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9320 case ISD::ATOMIC_LOAD_NAND:
9321 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9323 case ISD::ATOMIC_LOAD_OR:
9324 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9326 case ISD::ATOMIC_LOAD_SUB:
9327 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9329 case ISD::ATOMIC_LOAD_XOR:
9330 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9332 case ISD::ATOMIC_SWAP:
9333 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9338 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9340 default: return NULL;
9341 case X86ISD::BSF: return "X86ISD::BSF";
9342 case X86ISD::BSR: return "X86ISD::BSR";
9343 case X86ISD::SHLD: return "X86ISD::SHLD";
9344 case X86ISD::SHRD: return "X86ISD::SHRD";
9345 case X86ISD::FAND: return "X86ISD::FAND";
9346 case X86ISD::FOR: return "X86ISD::FOR";
9347 case X86ISD::FXOR: return "X86ISD::FXOR";
9348 case X86ISD::FSRL: return "X86ISD::FSRL";
9349 case X86ISD::FILD: return "X86ISD::FILD";
9350 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
9351 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9352 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9353 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9354 case X86ISD::FLD: return "X86ISD::FLD";
9355 case X86ISD::FST: return "X86ISD::FST";
9356 case X86ISD::CALL: return "X86ISD::CALL";
9357 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
9358 case X86ISD::BT: return "X86ISD::BT";
9359 case X86ISD::CMP: return "X86ISD::CMP";
9360 case X86ISD::COMI: return "X86ISD::COMI";
9361 case X86ISD::UCOMI: return "X86ISD::UCOMI";
9362 case X86ISD::SETCC: return "X86ISD::SETCC";
9363 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
9364 case X86ISD::CMOV: return "X86ISD::CMOV";
9365 case X86ISD::BRCOND: return "X86ISD::BRCOND";
9366 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
9367 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
9368 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
9369 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
9370 case X86ISD::Wrapper: return "X86ISD::Wrapper";
9371 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
9372 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
9373 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
9374 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
9375 case X86ISD::PINSRB: return "X86ISD::PINSRB";
9376 case X86ISD::PINSRW: return "X86ISD::PINSRW";
9377 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
9378 case X86ISD::PANDN: return "X86ISD::PANDN";
9379 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
9380 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
9381 case X86ISD::PSIGND: return "X86ISD::PSIGND";
9382 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB";
9383 case X86ISD::FMAX: return "X86ISD::FMAX";
9384 case X86ISD::FMIN: return "X86ISD::FMIN";
9385 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
9386 case X86ISD::FRCP: return "X86ISD::FRCP";
9387 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
9388 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
9389 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
9390 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
9391 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
9392 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
9393 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
9394 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
9395 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
9396 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
9397 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
9398 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
9399 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
9400 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
9401 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
9402 case X86ISD::VSHL: return "X86ISD::VSHL";
9403 case X86ISD::VSRL: return "X86ISD::VSRL";
9404 case X86ISD::CMPPD: return "X86ISD::CMPPD";
9405 case X86ISD::CMPPS: return "X86ISD::CMPPS";
9406 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
9407 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
9408 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
9409 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
9410 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
9411 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
9412 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
9413 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
9414 case X86ISD::ADD: return "X86ISD::ADD";
9415 case X86ISD::SUB: return "X86ISD::SUB";
9416 case X86ISD::ADC: return "X86ISD::ADC";
9417 case X86ISD::SBB: return "X86ISD::SBB";
9418 case X86ISD::SMUL: return "X86ISD::SMUL";
9419 case X86ISD::UMUL: return "X86ISD::UMUL";
9420 case X86ISD::INC: return "X86ISD::INC";
9421 case X86ISD::DEC: return "X86ISD::DEC";
9422 case X86ISD::OR: return "X86ISD::OR";
9423 case X86ISD::XOR: return "X86ISD::XOR";
9424 case X86ISD::AND: return "X86ISD::AND";
9425 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
9426 case X86ISD::PTEST: return "X86ISD::PTEST";
9427 case X86ISD::TESTP: return "X86ISD::TESTP";
9428 case X86ISD::PALIGN: return "X86ISD::PALIGN";
9429 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
9430 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
9431 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
9432 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
9433 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
9434 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
9435 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
9436 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
9437 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
9438 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
9439 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
9440 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
9441 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
9442 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
9443 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
9444 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
9445 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
9446 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
9447 case X86ISD::MOVSD: return "X86ISD::MOVSD";
9448 case X86ISD::MOVSS: return "X86ISD::MOVSS";
9449 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
9450 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
9451 case X86ISD::VUNPCKLPS: return "X86ISD::VUNPCKLPS";
9452 case X86ISD::VUNPCKLPD: return "X86ISD::VUNPCKLPD";
9453 case X86ISD::VUNPCKLPSY: return "X86ISD::VUNPCKLPSY";
9454 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
9455 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
9456 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
9457 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
9458 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
9459 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
9460 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
9461 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
9462 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
9463 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
9464 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
9465 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9466 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
9467 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
9471 // isLegalAddressingMode - Return true if the addressing mode represented
9472 // by AM is legal for this target, for a load/store of the specified type.
9473 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9474 const Type *Ty) const {
9475 // X86 supports extremely general addressing modes.
9476 CodeModel::Model M = getTargetMachine().getCodeModel();
9477 Reloc::Model R = getTargetMachine().getRelocationModel();
9479 // X86 allows a sign-extended 32-bit immediate field as a displacement.
9480 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9485 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9487 // If a reference to this global requires an extra load, we can't fold it.
9488 if (isGlobalStubReference(GVFlags))
9491 // If BaseGV requires a register for the PIC base, we cannot also have a
9492 // BaseReg specified.
9493 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9496 // If lower 4G is not available, then we must use rip-relative addressing.
9497 if ((M != CodeModel::Small || R != Reloc::Static) &&
9498 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9508 // These scales always work.
9513 // These scales are formed with basereg+scalereg. Only accept if there is
9518 default: // Other stuff never works.
9526 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9527 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9529 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9530 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9531 if (NumBits1 <= NumBits2)
9536 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9537 if (!VT1.isInteger() || !VT2.isInteger())
9539 unsigned NumBits1 = VT1.getSizeInBits();
9540 unsigned NumBits2 = VT2.getSizeInBits();
9541 if (NumBits1 <= NumBits2)
9546 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9547 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9548 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9551 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9552 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9553 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9556 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9557 // i16 instructions are longer (0x66 prefix) and potentially slower.
9558 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9561 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9562 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9563 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9564 /// are assumed to be legal.
9566 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9568 // Very little shuffling can be done for 64-bit vectors right now.
9569 if (VT.getSizeInBits() == 64)
9570 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9572 // FIXME: pshufb, blends, shifts.
9573 return (VT.getVectorNumElements() == 2 ||
9574 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9575 isMOVLMask(M, VT) ||
9576 isSHUFPMask(M, VT) ||
9577 isPSHUFDMask(M, VT) ||
9578 isPSHUFHWMask(M, VT) ||
9579 isPSHUFLWMask(M, VT) ||
9580 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9581 isUNPCKLMask(M, VT) ||
9582 isUNPCKHMask(M, VT) ||
9583 isUNPCKL_v_undef_Mask(M, VT) ||
9584 isUNPCKH_v_undef_Mask(M, VT));
9588 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9590 unsigned NumElts = VT.getVectorNumElements();
9591 // FIXME: This collection of masks seems suspect.
9594 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9595 return (isMOVLMask(Mask, VT) ||
9596 isCommutedMOVLMask(Mask, VT, true) ||
9597 isSHUFPMask(Mask, VT) ||
9598 isCommutedSHUFPMask(Mask, VT));
9603 //===----------------------------------------------------------------------===//
9604 // X86 Scheduler Hooks
9605 //===----------------------------------------------------------------------===//
9607 // private utility function
9609 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9610 MachineBasicBlock *MBB,
9617 TargetRegisterClass *RC,
9618 bool invSrc) const {
9619 // For the atomic bitwise operator, we generate
9622 // ld t1 = [bitinstr.addr]
9623 // op t2 = t1, [bitinstr.val]
9625 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9627 // fallthrough -->nextMBB
9628 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9629 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9630 MachineFunction::iterator MBBIter = MBB;
9633 /// First build the CFG
9634 MachineFunction *F = MBB->getParent();
9635 MachineBasicBlock *thisMBB = MBB;
9636 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9637 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9638 F->insert(MBBIter, newMBB);
9639 F->insert(MBBIter, nextMBB);
9641 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9642 nextMBB->splice(nextMBB->begin(), thisMBB,
9643 llvm::next(MachineBasicBlock::iterator(bInstr)),
9645 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9647 // Update thisMBB to fall through to newMBB
9648 thisMBB->addSuccessor(newMBB);
9650 // newMBB jumps to itself and fall through to nextMBB
9651 newMBB->addSuccessor(nextMBB);
9652 newMBB->addSuccessor(newMBB);
9654 // Insert instructions into newMBB based on incoming instruction
9655 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9656 "unexpected number of operands");
9657 DebugLoc dl = bInstr->getDebugLoc();
9658 MachineOperand& destOper = bInstr->getOperand(0);
9659 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9660 int numArgs = bInstr->getNumOperands() - 1;
9661 for (int i=0; i < numArgs; ++i)
9662 argOpers[i] = &bInstr->getOperand(i+1);
9664 // x86 address has 4 operands: base, index, scale, and displacement
9665 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9666 int valArgIndx = lastAddrIndx + 1;
9668 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9669 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9670 for (int i=0; i <= lastAddrIndx; ++i)
9671 (*MIB).addOperand(*argOpers[i]);
9673 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9675 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9680 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9681 assert((argOpers[valArgIndx]->isReg() ||
9682 argOpers[valArgIndx]->isImm()) &&
9684 if (argOpers[valArgIndx]->isReg())
9685 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9687 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9689 (*MIB).addOperand(*argOpers[valArgIndx]);
9691 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9694 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9695 for (int i=0; i <= lastAddrIndx; ++i)
9696 (*MIB).addOperand(*argOpers[i]);
9698 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9699 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9700 bInstr->memoperands_end());
9702 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9706 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9708 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9712 // private utility function: 64 bit atomics on 32 bit host.
9714 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9715 MachineBasicBlock *MBB,
9720 bool invSrc) const {
9721 // For the atomic bitwise operator, we generate
9722 // thisMBB (instructions are in pairs, except cmpxchg8b)
9723 // ld t1,t2 = [bitinstr.addr]
9725 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9726 // op t5, t6 <- out1, out2, [bitinstr.val]
9727 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9728 // mov ECX, EBX <- t5, t6
9729 // mov EAX, EDX <- t1, t2
9730 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9731 // mov t3, t4 <- EAX, EDX
9733 // result in out1, out2
9734 // fallthrough -->nextMBB
9736 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9737 const unsigned LoadOpc = X86::MOV32rm;
9738 const unsigned NotOpc = X86::NOT32r;
9739 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9740 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9741 MachineFunction::iterator MBBIter = MBB;
9744 /// First build the CFG
9745 MachineFunction *F = MBB->getParent();
9746 MachineBasicBlock *thisMBB = MBB;
9747 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9748 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9749 F->insert(MBBIter, newMBB);
9750 F->insert(MBBIter, nextMBB);
9752 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9753 nextMBB->splice(nextMBB->begin(), thisMBB,
9754 llvm::next(MachineBasicBlock::iterator(bInstr)),
9756 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9758 // Update thisMBB to fall through to newMBB
9759 thisMBB->addSuccessor(newMBB);
9761 // newMBB jumps to itself and fall through to nextMBB
9762 newMBB->addSuccessor(nextMBB);
9763 newMBB->addSuccessor(newMBB);
9765 DebugLoc dl = bInstr->getDebugLoc();
9766 // Insert instructions into newMBB based on incoming instruction
9767 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9768 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9769 "unexpected number of operands");
9770 MachineOperand& dest1Oper = bInstr->getOperand(0);
9771 MachineOperand& dest2Oper = bInstr->getOperand(1);
9772 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9773 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9774 argOpers[i] = &bInstr->getOperand(i+2);
9776 // We use some of the operands multiple times, so conservatively just
9777 // clear any kill flags that might be present.
9778 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9779 argOpers[i]->setIsKill(false);
9782 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9783 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9785 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9786 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9787 for (int i=0; i <= lastAddrIndx; ++i)
9788 (*MIB).addOperand(*argOpers[i]);
9789 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9790 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9791 // add 4 to displacement.
9792 for (int i=0; i <= lastAddrIndx-2; ++i)
9793 (*MIB).addOperand(*argOpers[i]);
9794 MachineOperand newOp3 = *(argOpers[3]);
9796 newOp3.setImm(newOp3.getImm()+4);
9798 newOp3.setOffset(newOp3.getOffset()+4);
9799 (*MIB).addOperand(newOp3);
9800 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9802 // t3/4 are defined later, at the bottom of the loop
9803 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9804 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9805 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9806 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9807 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9808 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9810 // The subsequent operations should be using the destination registers of
9811 //the PHI instructions.
9813 t1 = F->getRegInfo().createVirtualRegister(RC);
9814 t2 = F->getRegInfo().createVirtualRegister(RC);
9815 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9816 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9818 t1 = dest1Oper.getReg();
9819 t2 = dest2Oper.getReg();
9822 int valArgIndx = lastAddrIndx + 1;
9823 assert((argOpers[valArgIndx]->isReg() ||
9824 argOpers[valArgIndx]->isImm()) &&
9826 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9827 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9828 if (argOpers[valArgIndx]->isReg())
9829 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9831 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9832 if (regOpcL != X86::MOV32rr)
9834 (*MIB).addOperand(*argOpers[valArgIndx]);
9835 assert(argOpers[valArgIndx + 1]->isReg() ==
9836 argOpers[valArgIndx]->isReg());
9837 assert(argOpers[valArgIndx + 1]->isImm() ==
9838 argOpers[valArgIndx]->isImm());
9839 if (argOpers[valArgIndx + 1]->isReg())
9840 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9842 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9843 if (regOpcH != X86::MOV32rr)
9845 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9847 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9849 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9852 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9854 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9857 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9858 for (int i=0; i <= lastAddrIndx; ++i)
9859 (*MIB).addOperand(*argOpers[i]);
9861 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9862 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9863 bInstr->memoperands_end());
9865 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9866 MIB.addReg(X86::EAX);
9867 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9868 MIB.addReg(X86::EDX);
9871 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9873 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9877 // private utility function
9879 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9880 MachineBasicBlock *MBB,
9881 unsigned cmovOpc) const {
9882 // For the atomic min/max operator, we generate
9885 // ld t1 = [min/max.addr]
9886 // mov t2 = [min/max.val]
9888 // cmov[cond] t2 = t1
9890 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9892 // fallthrough -->nextMBB
9894 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9895 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9896 MachineFunction::iterator MBBIter = MBB;
9899 /// First build the CFG
9900 MachineFunction *F = MBB->getParent();
9901 MachineBasicBlock *thisMBB = MBB;
9902 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9903 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9904 F->insert(MBBIter, newMBB);
9905 F->insert(MBBIter, nextMBB);
9907 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9908 nextMBB->splice(nextMBB->begin(), thisMBB,
9909 llvm::next(MachineBasicBlock::iterator(mInstr)),
9911 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9913 // Update thisMBB to fall through to newMBB
9914 thisMBB->addSuccessor(newMBB);
9916 // newMBB jumps to newMBB and fall through to nextMBB
9917 newMBB->addSuccessor(nextMBB);
9918 newMBB->addSuccessor(newMBB);
9920 DebugLoc dl = mInstr->getDebugLoc();
9921 // Insert instructions into newMBB based on incoming instruction
9922 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9923 "unexpected number of operands");
9924 MachineOperand& destOper = mInstr->getOperand(0);
9925 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9926 int numArgs = mInstr->getNumOperands() - 1;
9927 for (int i=0; i < numArgs; ++i)
9928 argOpers[i] = &mInstr->getOperand(i+1);
9930 // x86 address has 4 operands: base, index, scale, and displacement
9931 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9932 int valArgIndx = lastAddrIndx + 1;
9934 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9935 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9936 for (int i=0; i <= lastAddrIndx; ++i)
9937 (*MIB).addOperand(*argOpers[i]);
9939 // We only support register and immediate values
9940 assert((argOpers[valArgIndx]->isReg() ||
9941 argOpers[valArgIndx]->isImm()) &&
9944 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9945 if (argOpers[valArgIndx]->isReg())
9946 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9948 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9949 (*MIB).addOperand(*argOpers[valArgIndx]);
9951 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9954 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9959 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9960 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9964 // Cmp and exchange if none has modified the memory location
9965 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9966 for (int i=0; i <= lastAddrIndx; ++i)
9967 (*MIB).addOperand(*argOpers[i]);
9969 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9970 (*MIB).setMemRefs(mInstr->memoperands_begin(),
9971 mInstr->memoperands_end());
9973 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9974 MIB.addReg(X86::EAX);
9977 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9979 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
9983 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9984 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9987 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9988 unsigned numArgs, bool memArg) const {
9989 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9990 "Target must have SSE4.2 or AVX features enabled");
9992 DebugLoc dl = MI->getDebugLoc();
9993 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9995 if (!Subtarget->hasAVX()) {
9997 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9999 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10002 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10004 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10007 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10008 for (unsigned i = 0; i < numArgs; ++i) {
10009 MachineOperand &Op = MI->getOperand(i+1);
10010 if (!(Op.isReg() && Op.isImplicit()))
10011 MIB.addOperand(Op);
10013 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10014 .addReg(X86::XMM0);
10016 MI->eraseFromParent();
10020 MachineBasicBlock *
10021 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10022 DebugLoc dl = MI->getDebugLoc();
10023 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10025 // Address into RAX/EAX, other two args into ECX, EDX.
10026 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10027 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10028 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10029 for (int i = 0; i < X86::AddrNumOperands; ++i)
10030 MIB.addOperand(MI->getOperand(i));
10032 unsigned ValOps = X86::AddrNumOperands;
10033 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10034 .addReg(MI->getOperand(ValOps).getReg());
10035 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10036 .addReg(MI->getOperand(ValOps+1).getReg());
10038 // The instruction doesn't actually take any operands though.
10039 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10041 MI->eraseFromParent(); // The pseudo is gone now.
10045 MachineBasicBlock *
10046 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10047 DebugLoc dl = MI->getDebugLoc();
10048 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10050 // First arg in ECX, the second in EAX.
10051 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10052 .addReg(MI->getOperand(0).getReg());
10053 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10054 .addReg(MI->getOperand(1).getReg());
10056 // The instruction doesn't actually take any operands though.
10057 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10059 MI->eraseFromParent(); // The pseudo is gone now.
10063 MachineBasicBlock *
10064 X86TargetLowering::EmitVAARG64WithCustomInserter(
10066 MachineBasicBlock *MBB) const {
10067 // Emit va_arg instruction on X86-64.
10069 // Operands to this pseudo-instruction:
10070 // 0 ) Output : destination address (reg)
10071 // 1-5) Input : va_list address (addr, i64mem)
10072 // 6 ) ArgSize : Size (in bytes) of vararg type
10073 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10074 // 8 ) Align : Alignment of type
10075 // 9 ) EFLAGS (implicit-def)
10077 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10078 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10080 unsigned DestReg = MI->getOperand(0).getReg();
10081 MachineOperand &Base = MI->getOperand(1);
10082 MachineOperand &Scale = MI->getOperand(2);
10083 MachineOperand &Index = MI->getOperand(3);
10084 MachineOperand &Disp = MI->getOperand(4);
10085 MachineOperand &Segment = MI->getOperand(5);
10086 unsigned ArgSize = MI->getOperand(6).getImm();
10087 unsigned ArgMode = MI->getOperand(7).getImm();
10088 unsigned Align = MI->getOperand(8).getImm();
10090 // Memory Reference
10091 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10092 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10093 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10095 // Machine Information
10096 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10097 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10098 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10099 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10100 DebugLoc DL = MI->getDebugLoc();
10102 // struct va_list {
10105 // i64 overflow_area (address)
10106 // i64 reg_save_area (address)
10108 // sizeof(va_list) = 24
10109 // alignment(va_list) = 8
10111 unsigned TotalNumIntRegs = 6;
10112 unsigned TotalNumXMMRegs = 8;
10113 bool UseGPOffset = (ArgMode == 1);
10114 bool UseFPOffset = (ArgMode == 2);
10115 unsigned MaxOffset = TotalNumIntRegs * 8 +
10116 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10118 /* Align ArgSize to a multiple of 8 */
10119 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10120 bool NeedsAlign = (Align > 8);
10122 MachineBasicBlock *thisMBB = MBB;
10123 MachineBasicBlock *overflowMBB;
10124 MachineBasicBlock *offsetMBB;
10125 MachineBasicBlock *endMBB;
10127 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
10128 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
10129 unsigned OffsetReg = 0;
10131 if (!UseGPOffset && !UseFPOffset) {
10132 // If we only pull from the overflow region, we don't create a branch.
10133 // We don't need to alter control flow.
10134 OffsetDestReg = 0; // unused
10135 OverflowDestReg = DestReg;
10138 overflowMBB = thisMBB;
10141 // First emit code to check if gp_offset (or fp_offset) is below the bound.
10142 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10143 // If not, pull from overflow_area. (branch to overflowMBB)
10148 // offsetMBB overflowMBB
10153 // Registers for the PHI in endMBB
10154 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10155 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10157 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10158 MachineFunction *MF = MBB->getParent();
10159 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10160 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10161 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10163 MachineFunction::iterator MBBIter = MBB;
10166 // Insert the new basic blocks
10167 MF->insert(MBBIter, offsetMBB);
10168 MF->insert(MBBIter, overflowMBB);
10169 MF->insert(MBBIter, endMBB);
10171 // Transfer the remainder of MBB and its successor edges to endMBB.
10172 endMBB->splice(endMBB->begin(), thisMBB,
10173 llvm::next(MachineBasicBlock::iterator(MI)),
10175 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10177 // Make offsetMBB and overflowMBB successors of thisMBB
10178 thisMBB->addSuccessor(offsetMBB);
10179 thisMBB->addSuccessor(overflowMBB);
10181 // endMBB is a successor of both offsetMBB and overflowMBB
10182 offsetMBB->addSuccessor(endMBB);
10183 overflowMBB->addSuccessor(endMBB);
10185 // Load the offset value into a register
10186 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10187 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10191 .addDisp(Disp, UseFPOffset ? 4 : 0)
10192 .addOperand(Segment)
10193 .setMemRefs(MMOBegin, MMOEnd);
10195 // Check if there is enough room left to pull this argument.
10196 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10198 .addImm(MaxOffset + 8 - ArgSizeA8);
10200 // Branch to "overflowMBB" if offset >= max
10201 // Fall through to "offsetMBB" otherwise
10202 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10203 .addMBB(overflowMBB);
10206 // In offsetMBB, emit code to use the reg_save_area.
10208 assert(OffsetReg != 0);
10210 // Read the reg_save_area address.
10211 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10212 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10217 .addOperand(Segment)
10218 .setMemRefs(MMOBegin, MMOEnd);
10220 // Zero-extend the offset
10221 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10222 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10225 .addImm(X86::sub_32bit);
10227 // Add the offset to the reg_save_area to get the final address.
10228 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10229 .addReg(OffsetReg64)
10230 .addReg(RegSaveReg);
10232 // Compute the offset for the next argument
10233 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10234 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10236 .addImm(UseFPOffset ? 16 : 8);
10238 // Store it back into the va_list.
10239 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10243 .addDisp(Disp, UseFPOffset ? 4 : 0)
10244 .addOperand(Segment)
10245 .addReg(NextOffsetReg)
10246 .setMemRefs(MMOBegin, MMOEnd);
10249 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10254 // Emit code to use overflow area
10257 // Load the overflow_area address into a register.
10258 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10259 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10264 .addOperand(Segment)
10265 .setMemRefs(MMOBegin, MMOEnd);
10267 // If we need to align it, do so. Otherwise, just copy the address
10268 // to OverflowDestReg.
10270 // Align the overflow address
10271 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10272 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10274 // aligned_addr = (addr + (align-1)) & ~(align-1)
10275 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10276 .addReg(OverflowAddrReg)
10279 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10281 .addImm(~(uint64_t)(Align-1));
10283 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10284 .addReg(OverflowAddrReg);
10287 // Compute the next overflow address after this argument.
10288 // (the overflow address should be kept 8-byte aligned)
10289 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10290 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10291 .addReg(OverflowDestReg)
10292 .addImm(ArgSizeA8);
10294 // Store the new overflow address.
10295 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10300 .addOperand(Segment)
10301 .addReg(NextAddrReg)
10302 .setMemRefs(MMOBegin, MMOEnd);
10304 // If we branched, emit the PHI to the front of endMBB.
10306 BuildMI(*endMBB, endMBB->begin(), DL,
10307 TII->get(X86::PHI), DestReg)
10308 .addReg(OffsetDestReg).addMBB(offsetMBB)
10309 .addReg(OverflowDestReg).addMBB(overflowMBB);
10312 // Erase the pseudo instruction
10313 MI->eraseFromParent();
10318 MachineBasicBlock *
10319 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10321 MachineBasicBlock *MBB) const {
10322 // Emit code to save XMM registers to the stack. The ABI says that the
10323 // number of registers to save is given in %al, so it's theoretically
10324 // possible to do an indirect jump trick to avoid saving all of them,
10325 // however this code takes a simpler approach and just executes all
10326 // of the stores if %al is non-zero. It's less code, and it's probably
10327 // easier on the hardware branch predictor, and stores aren't all that
10328 // expensive anyway.
10330 // Create the new basic blocks. One block contains all the XMM stores,
10331 // and one block is the final destination regardless of whether any
10332 // stores were performed.
10333 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10334 MachineFunction *F = MBB->getParent();
10335 MachineFunction::iterator MBBIter = MBB;
10337 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10338 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10339 F->insert(MBBIter, XMMSaveMBB);
10340 F->insert(MBBIter, EndMBB);
10342 // Transfer the remainder of MBB and its successor edges to EndMBB.
10343 EndMBB->splice(EndMBB->begin(), MBB,
10344 llvm::next(MachineBasicBlock::iterator(MI)),
10346 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10348 // The original block will now fall through to the XMM save block.
10349 MBB->addSuccessor(XMMSaveMBB);
10350 // The XMMSaveMBB will fall through to the end block.
10351 XMMSaveMBB->addSuccessor(EndMBB);
10353 // Now add the instructions.
10354 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10355 DebugLoc DL = MI->getDebugLoc();
10357 unsigned CountReg = MI->getOperand(0).getReg();
10358 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10359 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10361 if (!Subtarget->isTargetWin64()) {
10362 // If %al is 0, branch around the XMM save block.
10363 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10364 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10365 MBB->addSuccessor(EndMBB);
10368 // In the XMM save block, save all the XMM argument registers.
10369 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10370 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10371 MachineMemOperand *MMO =
10372 F->getMachineMemOperand(
10373 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10374 MachineMemOperand::MOStore,
10375 /*Size=*/16, /*Align=*/16);
10376 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10377 .addFrameIndex(RegSaveFrameIndex)
10378 .addImm(/*Scale=*/1)
10379 .addReg(/*IndexReg=*/0)
10380 .addImm(/*Disp=*/Offset)
10381 .addReg(/*Segment=*/0)
10382 .addReg(MI->getOperand(i).getReg())
10383 .addMemOperand(MMO);
10386 MI->eraseFromParent(); // The pseudo instruction is gone now.
10391 MachineBasicBlock *
10392 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10393 MachineBasicBlock *BB) const {
10394 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10395 DebugLoc DL = MI->getDebugLoc();
10397 // To "insert" a SELECT_CC instruction, we actually have to insert the
10398 // diamond control-flow pattern. The incoming instruction knows the
10399 // destination vreg to set, the condition code register to branch on, the
10400 // true/false values to select between, and a branch opcode to use.
10401 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10402 MachineFunction::iterator It = BB;
10408 // cmpTY ccX, r1, r2
10410 // fallthrough --> copy0MBB
10411 MachineBasicBlock *thisMBB = BB;
10412 MachineFunction *F = BB->getParent();
10413 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10414 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10415 F->insert(It, copy0MBB);
10416 F->insert(It, sinkMBB);
10418 // If the EFLAGS register isn't dead in the terminator, then claim that it's
10419 // live into the sink and copy blocks.
10420 const MachineFunction *MF = BB->getParent();
10421 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10422 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10424 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10425 const MachineOperand &MO = MI->getOperand(I);
10426 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10427 unsigned Reg = MO.getReg();
10428 if (Reg != X86::EFLAGS) continue;
10429 copy0MBB->addLiveIn(Reg);
10430 sinkMBB->addLiveIn(Reg);
10433 // Transfer the remainder of BB and its successor edges to sinkMBB.
10434 sinkMBB->splice(sinkMBB->begin(), BB,
10435 llvm::next(MachineBasicBlock::iterator(MI)),
10437 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10439 // Add the true and fallthrough blocks as its successors.
10440 BB->addSuccessor(copy0MBB);
10441 BB->addSuccessor(sinkMBB);
10443 // Create the conditional branch instruction.
10445 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10446 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10449 // %FalseValue = ...
10450 // # fallthrough to sinkMBB
10451 copy0MBB->addSuccessor(sinkMBB);
10454 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10456 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10457 TII->get(X86::PHI), MI->getOperand(0).getReg())
10458 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10459 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10461 MI->eraseFromParent(); // The pseudo instruction is gone now.
10465 MachineBasicBlock *
10466 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10467 MachineBasicBlock *BB) const {
10468 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10469 DebugLoc DL = MI->getDebugLoc();
10471 assert(!Subtarget->isTargetEnvMacho());
10473 // The lowering is pretty easy: we're just emitting the call to _alloca. The
10474 // non-trivial part is impdef of ESP.
10476 if (Subtarget->isTargetWin64()) {
10477 if (Subtarget->isTargetCygMing()) {
10478 // ___chkstk(Mingw64):
10479 // Clobbers R10, R11, RAX and EFLAGS.
10481 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10482 .addExternalSymbol("___chkstk")
10483 .addReg(X86::RAX, RegState::Implicit)
10484 .addReg(X86::RSP, RegState::Implicit)
10485 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10486 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10487 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10489 // __chkstk(MSVCRT): does not update stack pointer.
10490 // Clobbers R10, R11 and EFLAGS.
10491 // FIXME: RAX(allocated size) might be reused and not killed.
10492 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10493 .addExternalSymbol("__chkstk")
10494 .addReg(X86::RAX, RegState::Implicit)
10495 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10496 // RAX has the offset to subtracted from RSP.
10497 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10502 const char *StackProbeSymbol =
10503 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10505 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10506 .addExternalSymbol(StackProbeSymbol)
10507 .addReg(X86::EAX, RegState::Implicit)
10508 .addReg(X86::ESP, RegState::Implicit)
10509 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10510 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10511 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10514 MI->eraseFromParent(); // The pseudo instruction is gone now.
10518 MachineBasicBlock *
10519 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10520 MachineBasicBlock *BB) const {
10521 // This is pretty easy. We're taking the value that we received from
10522 // our load from the relocation, sticking it in either RDI (x86-64)
10523 // or EAX and doing an indirect call. The return value will then
10524 // be in the normal return register.
10525 const X86InstrInfo *TII
10526 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10527 DebugLoc DL = MI->getDebugLoc();
10528 MachineFunction *F = BB->getParent();
10530 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10531 assert(MI->getOperand(3).isGlobal() && "This should be a global");
10533 if (Subtarget->is64Bit()) {
10534 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10535 TII->get(X86::MOV64rm), X86::RDI)
10537 .addImm(0).addReg(0)
10538 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10539 MI->getOperand(3).getTargetFlags())
10541 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10542 addDirectMem(MIB, X86::RDI);
10543 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10544 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10545 TII->get(X86::MOV32rm), X86::EAX)
10547 .addImm(0).addReg(0)
10548 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10549 MI->getOperand(3).getTargetFlags())
10551 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10552 addDirectMem(MIB, X86::EAX);
10554 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10555 TII->get(X86::MOV32rm), X86::EAX)
10556 .addReg(TII->getGlobalBaseReg(F))
10557 .addImm(0).addReg(0)
10558 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10559 MI->getOperand(3).getTargetFlags())
10561 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10562 addDirectMem(MIB, X86::EAX);
10565 MI->eraseFromParent(); // The pseudo instruction is gone now.
10569 MachineBasicBlock *
10570 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10571 MachineBasicBlock *BB) const {
10572 switch (MI->getOpcode()) {
10573 default: assert(false && "Unexpected instr type to insert");
10574 case X86::TAILJMPd64:
10575 case X86::TAILJMPr64:
10576 case X86::TAILJMPm64:
10577 assert(!"TAILJMP64 would not be touched here.");
10578 case X86::TCRETURNdi64:
10579 case X86::TCRETURNri64:
10580 case X86::TCRETURNmi64:
10581 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10582 // On AMD64, additional defs should be added before register allocation.
10583 if (!Subtarget->isTargetWin64()) {
10584 MI->addRegisterDefined(X86::RSI);
10585 MI->addRegisterDefined(X86::RDI);
10586 MI->addRegisterDefined(X86::XMM6);
10587 MI->addRegisterDefined(X86::XMM7);
10588 MI->addRegisterDefined(X86::XMM8);
10589 MI->addRegisterDefined(X86::XMM9);
10590 MI->addRegisterDefined(X86::XMM10);
10591 MI->addRegisterDefined(X86::XMM11);
10592 MI->addRegisterDefined(X86::XMM12);
10593 MI->addRegisterDefined(X86::XMM13);
10594 MI->addRegisterDefined(X86::XMM14);
10595 MI->addRegisterDefined(X86::XMM15);
10598 case X86::WIN_ALLOCA:
10599 return EmitLoweredWinAlloca(MI, BB);
10600 case X86::TLSCall_32:
10601 case X86::TLSCall_64:
10602 return EmitLoweredTLSCall(MI, BB);
10603 case X86::CMOV_GR8:
10604 case X86::CMOV_FR32:
10605 case X86::CMOV_FR64:
10606 case X86::CMOV_V4F32:
10607 case X86::CMOV_V2F64:
10608 case X86::CMOV_V2I64:
10609 case X86::CMOV_GR16:
10610 case X86::CMOV_GR32:
10611 case X86::CMOV_RFP32:
10612 case X86::CMOV_RFP64:
10613 case X86::CMOV_RFP80:
10614 return EmitLoweredSelect(MI, BB);
10616 case X86::FP32_TO_INT16_IN_MEM:
10617 case X86::FP32_TO_INT32_IN_MEM:
10618 case X86::FP32_TO_INT64_IN_MEM:
10619 case X86::FP64_TO_INT16_IN_MEM:
10620 case X86::FP64_TO_INT32_IN_MEM:
10621 case X86::FP64_TO_INT64_IN_MEM:
10622 case X86::FP80_TO_INT16_IN_MEM:
10623 case X86::FP80_TO_INT32_IN_MEM:
10624 case X86::FP80_TO_INT64_IN_MEM: {
10625 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10626 DebugLoc DL = MI->getDebugLoc();
10628 // Change the floating point control register to use "round towards zero"
10629 // mode when truncating to an integer value.
10630 MachineFunction *F = BB->getParent();
10631 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10632 addFrameReference(BuildMI(*BB, MI, DL,
10633 TII->get(X86::FNSTCW16m)), CWFrameIdx);
10635 // Load the old value of the high byte of the control word...
10637 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10638 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10641 // Set the high part to be round to zero...
10642 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10645 // Reload the modified control word now...
10646 addFrameReference(BuildMI(*BB, MI, DL,
10647 TII->get(X86::FLDCW16m)), CWFrameIdx);
10649 // Restore the memory image of control word to original value
10650 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10653 // Get the X86 opcode to use.
10655 switch (MI->getOpcode()) {
10656 default: llvm_unreachable("illegal opcode!");
10657 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10658 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10659 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10660 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10661 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10662 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10663 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10664 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10665 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10669 MachineOperand &Op = MI->getOperand(0);
10671 AM.BaseType = X86AddressMode::RegBase;
10672 AM.Base.Reg = Op.getReg();
10674 AM.BaseType = X86AddressMode::FrameIndexBase;
10675 AM.Base.FrameIndex = Op.getIndex();
10677 Op = MI->getOperand(1);
10679 AM.Scale = Op.getImm();
10680 Op = MI->getOperand(2);
10682 AM.IndexReg = Op.getImm();
10683 Op = MI->getOperand(3);
10684 if (Op.isGlobal()) {
10685 AM.GV = Op.getGlobal();
10687 AM.Disp = Op.getImm();
10689 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10690 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10692 // Reload the original control word now.
10693 addFrameReference(BuildMI(*BB, MI, DL,
10694 TII->get(X86::FLDCW16m)), CWFrameIdx);
10696 MI->eraseFromParent(); // The pseudo instruction is gone now.
10699 // String/text processing lowering.
10700 case X86::PCMPISTRM128REG:
10701 case X86::VPCMPISTRM128REG:
10702 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10703 case X86::PCMPISTRM128MEM:
10704 case X86::VPCMPISTRM128MEM:
10705 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10706 case X86::PCMPESTRM128REG:
10707 case X86::VPCMPESTRM128REG:
10708 return EmitPCMP(MI, BB, 5, false /* in mem */);
10709 case X86::PCMPESTRM128MEM:
10710 case X86::VPCMPESTRM128MEM:
10711 return EmitPCMP(MI, BB, 5, true /* in mem */);
10713 // Thread synchronization.
10715 return EmitMonitor(MI, BB);
10717 return EmitMwait(MI, BB);
10719 // Atomic Lowering.
10720 case X86::ATOMAND32:
10721 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10722 X86::AND32ri, X86::MOV32rm,
10724 X86::NOT32r, X86::EAX,
10725 X86::GR32RegisterClass);
10726 case X86::ATOMOR32:
10727 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10728 X86::OR32ri, X86::MOV32rm,
10730 X86::NOT32r, X86::EAX,
10731 X86::GR32RegisterClass);
10732 case X86::ATOMXOR32:
10733 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10734 X86::XOR32ri, X86::MOV32rm,
10736 X86::NOT32r, X86::EAX,
10737 X86::GR32RegisterClass);
10738 case X86::ATOMNAND32:
10739 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10740 X86::AND32ri, X86::MOV32rm,
10742 X86::NOT32r, X86::EAX,
10743 X86::GR32RegisterClass, true);
10744 case X86::ATOMMIN32:
10745 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10746 case X86::ATOMMAX32:
10747 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10748 case X86::ATOMUMIN32:
10749 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10750 case X86::ATOMUMAX32:
10751 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10753 case X86::ATOMAND16:
10754 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10755 X86::AND16ri, X86::MOV16rm,
10757 X86::NOT16r, X86::AX,
10758 X86::GR16RegisterClass);
10759 case X86::ATOMOR16:
10760 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10761 X86::OR16ri, X86::MOV16rm,
10763 X86::NOT16r, X86::AX,
10764 X86::GR16RegisterClass);
10765 case X86::ATOMXOR16:
10766 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10767 X86::XOR16ri, X86::MOV16rm,
10769 X86::NOT16r, X86::AX,
10770 X86::GR16RegisterClass);
10771 case X86::ATOMNAND16:
10772 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10773 X86::AND16ri, X86::MOV16rm,
10775 X86::NOT16r, X86::AX,
10776 X86::GR16RegisterClass, true);
10777 case X86::ATOMMIN16:
10778 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10779 case X86::ATOMMAX16:
10780 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10781 case X86::ATOMUMIN16:
10782 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10783 case X86::ATOMUMAX16:
10784 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10786 case X86::ATOMAND8:
10787 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10788 X86::AND8ri, X86::MOV8rm,
10790 X86::NOT8r, X86::AL,
10791 X86::GR8RegisterClass);
10793 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10794 X86::OR8ri, X86::MOV8rm,
10796 X86::NOT8r, X86::AL,
10797 X86::GR8RegisterClass);
10798 case X86::ATOMXOR8:
10799 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10800 X86::XOR8ri, X86::MOV8rm,
10802 X86::NOT8r, X86::AL,
10803 X86::GR8RegisterClass);
10804 case X86::ATOMNAND8:
10805 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10806 X86::AND8ri, X86::MOV8rm,
10808 X86::NOT8r, X86::AL,
10809 X86::GR8RegisterClass, true);
10810 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10811 // This group is for 64-bit host.
10812 case X86::ATOMAND64:
10813 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10814 X86::AND64ri32, X86::MOV64rm,
10816 X86::NOT64r, X86::RAX,
10817 X86::GR64RegisterClass);
10818 case X86::ATOMOR64:
10819 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10820 X86::OR64ri32, X86::MOV64rm,
10822 X86::NOT64r, X86::RAX,
10823 X86::GR64RegisterClass);
10824 case X86::ATOMXOR64:
10825 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10826 X86::XOR64ri32, X86::MOV64rm,
10828 X86::NOT64r, X86::RAX,
10829 X86::GR64RegisterClass);
10830 case X86::ATOMNAND64:
10831 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10832 X86::AND64ri32, X86::MOV64rm,
10834 X86::NOT64r, X86::RAX,
10835 X86::GR64RegisterClass, true);
10836 case X86::ATOMMIN64:
10837 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10838 case X86::ATOMMAX64:
10839 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10840 case X86::ATOMUMIN64:
10841 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10842 case X86::ATOMUMAX64:
10843 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10845 // This group does 64-bit operations on a 32-bit host.
10846 case X86::ATOMAND6432:
10847 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10848 X86::AND32rr, X86::AND32rr,
10849 X86::AND32ri, X86::AND32ri,
10851 case X86::ATOMOR6432:
10852 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10853 X86::OR32rr, X86::OR32rr,
10854 X86::OR32ri, X86::OR32ri,
10856 case X86::ATOMXOR6432:
10857 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10858 X86::XOR32rr, X86::XOR32rr,
10859 X86::XOR32ri, X86::XOR32ri,
10861 case X86::ATOMNAND6432:
10862 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10863 X86::AND32rr, X86::AND32rr,
10864 X86::AND32ri, X86::AND32ri,
10866 case X86::ATOMADD6432:
10867 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10868 X86::ADD32rr, X86::ADC32rr,
10869 X86::ADD32ri, X86::ADC32ri,
10871 case X86::ATOMSUB6432:
10872 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10873 X86::SUB32rr, X86::SBB32rr,
10874 X86::SUB32ri, X86::SBB32ri,
10876 case X86::ATOMSWAP6432:
10877 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10878 X86::MOV32rr, X86::MOV32rr,
10879 X86::MOV32ri, X86::MOV32ri,
10881 case X86::VASTART_SAVE_XMM_REGS:
10882 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10884 case X86::VAARG_64:
10885 return EmitVAARG64WithCustomInserter(MI, BB);
10889 //===----------------------------------------------------------------------===//
10890 // X86 Optimization Hooks
10891 //===----------------------------------------------------------------------===//
10893 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10897 const SelectionDAG &DAG,
10898 unsigned Depth) const {
10899 unsigned Opc = Op.getOpcode();
10900 assert((Opc >= ISD::BUILTIN_OP_END ||
10901 Opc == ISD::INTRINSIC_WO_CHAIN ||
10902 Opc == ISD::INTRINSIC_W_CHAIN ||
10903 Opc == ISD::INTRINSIC_VOID) &&
10904 "Should use MaskedValueIsZero if you don't know whether Op"
10905 " is a target node!");
10907 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
10921 // These nodes' second result is a boolean.
10922 if (Op.getResNo() == 0)
10925 case X86ISD::SETCC:
10926 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10927 Mask.getBitWidth() - 1);
10932 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10933 unsigned Depth) const {
10934 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10935 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10936 return Op.getValueType().getScalarType().getSizeInBits();
10942 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10943 /// node is a GlobalAddress + offset.
10944 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10945 const GlobalValue* &GA,
10946 int64_t &Offset) const {
10947 if (N->getOpcode() == X86ISD::Wrapper) {
10948 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10949 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10950 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10954 return TargetLowering::isGAPlusOffset(N, GA, Offset);
10957 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10958 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10959 /// if the load addresses are consecutive, non-overlapping, and in the right
10961 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10962 TargetLowering::DAGCombinerInfo &DCI) {
10963 DebugLoc dl = N->getDebugLoc();
10964 EVT VT = N->getValueType(0);
10966 if (VT.getSizeInBits() != 128)
10969 // Don't create instructions with illegal types after legalize types has run.
10970 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10971 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
10974 SmallVector<SDValue, 16> Elts;
10975 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10976 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10978 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10981 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10982 /// generation and convert it from being a bunch of shuffles and extracts
10983 /// to a simple store and scalar loads to extract the elements.
10984 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10985 const TargetLowering &TLI) {
10986 SDValue InputVector = N->getOperand(0);
10988 // Only operate on vectors of 4 elements, where the alternative shuffling
10989 // gets to be more expensive.
10990 if (InputVector.getValueType() != MVT::v4i32)
10993 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10994 // single use which is a sign-extend or zero-extend, and all elements are
10996 SmallVector<SDNode *, 4> Uses;
10997 unsigned ExtractedElements = 0;
10998 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10999 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11000 if (UI.getUse().getResNo() != InputVector.getResNo())
11003 SDNode *Extract = *UI;
11004 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11007 if (Extract->getValueType(0) != MVT::i32)
11009 if (!Extract->hasOneUse())
11011 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11012 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11014 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11017 // Record which element was extracted.
11018 ExtractedElements |=
11019 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11021 Uses.push_back(Extract);
11024 // If not all the elements were used, this may not be worthwhile.
11025 if (ExtractedElements != 15)
11028 // Ok, we've now decided to do the transformation.
11029 DebugLoc dl = InputVector.getDebugLoc();
11031 // Store the value to a temporary stack slot.
11032 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11033 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11034 MachinePointerInfo(), false, false, 0);
11036 // Replace each use (extract) with a load of the appropriate element.
11037 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11038 UE = Uses.end(); UI != UE; ++UI) {
11039 SDNode *Extract = *UI;
11041 // cOMpute the element's address.
11042 SDValue Idx = Extract->getOperand(1);
11044 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11045 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11046 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11048 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11049 StackPtr, OffsetVal);
11051 // Load the scalar.
11052 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11053 ScalarAddr, MachinePointerInfo(),
11056 // Replace the exact with the load.
11057 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11060 // The replacement was made in place; don't return anything.
11064 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11065 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11066 const X86Subtarget *Subtarget) {
11067 DebugLoc DL = N->getDebugLoc();
11068 SDValue Cond = N->getOperand(0);
11069 // Get the LHS/RHS of the select.
11070 SDValue LHS = N->getOperand(1);
11071 SDValue RHS = N->getOperand(2);
11073 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11074 // instructions match the semantics of the common C idiom x<y?x:y but not
11075 // x<=y?x:y, because of how they handle negative zero (which can be
11076 // ignored in unsafe-math mode).
11077 if (Subtarget->hasSSE2() &&
11078 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11079 Cond.getOpcode() == ISD::SETCC) {
11080 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11082 unsigned Opcode = 0;
11083 // Check for x CC y ? x : y.
11084 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11085 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11089 // Converting this to a min would handle NaNs incorrectly, and swapping
11090 // the operands would cause it to handle comparisons between positive
11091 // and negative zero incorrectly.
11092 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11093 if (!UnsafeFPMath &&
11094 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11096 std::swap(LHS, RHS);
11098 Opcode = X86ISD::FMIN;
11101 // Converting this to a min would handle comparisons between positive
11102 // and negative zero incorrectly.
11103 if (!UnsafeFPMath &&
11104 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11106 Opcode = X86ISD::FMIN;
11109 // Converting this to a min would handle both negative zeros and NaNs
11110 // incorrectly, but we can swap the operands to fix both.
11111 std::swap(LHS, RHS);
11115 Opcode = X86ISD::FMIN;
11119 // Converting this to a max would handle comparisons between positive
11120 // and negative zero incorrectly.
11121 if (!UnsafeFPMath &&
11122 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11124 Opcode = X86ISD::FMAX;
11127 // Converting this to a max would handle NaNs incorrectly, and swapping
11128 // the operands would cause it to handle comparisons between positive
11129 // and negative zero incorrectly.
11130 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11131 if (!UnsafeFPMath &&
11132 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11134 std::swap(LHS, RHS);
11136 Opcode = X86ISD::FMAX;
11139 // Converting this to a max 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::FMAX;
11148 // Check for x CC y ? y : x -- a min/max with reversed arms.
11149 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11150 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11154 // Converting this to a min would handle comparisons between positive
11155 // and negative zero incorrectly, and swapping the operands would
11156 // cause it to handle NaNs incorrectly.
11157 if (!UnsafeFPMath &&
11158 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11159 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11161 std::swap(LHS, RHS);
11163 Opcode = X86ISD::FMIN;
11166 // Converting this to a min would handle NaNs incorrectly.
11167 if (!UnsafeFPMath &&
11168 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11170 Opcode = X86ISD::FMIN;
11173 // Converting this to a min would handle both negative zeros and NaNs
11174 // incorrectly, but we can swap the operands to fix both.
11175 std::swap(LHS, RHS);
11179 Opcode = X86ISD::FMIN;
11183 // Converting this to a max would handle NaNs incorrectly.
11184 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11186 Opcode = X86ISD::FMAX;
11189 // Converting this to a max would handle comparisons between positive
11190 // and negative zero incorrectly, and swapping the operands would
11191 // cause it to handle NaNs incorrectly.
11192 if (!UnsafeFPMath &&
11193 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11194 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11196 std::swap(LHS, RHS);
11198 Opcode = X86ISD::FMAX;
11201 // Converting this to a max would handle both negative zeros and NaNs
11202 // incorrectly, but we can swap the operands to fix both.
11203 std::swap(LHS, RHS);
11207 Opcode = X86ISD::FMAX;
11213 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11216 // If this is a select between two integer constants, try to do some
11218 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11219 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11220 // Don't do this for crazy integer types.
11221 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11222 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11223 // so that TrueC (the true value) is larger than FalseC.
11224 bool NeedsCondInvert = false;
11226 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11227 // Efficiently invertible.
11228 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
11229 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
11230 isa<ConstantSDNode>(Cond.getOperand(1))))) {
11231 NeedsCondInvert = true;
11232 std::swap(TrueC, FalseC);
11235 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
11236 if (FalseC->getAPIntValue() == 0 &&
11237 TrueC->getAPIntValue().isPowerOf2()) {
11238 if (NeedsCondInvert) // Invert the condition if needed.
11239 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11240 DAG.getConstant(1, Cond.getValueType()));
11242 // Zero extend the condition if needed.
11243 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11245 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11246 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11247 DAG.getConstant(ShAmt, MVT::i8));
11250 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11251 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11252 if (NeedsCondInvert) // Invert the condition if needed.
11253 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11254 DAG.getConstant(1, Cond.getValueType()));
11256 // Zero extend the condition if needed.
11257 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11258 FalseC->getValueType(0), Cond);
11259 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11260 SDValue(FalseC, 0));
11263 // Optimize cases that will turn into an LEA instruction. This requires
11264 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11265 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11266 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11267 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11269 bool isFastMultiplier = false;
11271 switch ((unsigned char)Diff) {
11273 case 1: // result = add base, cond
11274 case 2: // result = lea base( , cond*2)
11275 case 3: // result = lea base(cond, cond*2)
11276 case 4: // result = lea base( , cond*4)
11277 case 5: // result = lea base(cond, cond*4)
11278 case 8: // result = lea base( , cond*8)
11279 case 9: // result = lea base(cond, cond*8)
11280 isFastMultiplier = true;
11285 if (isFastMultiplier) {
11286 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11287 if (NeedsCondInvert) // Invert the condition if needed.
11288 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11289 DAG.getConstant(1, Cond.getValueType()));
11291 // Zero extend the condition if needed.
11292 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11294 // Scale the condition by the difference.
11296 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11297 DAG.getConstant(Diff, Cond.getValueType()));
11299 // Add the base if non-zero.
11300 if (FalseC->getAPIntValue() != 0)
11301 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11302 SDValue(FalseC, 0));
11312 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11313 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11314 TargetLowering::DAGCombinerInfo &DCI) {
11315 DebugLoc DL = N->getDebugLoc();
11317 // If the flag operand isn't dead, don't touch this CMOV.
11318 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11321 // If this is a select between two integer constants, try to do some
11322 // optimizations. Note that the operands are ordered the opposite of SELECT
11324 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
11325 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11326 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11327 // larger than FalseC (the false value).
11328 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11330 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11331 CC = X86::GetOppositeBranchCondition(CC);
11332 std::swap(TrueC, FalseC);
11335 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
11336 // This is efficient for any integer data type (including i8/i16) and
11338 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11339 SDValue Cond = N->getOperand(3);
11340 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11341 DAG.getConstant(CC, MVT::i8), Cond);
11343 // Zero extend the condition if needed.
11344 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11346 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11347 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11348 DAG.getConstant(ShAmt, MVT::i8));
11349 if (N->getNumValues() == 2) // Dead flag value?
11350 return DCI.CombineTo(N, Cond, SDValue());
11354 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
11355 // for any integer data type, including i8/i16.
11356 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11357 SDValue Cond = N->getOperand(3);
11358 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11359 DAG.getConstant(CC, MVT::i8), Cond);
11361 // Zero extend the condition if needed.
11362 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11363 FalseC->getValueType(0), Cond);
11364 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11365 SDValue(FalseC, 0));
11367 if (N->getNumValues() == 2) // Dead flag value?
11368 return DCI.CombineTo(N, Cond, SDValue());
11372 // Optimize cases that will turn into an LEA instruction. This requires
11373 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11374 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11375 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11376 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11378 bool isFastMultiplier = false;
11380 switch ((unsigned char)Diff) {
11382 case 1: // result = add base, cond
11383 case 2: // result = lea base( , cond*2)
11384 case 3: // result = lea base(cond, cond*2)
11385 case 4: // result = lea base( , cond*4)
11386 case 5: // result = lea base(cond, cond*4)
11387 case 8: // result = lea base( , cond*8)
11388 case 9: // result = lea base(cond, cond*8)
11389 isFastMultiplier = true;
11394 if (isFastMultiplier) {
11395 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11396 SDValue Cond = N->getOperand(3);
11397 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11398 DAG.getConstant(CC, MVT::i8), Cond);
11399 // Zero extend the condition if needed.
11400 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11402 // Scale the condition by the difference.
11404 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11405 DAG.getConstant(Diff, Cond.getValueType()));
11407 // Add the base if non-zero.
11408 if (FalseC->getAPIntValue() != 0)
11409 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11410 SDValue(FalseC, 0));
11411 if (N->getNumValues() == 2) // Dead flag value?
11412 return DCI.CombineTo(N, Cond, SDValue());
11422 /// PerformMulCombine - Optimize a single multiply with constant into two
11423 /// in order to implement it with two cheaper instructions, e.g.
11424 /// LEA + SHL, LEA + LEA.
11425 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11426 TargetLowering::DAGCombinerInfo &DCI) {
11427 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11430 EVT VT = N->getValueType(0);
11431 if (VT != MVT::i64)
11434 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11437 uint64_t MulAmt = C->getZExtValue();
11438 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11441 uint64_t MulAmt1 = 0;
11442 uint64_t MulAmt2 = 0;
11443 if ((MulAmt % 9) == 0) {
11445 MulAmt2 = MulAmt / 9;
11446 } else if ((MulAmt % 5) == 0) {
11448 MulAmt2 = MulAmt / 5;
11449 } else if ((MulAmt % 3) == 0) {
11451 MulAmt2 = MulAmt / 3;
11454 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11455 DebugLoc DL = N->getDebugLoc();
11457 if (isPowerOf2_64(MulAmt2) &&
11458 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11459 // If second multiplifer is pow2, issue it first. We want the multiply by
11460 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11462 std::swap(MulAmt1, MulAmt2);
11465 if (isPowerOf2_64(MulAmt1))
11466 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11467 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11469 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11470 DAG.getConstant(MulAmt1, VT));
11472 if (isPowerOf2_64(MulAmt2))
11473 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11474 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11476 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11477 DAG.getConstant(MulAmt2, VT));
11479 // Do not add new nodes to DAG combiner worklist.
11480 DCI.CombineTo(N, NewMul, false);
11485 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11486 SDValue N0 = N->getOperand(0);
11487 SDValue N1 = N->getOperand(1);
11488 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11489 EVT VT = N0.getValueType();
11491 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11492 // since the result of setcc_c is all zero's or all ones.
11493 if (N1C && N0.getOpcode() == ISD::AND &&
11494 N0.getOperand(1).getOpcode() == ISD::Constant) {
11495 SDValue N00 = N0.getOperand(0);
11496 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11497 ((N00.getOpcode() == ISD::ANY_EXTEND ||
11498 N00.getOpcode() == ISD::ZERO_EXTEND) &&
11499 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11500 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11501 APInt ShAmt = N1C->getAPIntValue();
11502 Mask = Mask.shl(ShAmt);
11504 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11505 N00, DAG.getConstant(Mask, VT));
11512 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11514 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11515 const X86Subtarget *Subtarget) {
11516 EVT VT = N->getValueType(0);
11517 if (!VT.isVector() && VT.isInteger() &&
11518 N->getOpcode() == ISD::SHL)
11519 return PerformSHLCombine(N, DAG);
11521 // On X86 with SSE2 support, we can transform this to a vector shift if
11522 // all elements are shifted by the same amount. We can't do this in legalize
11523 // because the a constant vector is typically transformed to a constant pool
11524 // so we have no knowledge of the shift amount.
11525 if (!Subtarget->hasSSE2())
11528 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11531 SDValue ShAmtOp = N->getOperand(1);
11532 EVT EltVT = VT.getVectorElementType();
11533 DebugLoc DL = N->getDebugLoc();
11534 SDValue BaseShAmt = SDValue();
11535 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11536 unsigned NumElts = VT.getVectorNumElements();
11538 for (; i != NumElts; ++i) {
11539 SDValue Arg = ShAmtOp.getOperand(i);
11540 if (Arg.getOpcode() == ISD::UNDEF) continue;
11544 for (; i != NumElts; ++i) {
11545 SDValue Arg = ShAmtOp.getOperand(i);
11546 if (Arg.getOpcode() == ISD::UNDEF) continue;
11547 if (Arg != BaseShAmt) {
11551 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11552 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11553 SDValue InVec = ShAmtOp.getOperand(0);
11554 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11555 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11557 for (; i != NumElts; ++i) {
11558 SDValue Arg = InVec.getOperand(i);
11559 if (Arg.getOpcode() == ISD::UNDEF) continue;
11563 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11564 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11565 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11566 if (C->getZExtValue() == SplatIdx)
11567 BaseShAmt = InVec.getOperand(1);
11570 if (BaseShAmt.getNode() == 0)
11571 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11572 DAG.getIntPtrConstant(0));
11576 // The shift amount is an i32.
11577 if (EltVT.bitsGT(MVT::i32))
11578 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11579 else if (EltVT.bitsLT(MVT::i32))
11580 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11582 // The shift amount is identical so we can do a vector shift.
11583 SDValue ValOp = N->getOperand(0);
11584 switch (N->getOpcode()) {
11586 llvm_unreachable("Unknown shift opcode!");
11589 if (VT == MVT::v2i64)
11590 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11591 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11593 if (VT == MVT::v4i32)
11594 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11595 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11597 if (VT == MVT::v8i16)
11598 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11599 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11603 if (VT == MVT::v4i32)
11604 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11605 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11607 if (VT == MVT::v8i16)
11608 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11609 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11613 if (VT == MVT::v2i64)
11614 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11615 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11617 if (VT == MVT::v4i32)
11618 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11619 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11621 if (VT == MVT::v8i16)
11622 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11623 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11631 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11632 TargetLowering::DAGCombinerInfo &DCI,
11633 const X86Subtarget *Subtarget) {
11634 if (DCI.isBeforeLegalizeOps())
11637 // Want to form PANDN nodes, in the hopes of then easily combining them with
11638 // OR and AND nodes to form PBLEND/PSIGN.
11639 EVT VT = N->getValueType(0);
11640 if (VT != MVT::v2i64)
11643 SDValue N0 = N->getOperand(0);
11644 SDValue N1 = N->getOperand(1);
11645 DebugLoc DL = N->getDebugLoc();
11647 // Check LHS for vnot
11648 if (N0.getOpcode() == ISD::XOR &&
11649 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11650 return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11652 // Check RHS for vnot
11653 if (N1.getOpcode() == ISD::XOR &&
11654 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11655 return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11660 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11661 TargetLowering::DAGCombinerInfo &DCI,
11662 const X86Subtarget *Subtarget) {
11663 if (DCI.isBeforeLegalizeOps())
11666 EVT VT = N->getValueType(0);
11667 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11670 SDValue N0 = N->getOperand(0);
11671 SDValue N1 = N->getOperand(1);
11673 // look for psign/blend
11674 if (Subtarget->hasSSSE3()) {
11675 if (VT == MVT::v2i64) {
11676 // Canonicalize pandn to RHS
11677 if (N0.getOpcode() == X86ISD::PANDN)
11679 // or (and (m, x), (pandn m, y))
11680 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11681 SDValue Mask = N1.getOperand(0);
11682 SDValue X = N1.getOperand(1);
11684 if (N0.getOperand(0) == Mask)
11685 Y = N0.getOperand(1);
11686 if (N0.getOperand(1) == Mask)
11687 Y = N0.getOperand(0);
11689 // Check to see if the mask appeared in both the AND and PANDN and
11693 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11694 if (Mask.getOpcode() != ISD::BITCAST ||
11695 X.getOpcode() != ISD::BITCAST ||
11696 Y.getOpcode() != ISD::BITCAST)
11699 // Look through mask bitcast.
11700 Mask = Mask.getOperand(0);
11701 EVT MaskVT = Mask.getValueType();
11703 // Validate that the Mask operand is a vector sra node. The sra node
11704 // will be an intrinsic.
11705 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11708 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11709 // there is no psrai.b
11710 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11711 case Intrinsic::x86_sse2_psrai_w:
11712 case Intrinsic::x86_sse2_psrai_d:
11714 default: return SDValue();
11717 // Check that the SRA is all signbits.
11718 SDValue SraC = Mask.getOperand(2);
11719 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
11720 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11721 if ((SraAmt + 1) != EltBits)
11724 DebugLoc DL = N->getDebugLoc();
11726 // Now we know we at least have a plendvb with the mask val. See if
11727 // we can form a psignb/w/d.
11728 // psign = x.type == y.type == mask.type && y = sub(0, x);
11729 X = X.getOperand(0);
11730 Y = Y.getOperand(0);
11731 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11732 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11733 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11736 case 8: Opc = X86ISD::PSIGNB; break;
11737 case 16: Opc = X86ISD::PSIGNW; break;
11738 case 32: Opc = X86ISD::PSIGND; break;
11742 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11743 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11746 // PBLENDVB only available on SSE 4.1
11747 if (!Subtarget->hasSSE41())
11750 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11751 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11752 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11753 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11754 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11759 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11760 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11762 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11764 if (!N0.hasOneUse() || !N1.hasOneUse())
11767 SDValue ShAmt0 = N0.getOperand(1);
11768 if (ShAmt0.getValueType() != MVT::i8)
11770 SDValue ShAmt1 = N1.getOperand(1);
11771 if (ShAmt1.getValueType() != MVT::i8)
11773 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11774 ShAmt0 = ShAmt0.getOperand(0);
11775 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11776 ShAmt1 = ShAmt1.getOperand(0);
11778 DebugLoc DL = N->getDebugLoc();
11779 unsigned Opc = X86ISD::SHLD;
11780 SDValue Op0 = N0.getOperand(0);
11781 SDValue Op1 = N1.getOperand(0);
11782 if (ShAmt0.getOpcode() == ISD::SUB) {
11783 Opc = X86ISD::SHRD;
11784 std::swap(Op0, Op1);
11785 std::swap(ShAmt0, ShAmt1);
11788 unsigned Bits = VT.getSizeInBits();
11789 if (ShAmt1.getOpcode() == ISD::SUB) {
11790 SDValue Sum = ShAmt1.getOperand(0);
11791 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11792 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11793 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11794 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11795 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11796 return DAG.getNode(Opc, DL, VT,
11798 DAG.getNode(ISD::TRUNCATE, DL,
11801 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11802 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11804 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11805 return DAG.getNode(Opc, DL, VT,
11806 N0.getOperand(0), N1.getOperand(0),
11807 DAG.getNode(ISD::TRUNCATE, DL,
11814 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11815 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11816 const X86Subtarget *Subtarget) {
11817 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
11818 // the FP state in cases where an emms may be missing.
11819 // A preferable solution to the general problem is to figure out the right
11820 // places to insert EMMS. This qualifies as a quick hack.
11822 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11823 StoreSDNode *St = cast<StoreSDNode>(N);
11824 EVT VT = St->getValue().getValueType();
11825 if (VT.getSizeInBits() != 64)
11828 const Function *F = DAG.getMachineFunction().getFunction();
11829 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11830 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11831 && Subtarget->hasSSE2();
11832 if ((VT.isVector() ||
11833 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11834 isa<LoadSDNode>(St->getValue()) &&
11835 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11836 St->getChain().hasOneUse() && !St->isVolatile()) {
11837 SDNode* LdVal = St->getValue().getNode();
11838 LoadSDNode *Ld = 0;
11839 int TokenFactorIndex = -1;
11840 SmallVector<SDValue, 8> Ops;
11841 SDNode* ChainVal = St->getChain().getNode();
11842 // Must be a store of a load. We currently handle two cases: the load
11843 // is a direct child, and it's under an intervening TokenFactor. It is
11844 // possible to dig deeper under nested TokenFactors.
11845 if (ChainVal == LdVal)
11846 Ld = cast<LoadSDNode>(St->getChain());
11847 else if (St->getValue().hasOneUse() &&
11848 ChainVal->getOpcode() == ISD::TokenFactor) {
11849 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11850 if (ChainVal->getOperand(i).getNode() == LdVal) {
11851 TokenFactorIndex = i;
11852 Ld = cast<LoadSDNode>(St->getValue());
11854 Ops.push_back(ChainVal->getOperand(i));
11858 if (!Ld || !ISD::isNormalLoad(Ld))
11861 // If this is not the MMX case, i.e. we are just turning i64 load/store
11862 // into f64 load/store, avoid the transformation if there are multiple
11863 // uses of the loaded value.
11864 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11867 DebugLoc LdDL = Ld->getDebugLoc();
11868 DebugLoc StDL = N->getDebugLoc();
11869 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11870 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11872 if (Subtarget->is64Bit() || F64IsLegal) {
11873 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11874 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11875 Ld->getPointerInfo(), Ld->isVolatile(),
11876 Ld->isNonTemporal(), Ld->getAlignment());
11877 SDValue NewChain = NewLd.getValue(1);
11878 if (TokenFactorIndex != -1) {
11879 Ops.push_back(NewChain);
11880 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11883 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11884 St->getPointerInfo(),
11885 St->isVolatile(), St->isNonTemporal(),
11886 St->getAlignment());
11889 // Otherwise, lower to two pairs of 32-bit loads / stores.
11890 SDValue LoAddr = Ld->getBasePtr();
11891 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11892 DAG.getConstant(4, MVT::i32));
11894 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11895 Ld->getPointerInfo(),
11896 Ld->isVolatile(), Ld->isNonTemporal(),
11897 Ld->getAlignment());
11898 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11899 Ld->getPointerInfo().getWithOffset(4),
11900 Ld->isVolatile(), Ld->isNonTemporal(),
11901 MinAlign(Ld->getAlignment(), 4));
11903 SDValue NewChain = LoLd.getValue(1);
11904 if (TokenFactorIndex != -1) {
11905 Ops.push_back(LoLd);
11906 Ops.push_back(HiLd);
11907 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11911 LoAddr = St->getBasePtr();
11912 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11913 DAG.getConstant(4, MVT::i32));
11915 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11916 St->getPointerInfo(),
11917 St->isVolatile(), St->isNonTemporal(),
11918 St->getAlignment());
11919 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11920 St->getPointerInfo().getWithOffset(4),
11922 St->isNonTemporal(),
11923 MinAlign(St->getAlignment(), 4));
11924 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11929 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11930 /// X86ISD::FXOR nodes.
11931 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11932 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11933 // F[X]OR(0.0, x) -> x
11934 // F[X]OR(x, 0.0) -> x
11935 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11936 if (C->getValueAPF().isPosZero())
11937 return N->getOperand(1);
11938 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11939 if (C->getValueAPF().isPosZero())
11940 return N->getOperand(0);
11944 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11945 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11946 // FAND(0.0, x) -> 0.0
11947 // FAND(x, 0.0) -> 0.0
11948 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11949 if (C->getValueAPF().isPosZero())
11950 return N->getOperand(0);
11951 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11952 if (C->getValueAPF().isPosZero())
11953 return N->getOperand(1);
11957 static SDValue PerformBTCombine(SDNode *N,
11959 TargetLowering::DAGCombinerInfo &DCI) {
11960 // BT ignores high bits in the bit index operand.
11961 SDValue Op1 = N->getOperand(1);
11962 if (Op1.hasOneUse()) {
11963 unsigned BitWidth = Op1.getValueSizeInBits();
11964 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11965 APInt KnownZero, KnownOne;
11966 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11967 !DCI.isBeforeLegalizeOps());
11968 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11969 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11970 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11971 DCI.CommitTargetLoweringOpt(TLO);
11976 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11977 SDValue Op = N->getOperand(0);
11978 if (Op.getOpcode() == ISD::BITCAST)
11979 Op = Op.getOperand(0);
11980 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11981 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11982 VT.getVectorElementType().getSizeInBits() ==
11983 OpVT.getVectorElementType().getSizeInBits()) {
11984 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11989 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11990 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
11991 // (and (i32 x86isd::setcc_carry), 1)
11992 // This eliminates the zext. This transformation is necessary because
11993 // ISD::SETCC is always legalized to i8.
11994 DebugLoc dl = N->getDebugLoc();
11995 SDValue N0 = N->getOperand(0);
11996 EVT VT = N->getValueType(0);
11997 if (N0.getOpcode() == ISD::AND &&
11999 N0.getOperand(0).hasOneUse()) {
12000 SDValue N00 = N0.getOperand(0);
12001 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12003 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12004 if (!C || C->getZExtValue() != 1)
12006 return DAG.getNode(ISD::AND, dl, VT,
12007 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12008 N00.getOperand(0), N00.getOperand(1)),
12009 DAG.getConstant(1, VT));
12015 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12016 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12017 unsigned X86CC = N->getConstantOperandVal(0);
12018 SDValue EFLAG = N->getOperand(1);
12019 DebugLoc DL = N->getDebugLoc();
12021 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12022 // a zext and produces an all-ones bit which is more useful than 0/1 in some
12024 if (X86CC == X86::COND_B)
12025 return DAG.getNode(ISD::AND, DL, MVT::i8,
12026 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12027 DAG.getConstant(X86CC, MVT::i8), EFLAG),
12028 DAG.getConstant(1, MVT::i8));
12033 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12034 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12035 X86TargetLowering::DAGCombinerInfo &DCI) {
12036 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12037 // the result is either zero or one (depending on the input carry bit).
12038 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12039 if (X86::isZeroNode(N->getOperand(0)) &&
12040 X86::isZeroNode(N->getOperand(1)) &&
12041 // We don't have a good way to replace an EFLAGS use, so only do this when
12043 SDValue(N, 1).use_empty()) {
12044 DebugLoc DL = N->getDebugLoc();
12045 EVT VT = N->getValueType(0);
12046 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12047 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12048 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12049 DAG.getConstant(X86::COND_B,MVT::i8),
12051 DAG.getConstant(1, VT));
12052 return DCI.CombineTo(N, Res1, CarryOut);
12058 // fold (add Y, (sete X, 0)) -> adc 0, Y
12059 // (add Y, (setne X, 0)) -> sbb -1, Y
12060 // (sub (sete X, 0), Y) -> sbb 0, Y
12061 // (sub (setne X, 0), Y) -> adc -1, Y
12062 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12063 DebugLoc DL = N->getDebugLoc();
12065 // Look through ZExts.
12066 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12067 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12070 SDValue SetCC = Ext.getOperand(0);
12071 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12074 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12075 if (CC != X86::COND_E && CC != X86::COND_NE)
12078 SDValue Cmp = SetCC.getOperand(1);
12079 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12080 !X86::isZeroNode(Cmp.getOperand(1)) ||
12081 !Cmp.getOperand(0).getValueType().isInteger())
12084 SDValue CmpOp0 = Cmp.getOperand(0);
12085 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12086 DAG.getConstant(1, CmpOp0.getValueType()));
12088 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12089 if (CC == X86::COND_NE)
12090 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12091 DL, OtherVal.getValueType(), OtherVal,
12092 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12093 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12094 DL, OtherVal.getValueType(), OtherVal,
12095 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12098 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12099 DAGCombinerInfo &DCI) const {
12100 SelectionDAG &DAG = DCI.DAG;
12101 switch (N->getOpcode()) {
12103 case ISD::EXTRACT_VECTOR_ELT:
12104 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12105 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
12106 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
12108 case ISD::SUB: return OptimizeConditonalInDecrement(N, DAG);
12109 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
12110 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
12113 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
12114 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
12115 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
12116 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
12118 case X86ISD::FOR: return PerformFORCombine(N, DAG);
12119 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
12120 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
12121 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
12122 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
12123 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
12124 case X86ISD::SHUFPS: // Handle all target specific shuffles
12125 case X86ISD::SHUFPD:
12126 case X86ISD::PALIGN:
12127 case X86ISD::PUNPCKHBW:
12128 case X86ISD::PUNPCKHWD:
12129 case X86ISD::PUNPCKHDQ:
12130 case X86ISD::PUNPCKHQDQ:
12131 case X86ISD::UNPCKHPS:
12132 case X86ISD::UNPCKHPD:
12133 case X86ISD::PUNPCKLBW:
12134 case X86ISD::PUNPCKLWD:
12135 case X86ISD::PUNPCKLDQ:
12136 case X86ISD::PUNPCKLQDQ:
12137 case X86ISD::UNPCKLPS:
12138 case X86ISD::UNPCKLPD:
12139 case X86ISD::VUNPCKLPS:
12140 case X86ISD::VUNPCKLPD:
12141 case X86ISD::VUNPCKLPSY:
12142 case X86ISD::VUNPCKLPDY:
12143 case X86ISD::MOVHLPS:
12144 case X86ISD::MOVLHPS:
12145 case X86ISD::PSHUFD:
12146 case X86ISD::PSHUFHW:
12147 case X86ISD::PSHUFLW:
12148 case X86ISD::MOVSS:
12149 case X86ISD::MOVSD:
12150 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12156 /// isTypeDesirableForOp - Return true if the target has native support for
12157 /// the specified value type and it is 'desirable' to use the type for the
12158 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12159 /// instruction encodings are longer and some i16 instructions are slow.
12160 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12161 if (!isTypeLegal(VT))
12163 if (VT != MVT::i16)
12170 case ISD::SIGN_EXTEND:
12171 case ISD::ZERO_EXTEND:
12172 case ISD::ANY_EXTEND:
12185 /// IsDesirableToPromoteOp - This method query the target whether it is
12186 /// beneficial for dag combiner to promote the specified node. If true, it
12187 /// should return the desired promotion type by reference.
12188 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12189 EVT VT = Op.getValueType();
12190 if (VT != MVT::i16)
12193 bool Promote = false;
12194 bool Commute = false;
12195 switch (Op.getOpcode()) {
12198 LoadSDNode *LD = cast<LoadSDNode>(Op);
12199 // If the non-extending load has a single use and it's not live out, then it
12200 // might be folded.
12201 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12202 Op.hasOneUse()*/) {
12203 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12204 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12205 // The only case where we'd want to promote LOAD (rather then it being
12206 // promoted as an operand is when it's only use is liveout.
12207 if (UI->getOpcode() != ISD::CopyToReg)
12214 case ISD::SIGN_EXTEND:
12215 case ISD::ZERO_EXTEND:
12216 case ISD::ANY_EXTEND:
12221 SDValue N0 = Op.getOperand(0);
12222 // Look out for (store (shl (load), x)).
12223 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12236 SDValue N0 = Op.getOperand(0);
12237 SDValue N1 = Op.getOperand(1);
12238 if (!Commute && MayFoldLoad(N1))
12240 // Avoid disabling potential load folding opportunities.
12241 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12243 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12253 //===----------------------------------------------------------------------===//
12254 // X86 Inline Assembly Support
12255 //===----------------------------------------------------------------------===//
12257 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12258 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12260 std::string AsmStr = IA->getAsmString();
12262 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12263 SmallVector<StringRef, 4> AsmPieces;
12264 SplitString(AsmStr, AsmPieces, ";\n");
12266 switch (AsmPieces.size()) {
12267 default: return false;
12269 AsmStr = AsmPieces[0];
12271 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
12273 // FIXME: this should verify that we are targeting a 486 or better. If not,
12274 // we will turn this bswap into something that will be lowered to logical ops
12275 // instead of emitting the bswap asm. For now, we don't support 486 or lower
12276 // so don't worry about this.
12278 if (AsmPieces.size() == 2 &&
12279 (AsmPieces[0] == "bswap" ||
12280 AsmPieces[0] == "bswapq" ||
12281 AsmPieces[0] == "bswapl") &&
12282 (AsmPieces[1] == "$0" ||
12283 AsmPieces[1] == "${0:q}")) {
12284 // No need to check constraints, nothing other than the equivalent of
12285 // "=r,0" would be valid here.
12286 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12287 if (!Ty || Ty->getBitWidth() % 16 != 0)
12289 return IntrinsicLowering::LowerToByteSwap(CI);
12291 // rorw $$8, ${0:w} --> llvm.bswap.i16
12292 if (CI->getType()->isIntegerTy(16) &&
12293 AsmPieces.size() == 3 &&
12294 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12295 AsmPieces[1] == "$$8," &&
12296 AsmPieces[2] == "${0:w}" &&
12297 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12299 const std::string &ConstraintsStr = IA->getConstraintString();
12300 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12301 std::sort(AsmPieces.begin(), AsmPieces.end());
12302 if (AsmPieces.size() == 4 &&
12303 AsmPieces[0] == "~{cc}" &&
12304 AsmPieces[1] == "~{dirflag}" &&
12305 AsmPieces[2] == "~{flags}" &&
12306 AsmPieces[3] == "~{fpsr}") {
12307 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12308 if (!Ty || Ty->getBitWidth() % 16 != 0)
12310 return IntrinsicLowering::LowerToByteSwap(CI);
12315 if (CI->getType()->isIntegerTy(32) &&
12316 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12317 SmallVector<StringRef, 4> Words;
12318 SplitString(AsmPieces[0], Words, " \t,");
12319 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12320 Words[2] == "${0:w}") {
12322 SplitString(AsmPieces[1], Words, " \t,");
12323 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12324 Words[2] == "$0") {
12326 SplitString(AsmPieces[2], Words, " \t,");
12327 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12328 Words[2] == "${0:w}") {
12330 const std::string &ConstraintsStr = IA->getConstraintString();
12331 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12332 std::sort(AsmPieces.begin(), AsmPieces.end());
12333 if (AsmPieces.size() == 4 &&
12334 AsmPieces[0] == "~{cc}" &&
12335 AsmPieces[1] == "~{dirflag}" &&
12336 AsmPieces[2] == "~{flags}" &&
12337 AsmPieces[3] == "~{fpsr}") {
12338 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12339 if (!Ty || Ty->getBitWidth() % 16 != 0)
12341 return IntrinsicLowering::LowerToByteSwap(CI);
12348 if (CI->getType()->isIntegerTy(64)) {
12349 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12350 if (Constraints.size() >= 2 &&
12351 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12352 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12353 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
12354 SmallVector<StringRef, 4> Words;
12355 SplitString(AsmPieces[0], Words, " \t");
12356 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12358 SplitString(AsmPieces[1], Words, " \t");
12359 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12361 SplitString(AsmPieces[2], Words, " \t,");
12362 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12363 Words[2] == "%edx") {
12364 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12365 if (!Ty || Ty->getBitWidth() % 16 != 0)
12367 return IntrinsicLowering::LowerToByteSwap(CI);
12380 /// getConstraintType - Given a constraint letter, return the type of
12381 /// constraint it is for this target.
12382 X86TargetLowering::ConstraintType
12383 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12384 if (Constraint.size() == 1) {
12385 switch (Constraint[0]) {
12395 return C_RegisterClass;
12419 return TargetLowering::getConstraintType(Constraint);
12422 /// Examine constraint type and operand type and determine a weight value.
12423 /// This object must already have been set up with the operand type
12424 /// and the current alternative constraint selected.
12425 TargetLowering::ConstraintWeight
12426 X86TargetLowering::getSingleConstraintMatchWeight(
12427 AsmOperandInfo &info, const char *constraint) const {
12428 ConstraintWeight weight = CW_Invalid;
12429 Value *CallOperandVal = info.CallOperandVal;
12430 // If we don't have a value, we can't do a match,
12431 // but allow it at the lowest weight.
12432 if (CallOperandVal == NULL)
12434 const Type *type = CallOperandVal->getType();
12435 // Look at the constraint type.
12436 switch (*constraint) {
12438 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12449 if (CallOperandVal->getType()->isIntegerTy())
12450 weight = CW_SpecificReg;
12455 if (type->isFloatingPointTy())
12456 weight = CW_SpecificReg;
12459 if (type->isX86_MMXTy() && Subtarget->hasMMX())
12460 weight = CW_SpecificReg;
12464 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12465 weight = CW_Register;
12468 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12469 if (C->getZExtValue() <= 31)
12470 weight = CW_Constant;
12474 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12475 if (C->getZExtValue() <= 63)
12476 weight = CW_Constant;
12480 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12481 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12482 weight = CW_Constant;
12486 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12487 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12488 weight = CW_Constant;
12492 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12493 if (C->getZExtValue() <= 3)
12494 weight = CW_Constant;
12498 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12499 if (C->getZExtValue() <= 0xff)
12500 weight = CW_Constant;
12505 if (dyn_cast<ConstantFP>(CallOperandVal)) {
12506 weight = CW_Constant;
12510 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12511 if ((C->getSExtValue() >= -0x80000000LL) &&
12512 (C->getSExtValue() <= 0x7fffffffLL))
12513 weight = CW_Constant;
12517 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12518 if (C->getZExtValue() <= 0xffffffff)
12519 weight = CW_Constant;
12526 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12527 /// with another that has more specific requirements based on the type of the
12528 /// corresponding operand.
12529 const char *X86TargetLowering::
12530 LowerXConstraint(EVT ConstraintVT) const {
12531 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12532 // 'f' like normal targets.
12533 if (ConstraintVT.isFloatingPoint()) {
12534 if (Subtarget->hasXMMInt())
12536 if (Subtarget->hasXMM())
12540 return TargetLowering::LowerXConstraint(ConstraintVT);
12543 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12544 /// vector. If it is invalid, don't add anything to Ops.
12545 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12547 std::vector<SDValue>&Ops,
12548 SelectionDAG &DAG) const {
12549 SDValue Result(0, 0);
12551 switch (Constraint) {
12554 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12555 if (C->getZExtValue() <= 31) {
12556 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12562 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12563 if (C->getZExtValue() <= 63) {
12564 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12570 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12571 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12572 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12578 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12579 if (C->getZExtValue() <= 255) {
12580 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12586 // 32-bit signed value
12587 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12588 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12589 C->getSExtValue())) {
12590 // Widen to 64 bits here to get it sign extended.
12591 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12594 // FIXME gcc accepts some relocatable values here too, but only in certain
12595 // memory models; it's complicated.
12600 // 32-bit unsigned value
12601 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12602 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12603 C->getZExtValue())) {
12604 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12608 // FIXME gcc accepts some relocatable values here too, but only in certain
12609 // memory models; it's complicated.
12613 // Literal immediates are always ok.
12614 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12615 // Widen to 64 bits here to get it sign extended.
12616 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12620 // In any sort of PIC mode addresses need to be computed at runtime by
12621 // adding in a register or some sort of table lookup. These can't
12622 // be used as immediates.
12623 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12626 // If we are in non-pic codegen mode, we allow the address of a global (with
12627 // an optional displacement) to be used with 'i'.
12628 GlobalAddressSDNode *GA = 0;
12629 int64_t Offset = 0;
12631 // Match either (GA), (GA+C), (GA+C1+C2), etc.
12633 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12634 Offset += GA->getOffset();
12636 } else if (Op.getOpcode() == ISD::ADD) {
12637 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12638 Offset += C->getZExtValue();
12639 Op = Op.getOperand(0);
12642 } else if (Op.getOpcode() == ISD::SUB) {
12643 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12644 Offset += -C->getZExtValue();
12645 Op = Op.getOperand(0);
12650 // Otherwise, this isn't something we can handle, reject it.
12654 const GlobalValue *GV = GA->getGlobal();
12655 // If we require an extra load to get this address, as in PIC mode, we
12656 // can't accept it.
12657 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12658 getTargetMachine())))
12661 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12662 GA->getValueType(0), Offset);
12667 if (Result.getNode()) {
12668 Ops.push_back(Result);
12671 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12674 std::vector<unsigned> X86TargetLowering::
12675 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12677 if (Constraint.size() == 1) {
12678 // FIXME: not handling fp-stack yet!
12679 switch (Constraint[0]) { // GCC X86 Constraint Letters
12680 default: break; // Unknown constraint letter
12681 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12682 if (Subtarget->is64Bit()) {
12683 if (VT == MVT::i32)
12684 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12685 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12686 X86::R10D,X86::R11D,X86::R12D,
12687 X86::R13D,X86::R14D,X86::R15D,
12688 X86::EBP, X86::ESP, 0);
12689 else if (VT == MVT::i16)
12690 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
12691 X86::SI, X86::DI, X86::R8W,X86::R9W,
12692 X86::R10W,X86::R11W,X86::R12W,
12693 X86::R13W,X86::R14W,X86::R15W,
12694 X86::BP, X86::SP, 0);
12695 else if (VT == MVT::i8)
12696 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
12697 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12698 X86::R10B,X86::R11B,X86::R12B,
12699 X86::R13B,X86::R14B,X86::R15B,
12700 X86::BPL, X86::SPL, 0);
12702 else if (VT == MVT::i64)
12703 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12704 X86::RSI, X86::RDI, X86::R8, X86::R9,
12705 X86::R10, X86::R11, X86::R12,
12706 X86::R13, X86::R14, X86::R15,
12707 X86::RBP, X86::RSP, 0);
12711 // 32-bit fallthrough
12712 case 'Q': // Q_REGS
12713 if (VT == MVT::i32)
12714 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12715 else if (VT == MVT::i16)
12716 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12717 else if (VT == MVT::i8)
12718 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12719 else if (VT == MVT::i64)
12720 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12725 return std::vector<unsigned>();
12728 std::pair<unsigned, const TargetRegisterClass*>
12729 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12731 // First, see if this is a constraint that directly corresponds to an LLVM
12733 if (Constraint.size() == 1) {
12734 // GCC Constraint Letters
12735 switch (Constraint[0]) {
12737 case 'r': // GENERAL_REGS
12738 case 'l': // INDEX_REGS
12740 return std::make_pair(0U, X86::GR8RegisterClass);
12741 if (VT == MVT::i16)
12742 return std::make_pair(0U, X86::GR16RegisterClass);
12743 if (VT == MVT::i32 || !Subtarget->is64Bit())
12744 return std::make_pair(0U, X86::GR32RegisterClass);
12745 return std::make_pair(0U, X86::GR64RegisterClass);
12746 case 'R': // LEGACY_REGS
12748 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12749 if (VT == MVT::i16)
12750 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12751 if (VT == MVT::i32 || !Subtarget->is64Bit())
12752 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12753 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12754 case 'f': // FP Stack registers.
12755 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12756 // value to the correct fpstack register class.
12757 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12758 return std::make_pair(0U, X86::RFP32RegisterClass);
12759 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12760 return std::make_pair(0U, X86::RFP64RegisterClass);
12761 return std::make_pair(0U, X86::RFP80RegisterClass);
12762 case 'y': // MMX_REGS if MMX allowed.
12763 if (!Subtarget->hasMMX()) break;
12764 return std::make_pair(0U, X86::VR64RegisterClass);
12765 case 'Y': // SSE_REGS if SSE2 allowed
12766 if (!Subtarget->hasXMMInt()) break;
12768 case 'x': // SSE_REGS if SSE1 allowed
12769 if (!Subtarget->hasXMM()) break;
12771 switch (VT.getSimpleVT().SimpleTy) {
12773 // Scalar SSE types.
12776 return std::make_pair(0U, X86::FR32RegisterClass);
12779 return std::make_pair(0U, X86::FR64RegisterClass);
12787 return std::make_pair(0U, X86::VR128RegisterClass);
12793 // Use the default implementation in TargetLowering to convert the register
12794 // constraint into a member of a register class.
12795 std::pair<unsigned, const TargetRegisterClass*> Res;
12796 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12798 // Not found as a standard register?
12799 if (Res.second == 0) {
12800 // Map st(0) -> st(7) -> ST0
12801 if (Constraint.size() == 7 && Constraint[0] == '{' &&
12802 tolower(Constraint[1]) == 's' &&
12803 tolower(Constraint[2]) == 't' &&
12804 Constraint[3] == '(' &&
12805 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12806 Constraint[5] == ')' &&
12807 Constraint[6] == '}') {
12809 Res.first = X86::ST0+Constraint[4]-'0';
12810 Res.second = X86::RFP80RegisterClass;
12814 // GCC allows "st(0)" to be called just plain "st".
12815 if (StringRef("{st}").equals_lower(Constraint)) {
12816 Res.first = X86::ST0;
12817 Res.second = X86::RFP80RegisterClass;
12822 if (StringRef("{flags}").equals_lower(Constraint)) {
12823 Res.first = X86::EFLAGS;
12824 Res.second = X86::CCRRegisterClass;
12828 // 'A' means EAX + EDX.
12829 if (Constraint == "A") {
12830 Res.first = X86::EAX;
12831 Res.second = X86::GR32_ADRegisterClass;
12837 // Otherwise, check to see if this is a register class of the wrong value
12838 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12839 // turn into {ax},{dx}.
12840 if (Res.second->hasType(VT))
12841 return Res; // Correct type already, nothing to do.
12843 // All of the single-register GCC register classes map their values onto
12844 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
12845 // really want an 8-bit or 32-bit register, map to the appropriate register
12846 // class and return the appropriate register.
12847 if (Res.second == X86::GR16RegisterClass) {
12848 if (VT == MVT::i8) {
12849 unsigned DestReg = 0;
12850 switch (Res.first) {
12852 case X86::AX: DestReg = X86::AL; break;
12853 case X86::DX: DestReg = X86::DL; break;
12854 case X86::CX: DestReg = X86::CL; break;
12855 case X86::BX: DestReg = X86::BL; break;
12858 Res.first = DestReg;
12859 Res.second = X86::GR8RegisterClass;
12861 } else if (VT == MVT::i32) {
12862 unsigned DestReg = 0;
12863 switch (Res.first) {
12865 case X86::AX: DestReg = X86::EAX; break;
12866 case X86::DX: DestReg = X86::EDX; break;
12867 case X86::CX: DestReg = X86::ECX; break;
12868 case X86::BX: DestReg = X86::EBX; break;
12869 case X86::SI: DestReg = X86::ESI; break;
12870 case X86::DI: DestReg = X86::EDI; break;
12871 case X86::BP: DestReg = X86::EBP; break;
12872 case X86::SP: DestReg = X86::ESP; break;
12875 Res.first = DestReg;
12876 Res.second = X86::GR32RegisterClass;
12878 } else if (VT == MVT::i64) {
12879 unsigned DestReg = 0;
12880 switch (Res.first) {
12882 case X86::AX: DestReg = X86::RAX; break;
12883 case X86::DX: DestReg = X86::RDX; break;
12884 case X86::CX: DestReg = X86::RCX; break;
12885 case X86::BX: DestReg = X86::RBX; break;
12886 case X86::SI: DestReg = X86::RSI; break;
12887 case X86::DI: DestReg = X86::RDI; break;
12888 case X86::BP: DestReg = X86::RBP; break;
12889 case X86::SP: DestReg = X86::RSP; break;
12892 Res.first = DestReg;
12893 Res.second = X86::GR64RegisterClass;
12896 } else if (Res.second == X86::FR32RegisterClass ||
12897 Res.second == X86::FR64RegisterClass ||
12898 Res.second == X86::VR128RegisterClass) {
12899 // Handle references to XMM physical registers that got mapped into the
12900 // wrong class. This can happen with constraints like {xmm0} where the
12901 // target independent register mapper will just pick the first match it can
12902 // find, ignoring the required type.
12903 if (VT == MVT::f32)
12904 Res.second = X86::FR32RegisterClass;
12905 else if (VT == MVT::f64)
12906 Res.second = X86::FR64RegisterClass;
12907 else if (X86::VR128RegisterClass->hasType(VT))
12908 Res.second = X86::VR128RegisterClass;