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::SREM_I64, "_allrem");
239 setLibcallName(RTLIB::UREM_I64, "_aullrem");
240 setLibcallName(RTLIB::MUL_I64, "_allmul");
241 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
242 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
243 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
244 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
245 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
246 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
247 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
248 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
249 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
252 if (Subtarget->isTargetDarwin()) {
253 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
254 setUseUnderscoreSetJmp(false);
255 setUseUnderscoreLongJmp(false);
256 } else if (Subtarget->isTargetMingw()) {
257 // MS runtime is weird: it exports _setjmp, but longjmp!
258 setUseUnderscoreSetJmp(true);
259 setUseUnderscoreLongJmp(false);
261 setUseUnderscoreSetJmp(true);
262 setUseUnderscoreLongJmp(true);
265 // Set up the register classes.
266 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
267 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
268 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
269 if (Subtarget->is64Bit())
270 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
272 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
274 // We don't accept any truncstore of integer registers.
275 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
276 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
277 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
278 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
279 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
280 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
282 // SETOEQ and SETUNE require checking two conditions.
283 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
284 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
285 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
286 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
287 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
288 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
290 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
292 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
293 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
294 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
296 if (Subtarget->is64Bit()) {
297 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
298 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
299 } else if (!UseSoftFloat) {
300 // We have an algorithm for SSE2->double, and we turn this into a
301 // 64-bit FILD followed by conditional FADD for other targets.
302 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
303 // We have an algorithm for SSE2, and we turn this into a 64-bit
304 // FILD for other targets.
305 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
308 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
310 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
311 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
314 // SSE has no i16 to fp conversion, only i32
315 if (X86ScalarSSEf32) {
316 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
317 // f32 and f64 cases are Legal, f80 case is not
318 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
320 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
321 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
324 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
325 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
328 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
329 // are Legal, f80 is custom lowered.
330 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
331 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
333 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
335 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
336 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
338 if (X86ScalarSSEf32) {
339 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
340 // f32 and f64 cases are Legal, f80 case is not
341 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
343 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
344 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
347 // Handle FP_TO_UINT by promoting the destination to a larger signed
349 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
350 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
351 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
353 if (Subtarget->is64Bit()) {
354 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
355 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
356 } else if (!UseSoftFloat) {
357 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
358 // Expand FP_TO_UINT into a select.
359 // FIXME: We would like to use a Custom expander here eventually to do
360 // the optimal thing for SSE vs. the default expansion in the legalizer.
361 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
363 // With SSE3 we can use fisttpll to convert to a signed i64; without
364 // SSE, we're stuck with a fistpll.
365 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
368 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
369 if (!X86ScalarSSEf64) {
370 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
371 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
372 if (Subtarget->is64Bit()) {
373 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
374 // Without SSE, i64->f64 goes through memory.
375 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
379 // Scalar integer divide and remainder are lowered to use operations that
380 // produce two results, to match the available instructions. This exposes
381 // the two-result form to trivial CSE, which is able to combine x/y and x%y
382 // into a single instruction.
384 // Scalar integer multiply-high is also lowered to use two-result
385 // operations, to match the available instructions. However, plain multiply
386 // (low) operations are left as Legal, as there are single-result
387 // instructions for this in x86. Using the two-result multiply instructions
388 // when both high and low results are needed must be arranged by dagcombine.
389 for (unsigned i = 0, e = 4; i != e; ++i) {
391 setOperationAction(ISD::MULHS, VT, Expand);
392 setOperationAction(ISD::MULHU, VT, Expand);
393 setOperationAction(ISD::SDIV, VT, Expand);
394 setOperationAction(ISD::UDIV, VT, Expand);
395 setOperationAction(ISD::SREM, VT, Expand);
396 setOperationAction(ISD::UREM, VT, Expand);
398 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
399 setOperationAction(ISD::ADDC, VT, Custom);
400 setOperationAction(ISD::ADDE, VT, Custom);
401 setOperationAction(ISD::SUBC, VT, Custom);
402 setOperationAction(ISD::SUBE, VT, Custom);
405 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
406 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
407 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
408 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
409 if (Subtarget->is64Bit())
410 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
411 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
412 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
413 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
414 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
415 setOperationAction(ISD::FREM , MVT::f32 , Expand);
416 setOperationAction(ISD::FREM , MVT::f64 , Expand);
417 setOperationAction(ISD::FREM , MVT::f80 , Expand);
418 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
420 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
421 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
422 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
423 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
424 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
425 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
426 if (Subtarget->is64Bit()) {
427 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
428 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
431 if (Subtarget->hasPOPCNT()) {
432 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
434 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
435 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
436 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
437 if (Subtarget->is64Bit())
438 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
441 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
442 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
444 // These should be promoted to a larger select which is supported.
445 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
446 // X86 wants to expand cmov itself.
447 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
448 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
449 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
450 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
451 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
452 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
453 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
454 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
455 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
456 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
457 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
458 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
459 if (Subtarget->is64Bit()) {
460 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
461 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
463 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
466 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
467 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
468 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
469 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
470 if (Subtarget->is64Bit())
471 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
472 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
473 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
474 if (Subtarget->is64Bit()) {
475 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
476 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
477 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
478 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
479 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
481 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
482 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
483 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
484 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
485 if (Subtarget->is64Bit()) {
486 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
487 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
488 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
491 if (Subtarget->hasXMM())
492 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
494 // We may not have a libcall for MEMBARRIER so we should lower this.
495 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
497 // On X86 and X86-64, atomic operations are lowered to locked instructions.
498 // Locked instructions, in turn, have implicit fence semantics (all memory
499 // operations are flushed before issuing the locked instruction, and they
500 // are not buffered), so we can fold away the common pattern of
501 // fence-atomic-fence.
502 setShouldFoldAtomicFences(true);
504 // Expand certain atomics
505 for (unsigned i = 0, e = 4; i != e; ++i) {
507 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
508 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
511 if (!Subtarget->is64Bit()) {
512 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
513 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
514 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
515 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
516 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
517 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
518 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
521 // FIXME - use subtarget debug flags
522 if (!Subtarget->isTargetDarwin() &&
523 !Subtarget->isTargetELF() &&
524 !Subtarget->isTargetCygMing()) {
525 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
528 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
529 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
530 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
531 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
532 if (Subtarget->is64Bit()) {
533 setExceptionPointerRegister(X86::RAX);
534 setExceptionSelectorRegister(X86::RDX);
536 setExceptionPointerRegister(X86::EAX);
537 setExceptionSelectorRegister(X86::EDX);
539 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
540 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
542 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
544 setOperationAction(ISD::TRAP, MVT::Other, Legal);
546 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
547 setOperationAction(ISD::VASTART , MVT::Other, Custom);
548 setOperationAction(ISD::VAEND , MVT::Other, Expand);
549 if (Subtarget->is64Bit()) {
550 setOperationAction(ISD::VAARG , MVT::Other, Custom);
551 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
553 setOperationAction(ISD::VAARG , MVT::Other, Expand);
554 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
557 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
558 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
559 setOperationAction(ISD::DYNAMIC_STACKALLOC,
560 (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
561 (Subtarget->isTargetCOFF()
562 && !Subtarget->isTargetEnvMacho()
565 if (!UseSoftFloat && X86ScalarSSEf64) {
566 // f32 and f64 use SSE.
567 // Set up the FP register classes.
568 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
569 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
571 // Use ANDPD to simulate FABS.
572 setOperationAction(ISD::FABS , MVT::f64, Custom);
573 setOperationAction(ISD::FABS , MVT::f32, Custom);
575 // Use XORP to simulate FNEG.
576 setOperationAction(ISD::FNEG , MVT::f64, Custom);
577 setOperationAction(ISD::FNEG , MVT::f32, Custom);
579 // Use ANDPD and ORPD to simulate FCOPYSIGN.
580 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
581 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
583 // Lower this to FGETSIGNx86 plus an AND.
584 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
585 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
587 // We don't support sin/cos/fmod
588 setOperationAction(ISD::FSIN , MVT::f64, Expand);
589 setOperationAction(ISD::FCOS , MVT::f64, Expand);
590 setOperationAction(ISD::FSIN , MVT::f32, Expand);
591 setOperationAction(ISD::FCOS , MVT::f32, Expand);
593 // Expand FP immediates into loads from the stack, except for the special
595 addLegalFPImmediate(APFloat(+0.0)); // xorpd
596 addLegalFPImmediate(APFloat(+0.0f)); // xorps
597 } else if (!UseSoftFloat && X86ScalarSSEf32) {
598 // Use SSE for f32, x87 for f64.
599 // Set up the FP register classes.
600 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
601 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
603 // Use ANDPS to simulate FABS.
604 setOperationAction(ISD::FABS , MVT::f32, Custom);
606 // Use XORP to simulate FNEG.
607 setOperationAction(ISD::FNEG , MVT::f32, Custom);
609 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
611 // Use ANDPS and ORPS to simulate FCOPYSIGN.
612 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
613 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
615 // We don't support sin/cos/fmod
616 setOperationAction(ISD::FSIN , MVT::f32, Expand);
617 setOperationAction(ISD::FCOS , MVT::f32, Expand);
619 // Special cases we handle for FP constants.
620 addLegalFPImmediate(APFloat(+0.0f)); // xorps
621 addLegalFPImmediate(APFloat(+0.0)); // FLD0
622 addLegalFPImmediate(APFloat(+1.0)); // FLD1
623 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
624 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
627 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
628 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
630 } else if (!UseSoftFloat) {
631 // f32 and f64 in x87.
632 // Set up the FP register classes.
633 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
634 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
636 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
637 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
638 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
639 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
642 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
643 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
645 addLegalFPImmediate(APFloat(+0.0)); // FLD0
646 addLegalFPImmediate(APFloat(+1.0)); // FLD1
647 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
648 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
649 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
650 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
651 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
652 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
655 // We don't support FMA.
656 setOperationAction(ISD::FMA, MVT::f64, Expand);
657 setOperationAction(ISD::FMA, MVT::f32, Expand);
659 // Long double always uses X87.
661 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
662 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
663 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
665 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
666 addLegalFPImmediate(TmpFlt); // FLD0
668 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
671 APFloat TmpFlt2(+1.0);
672 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
674 addLegalFPImmediate(TmpFlt2); // FLD1
675 TmpFlt2.changeSign();
676 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
680 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
681 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
684 setOperationAction(ISD::FMA, MVT::f80, Expand);
687 // Always use a library call for pow.
688 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
689 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
690 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
692 setOperationAction(ISD::FLOG, MVT::f80, Expand);
693 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
694 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
695 setOperationAction(ISD::FEXP, MVT::f80, Expand);
696 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
698 // First set operation action for all vector types to either promote
699 // (for widening) or expand (for scalarization). Then we will selectively
700 // turn on ones that can be effectively codegen'd.
701 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
702 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
703 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
704 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
705 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
718 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
720 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
721 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
745 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
746 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
747 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
748 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
749 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
750 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
751 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
752 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
753 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
754 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
755 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
756 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
757 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
758 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
759 setTruncStoreAction((MVT::SimpleValueType)VT,
760 (MVT::SimpleValueType)InnerVT, Expand);
761 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
762 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
763 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
766 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
767 // with -msoft-float, disable use of MMX as well.
768 if (!UseSoftFloat && Subtarget->hasMMX()) {
769 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
770 // No operations on x86mmx supported, everything uses intrinsics.
773 // MMX-sized vectors (other than x86mmx) are expected to be expanded
774 // into smaller operations.
775 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
776 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
777 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
778 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
779 setOperationAction(ISD::AND, MVT::v8i8, Expand);
780 setOperationAction(ISD::AND, MVT::v4i16, Expand);
781 setOperationAction(ISD::AND, MVT::v2i32, Expand);
782 setOperationAction(ISD::AND, MVT::v1i64, Expand);
783 setOperationAction(ISD::OR, MVT::v8i8, Expand);
784 setOperationAction(ISD::OR, MVT::v4i16, Expand);
785 setOperationAction(ISD::OR, MVT::v2i32, Expand);
786 setOperationAction(ISD::OR, MVT::v1i64, Expand);
787 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
788 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
789 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
790 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
791 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
792 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
793 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
794 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
795 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
796 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
797 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
798 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
799 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
800 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
801 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
802 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
803 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
805 if (!UseSoftFloat && Subtarget->hasXMM()) {
806 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
808 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
809 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
810 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
811 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
812 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
813 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
814 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
815 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
816 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
817 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
818 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
819 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
822 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
823 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
825 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
826 // registers cannot be used even for integer operations.
827 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
828 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
829 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
830 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
832 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
833 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
834 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
835 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
836 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
837 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
838 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
839 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
840 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
841 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
842 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
843 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
844 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
845 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
846 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
847 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
849 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
850 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
851 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
852 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
854 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
855 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
856 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
857 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
858 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
860 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
861 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
862 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
863 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
864 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
866 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
867 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
868 EVT VT = (MVT::SimpleValueType)i;
869 // Do not attempt to custom lower non-power-of-2 vectors
870 if (!isPowerOf2_32(VT.getVectorNumElements()))
872 // Do not attempt to custom lower non-128-bit vectors
873 if (!VT.is128BitVector())
875 setOperationAction(ISD::BUILD_VECTOR,
876 VT.getSimpleVT().SimpleTy, Custom);
877 setOperationAction(ISD::VECTOR_SHUFFLE,
878 VT.getSimpleVT().SimpleTy, Custom);
879 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
880 VT.getSimpleVT().SimpleTy, Custom);
883 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
884 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
885 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
886 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
887 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
888 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
890 if (Subtarget->is64Bit()) {
891 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
892 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
895 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
896 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
897 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
900 // Do not attempt to promote non-128-bit vectors
901 if (!VT.is128BitVector())
904 setOperationAction(ISD::AND, SVT, Promote);
905 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
906 setOperationAction(ISD::OR, SVT, Promote);
907 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
908 setOperationAction(ISD::XOR, SVT, Promote);
909 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
910 setOperationAction(ISD::LOAD, SVT, Promote);
911 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
912 setOperationAction(ISD::SELECT, SVT, Promote);
913 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
916 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
918 // Custom lower v2i64 and v2f64 selects.
919 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
920 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
921 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
922 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
924 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
925 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
928 if (Subtarget->hasSSE41()) {
929 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
930 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
931 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
932 setOperationAction(ISD::FRINT, MVT::f32, Legal);
933 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
934 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
935 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
936 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
937 setOperationAction(ISD::FRINT, MVT::f64, Legal);
938 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
940 // FIXME: Do we need to handle scalar-to-vector here?
941 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
943 // Can turn SHL into an integer multiply.
944 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
945 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
947 // i8 and i16 vectors are custom , because the source register and source
948 // source memory operand types are not the same width. f32 vectors are
949 // custom since the immediate controlling the insert encodes additional
951 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
952 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
953 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
954 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
956 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
957 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
958 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
959 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
961 if (Subtarget->is64Bit()) {
962 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
963 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
967 if (Subtarget->hasSSE2()) {
968 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
969 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
970 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
972 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
973 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
974 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
976 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
977 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
980 if (Subtarget->hasSSE42())
981 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
983 if (!UseSoftFloat && Subtarget->hasAVX()) {
984 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
985 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
986 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
987 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
988 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
990 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
991 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
992 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
993 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
995 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
996 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
997 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
998 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
999 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1000 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1002 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1003 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1004 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1005 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1006 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1007 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1009 // Custom lower build_vector, vector_shuffle, scalar_to_vector,
1010 // insert_vector_elt extract_subvector and extract_vector_elt for
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())
1018 || (MVT(VT).getSizeInBits() < 256))
1020 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1021 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1022 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1023 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1024 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1026 // Custom-lower insert_subvector and extract_subvector based on
1028 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1029 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1031 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1032 // Do not attempt to custom lower non-256-bit vectors
1033 if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1036 if (MVT(VT).getSizeInBits() == 128) {
1037 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1039 else if (MVT(VT).getSizeInBits() == 256) {
1040 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1044 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1045 // Don't promote loads because we need them for VPERM vector index versions.
1047 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1048 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1050 if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1051 || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1053 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
1054 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v4i64);
1055 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
1056 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v4i64);
1057 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
1058 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v4i64);
1059 //setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
1060 //AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v4i64);
1061 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1062 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1067 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1068 // of this type with custom code.
1069 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1070 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1071 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1074 // We want to custom lower some of our intrinsics.
1075 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1078 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1079 // handle type legalization for these operations here.
1081 // FIXME: We really should do custom legalization for addition and
1082 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1083 // than generic legalization for 64-bit multiplication-with-overflow, though.
1084 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1085 // Add/Sub/Mul with overflow operations are custom lowered.
1087 setOperationAction(ISD::SADDO, VT, Custom);
1088 setOperationAction(ISD::UADDO, VT, Custom);
1089 setOperationAction(ISD::SSUBO, VT, Custom);
1090 setOperationAction(ISD::USUBO, VT, Custom);
1091 setOperationAction(ISD::SMULO, VT, Custom);
1092 setOperationAction(ISD::UMULO, VT, Custom);
1095 // There are no 8-bit 3-address imul/mul instructions
1096 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1097 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1099 if (!Subtarget->is64Bit()) {
1100 // These libcalls are not available in 32-bit.
1101 setLibcallName(RTLIB::SHL_I128, 0);
1102 setLibcallName(RTLIB::SRL_I128, 0);
1103 setLibcallName(RTLIB::SRA_I128, 0);
1106 // We have target-specific dag combine patterns for the following nodes:
1107 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1108 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1109 setTargetDAGCombine(ISD::BUILD_VECTOR);
1110 setTargetDAGCombine(ISD::SELECT);
1111 setTargetDAGCombine(ISD::SHL);
1112 setTargetDAGCombine(ISD::SRA);
1113 setTargetDAGCombine(ISD::SRL);
1114 setTargetDAGCombine(ISD::OR);
1115 setTargetDAGCombine(ISD::AND);
1116 setTargetDAGCombine(ISD::ADD);
1117 setTargetDAGCombine(ISD::SUB);
1118 setTargetDAGCombine(ISD::STORE);
1119 setTargetDAGCombine(ISD::ZERO_EXTEND);
1120 setTargetDAGCombine(ISD::SINT_TO_FP);
1121 if (Subtarget->is64Bit())
1122 setTargetDAGCombine(ISD::MUL);
1124 computeRegisterProperties();
1126 // On Darwin, -Os means optimize for size without hurting performance,
1127 // do not reduce the limit.
1128 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1129 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1130 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1131 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1132 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1133 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1134 setPrefLoopAlignment(16);
1135 benefitFromCodePlacementOpt = true;
1137 setPrefFunctionAlignment(4);
1141 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1146 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1147 /// the desired ByVal argument alignment.
1148 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1151 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1152 if (VTy->getBitWidth() == 128)
1154 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1155 unsigned EltAlign = 0;
1156 getMaxByValAlign(ATy->getElementType(), EltAlign);
1157 if (EltAlign > MaxAlign)
1158 MaxAlign = EltAlign;
1159 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1160 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1161 unsigned EltAlign = 0;
1162 getMaxByValAlign(STy->getElementType(i), EltAlign);
1163 if (EltAlign > MaxAlign)
1164 MaxAlign = EltAlign;
1172 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1173 /// function arguments in the caller parameter area. For X86, aggregates
1174 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1175 /// are at 4-byte boundaries.
1176 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1177 if (Subtarget->is64Bit()) {
1178 // Max of 8 and alignment of type.
1179 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1186 if (Subtarget->hasXMM())
1187 getMaxByValAlign(Ty, Align);
1191 /// getOptimalMemOpType - Returns the target specific optimal type for load
1192 /// and store operations as a result of memset, memcpy, and memmove
1193 /// lowering. If DstAlign is zero that means it's safe to destination
1194 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1195 /// means there isn't a need to check it against alignment requirement,
1196 /// probably because the source does not need to be loaded. If
1197 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1198 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1199 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1200 /// constant so it does not need to be loaded.
1201 /// It returns EVT::Other if the type should be determined using generic
1202 /// target-independent logic.
1204 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1205 unsigned DstAlign, unsigned SrcAlign,
1206 bool NonScalarIntSafe,
1208 MachineFunction &MF) const {
1209 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1210 // linux. This is because the stack realignment code can't handle certain
1211 // cases like PR2962. This should be removed when PR2962 is fixed.
1212 const Function *F = MF.getFunction();
1213 if (NonScalarIntSafe &&
1214 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1216 (Subtarget->isUnalignedMemAccessFast() ||
1217 ((DstAlign == 0 || DstAlign >= 16) &&
1218 (SrcAlign == 0 || SrcAlign >= 16))) &&
1219 Subtarget->getStackAlignment() >= 16) {
1220 if (Subtarget->hasSSE2())
1222 if (Subtarget->hasSSE1())
1224 } else if (!MemcpyStrSrc && Size >= 8 &&
1225 !Subtarget->is64Bit() &&
1226 Subtarget->getStackAlignment() >= 8 &&
1227 Subtarget->hasXMMInt()) {
1228 // Do not use f64 to lower memcpy if source is string constant. It's
1229 // better to use i32 to avoid the loads.
1233 if (Subtarget->is64Bit() && Size >= 8)
1238 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1239 /// current function. The returned value is a member of the
1240 /// MachineJumpTableInfo::JTEntryKind enum.
1241 unsigned X86TargetLowering::getJumpTableEncoding() const {
1242 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1244 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1245 Subtarget->isPICStyleGOT())
1246 return MachineJumpTableInfo::EK_Custom32;
1248 // Otherwise, use the normal jump table encoding heuristics.
1249 return TargetLowering::getJumpTableEncoding();
1253 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1254 const MachineBasicBlock *MBB,
1255 unsigned uid,MCContext &Ctx) const{
1256 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1257 Subtarget->isPICStyleGOT());
1258 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1260 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1261 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1264 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1266 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1267 SelectionDAG &DAG) const {
1268 if (!Subtarget->is64Bit())
1269 // This doesn't have DebugLoc associated with it, but is not really the
1270 // same as a Register.
1271 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1275 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1276 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1278 const MCExpr *X86TargetLowering::
1279 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1280 MCContext &Ctx) const {
1281 // X86-64 uses RIP relative addressing based on the jump table label.
1282 if (Subtarget->isPICStyleRIPRel())
1283 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1285 // Otherwise, the reference is relative to the PIC base.
1286 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1289 // FIXME: Why this routine is here? Move to RegInfo!
1290 std::pair<const TargetRegisterClass*, uint8_t>
1291 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1292 const TargetRegisterClass *RRC = 0;
1294 switch (VT.getSimpleVT().SimpleTy) {
1296 return TargetLowering::findRepresentativeClass(VT);
1297 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1298 RRC = (Subtarget->is64Bit()
1299 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1302 RRC = X86::VR64RegisterClass;
1304 case MVT::f32: case MVT::f64:
1305 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1306 case MVT::v4f32: case MVT::v2f64:
1307 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1309 RRC = X86::VR128RegisterClass;
1312 return std::make_pair(RRC, Cost);
1315 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1316 unsigned &Offset) const {
1317 if (!Subtarget->isTargetLinux())
1320 if (Subtarget->is64Bit()) {
1321 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1323 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1336 //===----------------------------------------------------------------------===//
1337 // Return Value Calling Convention Implementation
1338 //===----------------------------------------------------------------------===//
1340 #include "X86GenCallingConv.inc"
1343 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1344 MachineFunction &MF, bool isVarArg,
1345 const SmallVectorImpl<ISD::OutputArg> &Outs,
1346 LLVMContext &Context) const {
1347 SmallVector<CCValAssign, 16> RVLocs;
1348 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1350 return CCInfo.CheckReturn(Outs, RetCC_X86);
1354 X86TargetLowering::LowerReturn(SDValue Chain,
1355 CallingConv::ID CallConv, bool isVarArg,
1356 const SmallVectorImpl<ISD::OutputArg> &Outs,
1357 const SmallVectorImpl<SDValue> &OutVals,
1358 DebugLoc dl, SelectionDAG &DAG) const {
1359 MachineFunction &MF = DAG.getMachineFunction();
1360 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1362 SmallVector<CCValAssign, 16> RVLocs;
1363 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1364 RVLocs, *DAG.getContext());
1365 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1367 // Add the regs to the liveout set for the function.
1368 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1369 for (unsigned i = 0; i != RVLocs.size(); ++i)
1370 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1371 MRI.addLiveOut(RVLocs[i].getLocReg());
1375 SmallVector<SDValue, 6> RetOps;
1376 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1377 // Operand #1 = Bytes To Pop
1378 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1381 // Copy the result values into the output registers.
1382 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1383 CCValAssign &VA = RVLocs[i];
1384 assert(VA.isRegLoc() && "Can only return in registers!");
1385 SDValue ValToCopy = OutVals[i];
1386 EVT ValVT = ValToCopy.getValueType();
1388 // If this is x86-64, and we disabled SSE, we can't return FP values,
1389 // or SSE or MMX vectors.
1390 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1391 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1392 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1393 report_fatal_error("SSE register return with SSE disabled");
1395 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1396 // llvm-gcc has never done it right and no one has noticed, so this
1397 // should be OK for now.
1398 if (ValVT == MVT::f64 &&
1399 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1400 report_fatal_error("SSE2 register return with SSE2 disabled");
1402 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1403 // the RET instruction and handled by the FP Stackifier.
1404 if (VA.getLocReg() == X86::ST0 ||
1405 VA.getLocReg() == X86::ST1) {
1406 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1407 // change the value to the FP stack register class.
1408 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1409 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1410 RetOps.push_back(ValToCopy);
1411 // Don't emit a copytoreg.
1415 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1416 // which is returned in RAX / RDX.
1417 if (Subtarget->is64Bit()) {
1418 if (ValVT == MVT::x86mmx) {
1419 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1420 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1421 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1423 // If we don't have SSE2 available, convert to v4f32 so the generated
1424 // register is legal.
1425 if (!Subtarget->hasSSE2())
1426 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1431 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1432 Flag = Chain.getValue(1);
1435 // The x86-64 ABI for returning structs by value requires that we copy
1436 // the sret argument into %rax for the return. We saved the argument into
1437 // a virtual register in the entry block, so now we copy the value out
1439 if (Subtarget->is64Bit() &&
1440 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1441 MachineFunction &MF = DAG.getMachineFunction();
1442 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1443 unsigned Reg = FuncInfo->getSRetReturnReg();
1445 "SRetReturnReg should have been set in LowerFormalArguments().");
1446 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1448 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1449 Flag = Chain.getValue(1);
1451 // RAX now acts like a return value.
1452 MRI.addLiveOut(X86::RAX);
1455 RetOps[0] = Chain; // Update chain.
1457 // Add the flag if we have it.
1459 RetOps.push_back(Flag);
1461 return DAG.getNode(X86ISD::RET_FLAG, dl,
1462 MVT::Other, &RetOps[0], RetOps.size());
1465 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1466 if (N->getNumValues() != 1)
1468 if (!N->hasNUsesOfValue(1, 0))
1471 SDNode *Copy = *N->use_begin();
1472 if (Copy->getOpcode() != ISD::CopyToReg &&
1473 Copy->getOpcode() != ISD::FP_EXTEND)
1476 bool HasRet = false;
1477 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1479 if (UI->getOpcode() != X86ISD::RET_FLAG)
1488 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1489 ISD::NodeType ExtendKind) const {
1491 // TODO: Is this also valid on 32-bit?
1492 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1493 ReturnMVT = MVT::i8;
1495 ReturnMVT = MVT::i32;
1497 EVT MinVT = getRegisterType(Context, ReturnMVT);
1498 return VT.bitsLT(MinVT) ? MinVT : VT;
1501 /// LowerCallResult - Lower the result values of a call into the
1502 /// appropriate copies out of appropriate physical registers.
1505 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1506 CallingConv::ID CallConv, bool isVarArg,
1507 const SmallVectorImpl<ISD::InputArg> &Ins,
1508 DebugLoc dl, SelectionDAG &DAG,
1509 SmallVectorImpl<SDValue> &InVals) const {
1511 // Assign locations to each value returned by this call.
1512 SmallVector<CCValAssign, 16> RVLocs;
1513 bool Is64Bit = Subtarget->is64Bit();
1514 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1515 getTargetMachine(), RVLocs, *DAG.getContext());
1516 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1518 // Copy all of the result registers out of their specified physreg.
1519 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1520 CCValAssign &VA = RVLocs[i];
1521 EVT CopyVT = VA.getValVT();
1523 // If this is x86-64, and we disabled SSE, we can't return FP values
1524 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1525 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1526 report_fatal_error("SSE register return with SSE disabled");
1531 // If this is a call to a function that returns an fp value on the floating
1532 // point stack, we must guarantee the the value is popped from the stack, so
1533 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1534 // if the return value is not used. We use the FpPOP_RETVAL instruction
1536 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1537 // If we prefer to use the value in xmm registers, copy it out as f80 and
1538 // use a truncate to move it from fp stack reg to xmm reg.
1539 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1540 SDValue Ops[] = { Chain, InFlag };
1541 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1542 MVT::Other, MVT::Glue, Ops, 2), 1);
1543 Val = Chain.getValue(0);
1545 // Round the f80 to the right size, which also moves it to the appropriate
1547 if (CopyVT != VA.getValVT())
1548 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1549 // This truncation won't change the value.
1550 DAG.getIntPtrConstant(1));
1552 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1553 CopyVT, InFlag).getValue(1);
1554 Val = Chain.getValue(0);
1556 InFlag = Chain.getValue(2);
1557 InVals.push_back(Val);
1564 //===----------------------------------------------------------------------===//
1565 // C & StdCall & Fast Calling Convention implementation
1566 //===----------------------------------------------------------------------===//
1567 // StdCall calling convention seems to be standard for many Windows' API
1568 // routines and around. It differs from C calling convention just a little:
1569 // callee should clean up the stack, not caller. Symbols should be also
1570 // decorated in some fancy way :) It doesn't support any vector arguments.
1571 // For info on fast calling convention see Fast Calling Convention (tail call)
1572 // implementation LowerX86_32FastCCCallTo.
1574 /// CallIsStructReturn - Determines whether a call uses struct return
1576 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1580 return Outs[0].Flags.isSRet();
1583 /// ArgsAreStructReturn - Determines whether a function uses struct
1584 /// return semantics.
1586 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1590 return Ins[0].Flags.isSRet();
1593 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1594 /// by "Src" to address "Dst" with size and alignment information specified by
1595 /// the specific parameter attribute. The copy will be passed as a byval
1596 /// function parameter.
1598 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1599 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1601 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1603 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1604 /*isVolatile*/false, /*AlwaysInline=*/true,
1605 MachinePointerInfo(), MachinePointerInfo());
1608 /// IsTailCallConvention - Return true if the calling convention is one that
1609 /// supports tail call optimization.
1610 static bool IsTailCallConvention(CallingConv::ID CC) {
1611 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1614 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1615 if (!CI->isTailCall())
1619 CallingConv::ID CalleeCC = CS.getCallingConv();
1620 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1626 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1627 /// a tailcall target by changing its ABI.
1628 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1629 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1633 X86TargetLowering::LowerMemArgument(SDValue Chain,
1634 CallingConv::ID CallConv,
1635 const SmallVectorImpl<ISD::InputArg> &Ins,
1636 DebugLoc dl, SelectionDAG &DAG,
1637 const CCValAssign &VA,
1638 MachineFrameInfo *MFI,
1640 // Create the nodes corresponding to a load from this parameter slot.
1641 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1642 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1643 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1646 // If value is passed by pointer we have address passed instead of the value
1648 if (VA.getLocInfo() == CCValAssign::Indirect)
1649 ValVT = VA.getLocVT();
1651 ValVT = VA.getValVT();
1653 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1654 // changed with more analysis.
1655 // In case of tail call optimization mark all arguments mutable. Since they
1656 // could be overwritten by lowering of arguments in case of a tail call.
1657 if (Flags.isByVal()) {
1658 unsigned Bytes = Flags.getByValSize();
1659 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1660 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1661 return DAG.getFrameIndex(FI, getPointerTy());
1663 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1664 VA.getLocMemOffset(), isImmutable);
1665 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1666 return DAG.getLoad(ValVT, dl, Chain, FIN,
1667 MachinePointerInfo::getFixedStack(FI),
1673 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1674 CallingConv::ID CallConv,
1676 const SmallVectorImpl<ISD::InputArg> &Ins,
1679 SmallVectorImpl<SDValue> &InVals)
1681 MachineFunction &MF = DAG.getMachineFunction();
1682 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1684 const Function* Fn = MF.getFunction();
1685 if (Fn->hasExternalLinkage() &&
1686 Subtarget->isTargetCygMing() &&
1687 Fn->getName() == "main")
1688 FuncInfo->setForceFramePointer(true);
1690 MachineFrameInfo *MFI = MF.getFrameInfo();
1691 bool Is64Bit = Subtarget->is64Bit();
1692 bool IsWin64 = Subtarget->isTargetWin64();
1694 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1695 "Var args not supported with calling convention fastcc or ghc");
1697 // Assign locations to all of the incoming arguments.
1698 SmallVector<CCValAssign, 16> ArgLocs;
1699 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1700 ArgLocs, *DAG.getContext());
1702 // Allocate shadow area for Win64
1704 CCInfo.AllocateStack(32, 8);
1707 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1709 unsigned LastVal = ~0U;
1711 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1712 CCValAssign &VA = ArgLocs[i];
1713 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1715 assert(VA.getValNo() != LastVal &&
1716 "Don't support value assigned to multiple locs yet");
1717 LastVal = VA.getValNo();
1719 if (VA.isRegLoc()) {
1720 EVT RegVT = VA.getLocVT();
1721 TargetRegisterClass *RC = NULL;
1722 if (RegVT == MVT::i32)
1723 RC = X86::GR32RegisterClass;
1724 else if (Is64Bit && RegVT == MVT::i64)
1725 RC = X86::GR64RegisterClass;
1726 else if (RegVT == MVT::f32)
1727 RC = X86::FR32RegisterClass;
1728 else if (RegVT == MVT::f64)
1729 RC = X86::FR64RegisterClass;
1730 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1731 RC = X86::VR256RegisterClass;
1732 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1733 RC = X86::VR128RegisterClass;
1734 else if (RegVT == MVT::x86mmx)
1735 RC = X86::VR64RegisterClass;
1737 llvm_unreachable("Unknown argument type!");
1739 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1740 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1742 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1743 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1745 if (VA.getLocInfo() == CCValAssign::SExt)
1746 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1747 DAG.getValueType(VA.getValVT()));
1748 else if (VA.getLocInfo() == CCValAssign::ZExt)
1749 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1750 DAG.getValueType(VA.getValVT()));
1751 else if (VA.getLocInfo() == CCValAssign::BCvt)
1752 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1754 if (VA.isExtInLoc()) {
1755 // Handle MMX values passed in XMM regs.
1756 if (RegVT.isVector()) {
1757 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1760 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1763 assert(VA.isMemLoc());
1764 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1767 // If value is passed via pointer - do a load.
1768 if (VA.getLocInfo() == CCValAssign::Indirect)
1769 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1770 MachinePointerInfo(), false, false, 0);
1772 InVals.push_back(ArgValue);
1775 // The x86-64 ABI for returning structs by value requires that we copy
1776 // the sret argument into %rax for the return. Save the argument into
1777 // a virtual register so that we can access it from the return points.
1778 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1779 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1780 unsigned Reg = FuncInfo->getSRetReturnReg();
1782 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1783 FuncInfo->setSRetReturnReg(Reg);
1785 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1786 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1789 unsigned StackSize = CCInfo.getNextStackOffset();
1790 // Align stack specially for tail calls.
1791 if (FuncIsMadeTailCallSafe(CallConv))
1792 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1794 // If the function takes variable number of arguments, make a frame index for
1795 // the start of the first vararg value... for expansion of llvm.va_start.
1797 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1798 CallConv != CallingConv::X86_ThisCall)) {
1799 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1802 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1804 // FIXME: We should really autogenerate these arrays
1805 static const unsigned GPR64ArgRegsWin64[] = {
1806 X86::RCX, X86::RDX, X86::R8, X86::R9
1808 static const unsigned GPR64ArgRegs64Bit[] = {
1809 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1811 static const unsigned XMMArgRegs64Bit[] = {
1812 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1813 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1815 const unsigned *GPR64ArgRegs;
1816 unsigned NumXMMRegs = 0;
1819 // The XMM registers which might contain var arg parameters are shadowed
1820 // in their paired GPR. So we only need to save the GPR to their home
1822 TotalNumIntRegs = 4;
1823 GPR64ArgRegs = GPR64ArgRegsWin64;
1825 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1826 GPR64ArgRegs = GPR64ArgRegs64Bit;
1828 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1830 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1833 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1834 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1835 "SSE register cannot be used when SSE is disabled!");
1836 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1837 "SSE register cannot be used when SSE is disabled!");
1838 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1839 // Kernel mode asks for SSE to be disabled, so don't push them
1841 TotalNumXMMRegs = 0;
1844 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1845 // Get to the caller-allocated home save location. Add 8 to account
1846 // for the return address.
1847 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1848 FuncInfo->setRegSaveFrameIndex(
1849 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1850 // Fixup to set vararg frame on shadow area (4 x i64).
1852 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1854 // For X86-64, if there are vararg parameters that are passed via
1855 // registers, then we must store them to their spots on the stack so they
1856 // may be loaded by deferencing the result of va_next.
1857 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1858 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1859 FuncInfo->setRegSaveFrameIndex(
1860 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1864 // Store the integer parameter registers.
1865 SmallVector<SDValue, 8> MemOps;
1866 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1868 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1869 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1870 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1871 DAG.getIntPtrConstant(Offset));
1872 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1873 X86::GR64RegisterClass);
1874 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1876 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1877 MachinePointerInfo::getFixedStack(
1878 FuncInfo->getRegSaveFrameIndex(), Offset),
1880 MemOps.push_back(Store);
1884 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1885 // Now store the XMM (fp + vector) parameter registers.
1886 SmallVector<SDValue, 11> SaveXMMOps;
1887 SaveXMMOps.push_back(Chain);
1889 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1890 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1891 SaveXMMOps.push_back(ALVal);
1893 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1894 FuncInfo->getRegSaveFrameIndex()));
1895 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1896 FuncInfo->getVarArgsFPOffset()));
1898 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1899 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1900 X86::VR128RegisterClass);
1901 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1902 SaveXMMOps.push_back(Val);
1904 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1906 &SaveXMMOps[0], SaveXMMOps.size()));
1909 if (!MemOps.empty())
1910 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1911 &MemOps[0], MemOps.size());
1915 // Some CCs need callee pop.
1916 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1917 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1919 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1920 // If this is an sret function, the return should pop the hidden pointer.
1921 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1922 FuncInfo->setBytesToPopOnReturn(4);
1926 // RegSaveFrameIndex is X86-64 only.
1927 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1928 if (CallConv == CallingConv::X86_FastCall ||
1929 CallConv == CallingConv::X86_ThisCall)
1930 // fastcc functions can't have varargs.
1931 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1938 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1939 SDValue StackPtr, SDValue Arg,
1940 DebugLoc dl, SelectionDAG &DAG,
1941 const CCValAssign &VA,
1942 ISD::ArgFlagsTy Flags) const {
1943 unsigned LocMemOffset = VA.getLocMemOffset();
1944 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1945 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1946 if (Flags.isByVal())
1947 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1949 return DAG.getStore(Chain, dl, Arg, PtrOff,
1950 MachinePointerInfo::getStack(LocMemOffset),
1954 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1955 /// optimization is performed and it is required.
1957 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1958 SDValue &OutRetAddr, SDValue Chain,
1959 bool IsTailCall, bool Is64Bit,
1960 int FPDiff, DebugLoc dl) const {
1961 // Adjust the Return address stack slot.
1962 EVT VT = getPointerTy();
1963 OutRetAddr = getReturnAddressFrameIndex(DAG);
1965 // Load the "old" Return address.
1966 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1968 return SDValue(OutRetAddr.getNode(), 1);
1971 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1972 /// optimization is performed and it is required (FPDiff!=0).
1974 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1975 SDValue Chain, SDValue RetAddrFrIdx,
1976 bool Is64Bit, int FPDiff, DebugLoc dl) {
1977 // Store the return address to the appropriate stack slot.
1978 if (!FPDiff) return Chain;
1979 // Calculate the new stack slot for the return address.
1980 int SlotSize = Is64Bit ? 8 : 4;
1981 int NewReturnAddrFI =
1982 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1983 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1984 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1985 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1986 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1992 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1993 CallingConv::ID CallConv, bool isVarArg,
1995 const SmallVectorImpl<ISD::OutputArg> &Outs,
1996 const SmallVectorImpl<SDValue> &OutVals,
1997 const SmallVectorImpl<ISD::InputArg> &Ins,
1998 DebugLoc dl, SelectionDAG &DAG,
1999 SmallVectorImpl<SDValue> &InVals) const {
2000 MachineFunction &MF = DAG.getMachineFunction();
2001 bool Is64Bit = Subtarget->is64Bit();
2002 bool IsWin64 = Subtarget->isTargetWin64();
2003 bool IsStructRet = CallIsStructReturn(Outs);
2004 bool IsSibcall = false;
2007 // Check if it's really possible to do a tail call.
2008 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2009 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2010 Outs, OutVals, Ins, DAG);
2012 // Sibcalls are automatically detected tailcalls which do not require
2014 if (!GuaranteedTailCallOpt && isTailCall)
2021 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2022 "Var args not supported with calling convention fastcc or ghc");
2024 // Analyze operands of the call, assigning locations to each operand.
2025 SmallVector<CCValAssign, 16> ArgLocs;
2026 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2027 ArgLocs, *DAG.getContext());
2029 // Allocate shadow area for Win64
2031 CCInfo.AllocateStack(32, 8);
2034 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2036 // Get a count of how many bytes are to be pushed on the stack.
2037 unsigned NumBytes = CCInfo.getNextStackOffset();
2039 // This is a sibcall. The memory operands are available in caller's
2040 // own caller's stack.
2042 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2043 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2046 if (isTailCall && !IsSibcall) {
2047 // Lower arguments at fp - stackoffset + fpdiff.
2048 unsigned NumBytesCallerPushed =
2049 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2050 FPDiff = NumBytesCallerPushed - NumBytes;
2052 // Set the delta of movement of the returnaddr stackslot.
2053 // But only set if delta is greater than previous delta.
2054 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2055 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2059 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2061 SDValue RetAddrFrIdx;
2062 // Load return address for tail calls.
2063 if (isTailCall && FPDiff)
2064 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2065 Is64Bit, FPDiff, dl);
2067 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2068 SmallVector<SDValue, 8> MemOpChains;
2071 // Walk the register/memloc assignments, inserting copies/loads. In the case
2072 // of tail call optimization arguments are handle later.
2073 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2074 CCValAssign &VA = ArgLocs[i];
2075 EVT RegVT = VA.getLocVT();
2076 SDValue Arg = OutVals[i];
2077 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2078 bool isByVal = Flags.isByVal();
2080 // Promote the value if needed.
2081 switch (VA.getLocInfo()) {
2082 default: llvm_unreachable("Unknown loc info!");
2083 case CCValAssign::Full: break;
2084 case CCValAssign::SExt:
2085 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2087 case CCValAssign::ZExt:
2088 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2090 case CCValAssign::AExt:
2091 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2092 // Special case: passing MMX values in XMM registers.
2093 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2094 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2095 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2097 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2099 case CCValAssign::BCvt:
2100 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2102 case CCValAssign::Indirect: {
2103 // Store the argument.
2104 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2105 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2106 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2107 MachinePointerInfo::getFixedStack(FI),
2114 if (VA.isRegLoc()) {
2115 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2116 if (isVarArg && IsWin64) {
2117 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2118 // shadow reg if callee is a varargs function.
2119 unsigned ShadowReg = 0;
2120 switch (VA.getLocReg()) {
2121 case X86::XMM0: ShadowReg = X86::RCX; break;
2122 case X86::XMM1: ShadowReg = X86::RDX; break;
2123 case X86::XMM2: ShadowReg = X86::R8; break;
2124 case X86::XMM3: ShadowReg = X86::R9; break;
2127 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2129 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2130 assert(VA.isMemLoc());
2131 if (StackPtr.getNode() == 0)
2132 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2133 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2134 dl, DAG, VA, Flags));
2138 if (!MemOpChains.empty())
2139 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2140 &MemOpChains[0], MemOpChains.size());
2142 // Build a sequence of copy-to-reg nodes chained together with token chain
2143 // and flag operands which copy the outgoing args into registers.
2145 // Tail call byval lowering might overwrite argument registers so in case of
2146 // tail call optimization the copies to registers are lowered later.
2148 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2149 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2150 RegsToPass[i].second, InFlag);
2151 InFlag = Chain.getValue(1);
2154 if (Subtarget->isPICStyleGOT()) {
2155 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2158 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2159 DAG.getNode(X86ISD::GlobalBaseReg,
2160 DebugLoc(), getPointerTy()),
2162 InFlag = Chain.getValue(1);
2164 // If we are tail calling and generating PIC/GOT style code load the
2165 // address of the callee into ECX. The value in ecx is used as target of
2166 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2167 // for tail calls on PIC/GOT architectures. Normally we would just put the
2168 // address of GOT into ebx and then call target@PLT. But for tail calls
2169 // ebx would be restored (since ebx is callee saved) before jumping to the
2172 // Note: The actual moving to ECX is done further down.
2173 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2174 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2175 !G->getGlobal()->hasProtectedVisibility())
2176 Callee = LowerGlobalAddress(Callee, DAG);
2177 else if (isa<ExternalSymbolSDNode>(Callee))
2178 Callee = LowerExternalSymbol(Callee, DAG);
2182 if (Is64Bit && isVarArg && !IsWin64) {
2183 // From AMD64 ABI document:
2184 // For calls that may call functions that use varargs or stdargs
2185 // (prototype-less calls or calls to functions containing ellipsis (...) in
2186 // the declaration) %al is used as hidden argument to specify the number
2187 // of SSE registers used. The contents of %al do not need to match exactly
2188 // the number of registers, but must be an ubound on the number of SSE
2189 // registers used and is in the range 0 - 8 inclusive.
2191 // Count the number of XMM registers allocated.
2192 static const unsigned XMMArgRegs[] = {
2193 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2194 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2196 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2197 assert((Subtarget->hasXMM() || !NumXMMRegs)
2198 && "SSE registers cannot be used when SSE is disabled");
2200 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2201 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2202 InFlag = Chain.getValue(1);
2206 // For tail calls lower the arguments to the 'real' stack slot.
2208 // Force all the incoming stack arguments to be loaded from the stack
2209 // before any new outgoing arguments are stored to the stack, because the
2210 // outgoing stack slots may alias the incoming argument stack slots, and
2211 // the alias isn't otherwise explicit. This is slightly more conservative
2212 // than necessary, because it means that each store effectively depends
2213 // on every argument instead of just those arguments it would clobber.
2214 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2216 SmallVector<SDValue, 8> MemOpChains2;
2219 // Do not flag preceding copytoreg stuff together with the following stuff.
2221 if (GuaranteedTailCallOpt) {
2222 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2223 CCValAssign &VA = ArgLocs[i];
2226 assert(VA.isMemLoc());
2227 SDValue Arg = OutVals[i];
2228 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2229 // Create frame index.
2230 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2231 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2232 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2233 FIN = DAG.getFrameIndex(FI, getPointerTy());
2235 if (Flags.isByVal()) {
2236 // Copy relative to framepointer.
2237 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2238 if (StackPtr.getNode() == 0)
2239 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2241 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2243 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2247 // Store relative to framepointer.
2248 MemOpChains2.push_back(
2249 DAG.getStore(ArgChain, dl, Arg, FIN,
2250 MachinePointerInfo::getFixedStack(FI),
2256 if (!MemOpChains2.empty())
2257 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2258 &MemOpChains2[0], MemOpChains2.size());
2260 // Copy arguments to their registers.
2261 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2262 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2263 RegsToPass[i].second, InFlag);
2264 InFlag = Chain.getValue(1);
2268 // Store the return address to the appropriate stack slot.
2269 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2273 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2274 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2275 // In the 64-bit large code model, we have to make all calls
2276 // through a register, since the call instruction's 32-bit
2277 // pc-relative offset may not be large enough to hold the whole
2279 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2280 // If the callee is a GlobalAddress node (quite common, every direct call
2281 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2284 // We should use extra load for direct calls to dllimported functions in
2286 const GlobalValue *GV = G->getGlobal();
2287 if (!GV->hasDLLImportLinkage()) {
2288 unsigned char OpFlags = 0;
2289 bool ExtraLoad = false;
2290 unsigned WrapperKind = ISD::DELETED_NODE;
2292 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2293 // external symbols most go through the PLT in PIC mode. If the symbol
2294 // has hidden or protected visibility, or if it is static or local, then
2295 // we don't need to use the PLT - we can directly call it.
2296 if (Subtarget->isTargetELF() &&
2297 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2298 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2299 OpFlags = X86II::MO_PLT;
2300 } else if (Subtarget->isPICStyleStubAny() &&
2301 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2302 (!Subtarget->getTargetTriple().isMacOSX() ||
2303 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2304 // PC-relative references to external symbols should go through $stub,
2305 // unless we're building with the leopard linker or later, which
2306 // automatically synthesizes these stubs.
2307 OpFlags = X86II::MO_DARWIN_STUB;
2308 } else if (Subtarget->isPICStyleRIPRel() &&
2309 isa<Function>(GV) &&
2310 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2311 // If the function is marked as non-lazy, generate an indirect call
2312 // which loads from the GOT directly. This avoids runtime overhead
2313 // at the cost of eager binding (and one extra byte of encoding).
2314 OpFlags = X86II::MO_GOTPCREL;
2315 WrapperKind = X86ISD::WrapperRIP;
2319 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2320 G->getOffset(), OpFlags);
2322 // Add a wrapper if needed.
2323 if (WrapperKind != ISD::DELETED_NODE)
2324 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2325 // Add extra indirection if needed.
2327 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2328 MachinePointerInfo::getGOT(),
2331 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2332 unsigned char OpFlags = 0;
2334 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2335 // external symbols should go through the PLT.
2336 if (Subtarget->isTargetELF() &&
2337 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2338 OpFlags = X86II::MO_PLT;
2339 } else if (Subtarget->isPICStyleStubAny() &&
2340 (!Subtarget->getTargetTriple().isMacOSX() ||
2341 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2342 // PC-relative references to external symbols should go through $stub,
2343 // unless we're building with the leopard linker or later, which
2344 // automatically synthesizes these stubs.
2345 OpFlags = X86II::MO_DARWIN_STUB;
2348 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2352 // Returns a chain & a flag for retval copy to use.
2353 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2354 SmallVector<SDValue, 8> Ops;
2356 if (!IsSibcall && isTailCall) {
2357 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2358 DAG.getIntPtrConstant(0, true), InFlag);
2359 InFlag = Chain.getValue(1);
2362 Ops.push_back(Chain);
2363 Ops.push_back(Callee);
2366 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2368 // Add argument registers to the end of the list so that they are known live
2370 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2371 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2372 RegsToPass[i].second.getValueType()));
2374 // Add an implicit use GOT pointer in EBX.
2375 if (!isTailCall && Subtarget->isPICStyleGOT())
2376 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2378 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2379 if (Is64Bit && isVarArg && !IsWin64)
2380 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2382 if (InFlag.getNode())
2383 Ops.push_back(InFlag);
2387 //// If this is the first return lowered for this function, add the regs
2388 //// to the liveout set for the function.
2389 // This isn't right, although it's probably harmless on x86; liveouts
2390 // should be computed from returns not tail calls. Consider a void
2391 // function making a tail call to a function returning int.
2392 return DAG.getNode(X86ISD::TC_RETURN, dl,
2393 NodeTys, &Ops[0], Ops.size());
2396 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2397 InFlag = Chain.getValue(1);
2399 // Create the CALLSEQ_END node.
2400 unsigned NumBytesForCalleeToPush;
2401 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2402 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2403 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2404 // If this is a call to a struct-return function, the callee
2405 // pops the hidden struct pointer, so we have to push it back.
2406 // This is common for Darwin/X86, Linux & Mingw32 targets.
2407 NumBytesForCalleeToPush = 4;
2409 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2411 // Returns a flag for retval copy to use.
2413 Chain = DAG.getCALLSEQ_END(Chain,
2414 DAG.getIntPtrConstant(NumBytes, true),
2415 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2418 InFlag = Chain.getValue(1);
2421 // Handle result values, copying them out of physregs into vregs that we
2423 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2424 Ins, dl, DAG, InVals);
2428 //===----------------------------------------------------------------------===//
2429 // Fast Calling Convention (tail call) implementation
2430 //===----------------------------------------------------------------------===//
2432 // Like std call, callee cleans arguments, convention except that ECX is
2433 // reserved for storing the tail called function address. Only 2 registers are
2434 // free for argument passing (inreg). Tail call optimization is performed
2436 // * tailcallopt is enabled
2437 // * caller/callee are fastcc
2438 // On X86_64 architecture with GOT-style position independent code only local
2439 // (within module) calls are supported at the moment.
2440 // To keep the stack aligned according to platform abi the function
2441 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2442 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2443 // If a tail called function callee has more arguments than the caller the
2444 // caller needs to make sure that there is room to move the RETADDR to. This is
2445 // achieved by reserving an area the size of the argument delta right after the
2446 // original REtADDR, but before the saved framepointer or the spilled registers
2447 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2459 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2460 /// for a 16 byte align requirement.
2462 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2463 SelectionDAG& DAG) const {
2464 MachineFunction &MF = DAG.getMachineFunction();
2465 const TargetMachine &TM = MF.getTarget();
2466 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2467 unsigned StackAlignment = TFI.getStackAlignment();
2468 uint64_t AlignMask = StackAlignment - 1;
2469 int64_t Offset = StackSize;
2470 uint64_t SlotSize = TD->getPointerSize();
2471 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2472 // Number smaller than 12 so just add the difference.
2473 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2475 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2476 Offset = ((~AlignMask) & Offset) + StackAlignment +
2477 (StackAlignment-SlotSize);
2482 /// MatchingStackOffset - Return true if the given stack call argument is
2483 /// already available in the same position (relatively) of the caller's
2484 /// incoming argument stack.
2486 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2487 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2488 const X86InstrInfo *TII) {
2489 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2491 if (Arg.getOpcode() == ISD::CopyFromReg) {
2492 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2493 if (!TargetRegisterInfo::isVirtualRegister(VR))
2495 MachineInstr *Def = MRI->getVRegDef(VR);
2498 if (!Flags.isByVal()) {
2499 if (!TII->isLoadFromStackSlot(Def, FI))
2502 unsigned Opcode = Def->getOpcode();
2503 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2504 Def->getOperand(1).isFI()) {
2505 FI = Def->getOperand(1).getIndex();
2506 Bytes = Flags.getByValSize();
2510 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2511 if (Flags.isByVal())
2512 // ByVal argument is passed in as a pointer but it's now being
2513 // dereferenced. e.g.
2514 // define @foo(%struct.X* %A) {
2515 // tail call @bar(%struct.X* byval %A)
2518 SDValue Ptr = Ld->getBasePtr();
2519 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2522 FI = FINode->getIndex();
2523 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2524 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2525 FI = FINode->getIndex();
2526 Bytes = Flags.getByValSize();
2530 assert(FI != INT_MAX);
2531 if (!MFI->isFixedObjectIndex(FI))
2533 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2536 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2537 /// for tail call optimization. Targets which want to do tail call
2538 /// optimization should implement this function.
2540 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2541 CallingConv::ID CalleeCC,
2543 bool isCalleeStructRet,
2544 bool isCallerStructRet,
2545 const SmallVectorImpl<ISD::OutputArg> &Outs,
2546 const SmallVectorImpl<SDValue> &OutVals,
2547 const SmallVectorImpl<ISD::InputArg> &Ins,
2548 SelectionDAG& DAG) const {
2549 if (!IsTailCallConvention(CalleeCC) &&
2550 CalleeCC != CallingConv::C)
2553 // If -tailcallopt is specified, make fastcc functions tail-callable.
2554 const MachineFunction &MF = DAG.getMachineFunction();
2555 const Function *CallerF = DAG.getMachineFunction().getFunction();
2556 CallingConv::ID CallerCC = CallerF->getCallingConv();
2557 bool CCMatch = CallerCC == CalleeCC;
2559 if (GuaranteedTailCallOpt) {
2560 if (IsTailCallConvention(CalleeCC) && CCMatch)
2565 // Look for obvious safe cases to perform tail call optimization that do not
2566 // require ABI changes. This is what gcc calls sibcall.
2568 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2569 // emit a special epilogue.
2570 if (RegInfo->needsStackRealignment(MF))
2573 // Also avoid sibcall optimization if either caller or callee uses struct
2574 // return semantics.
2575 if (isCalleeStructRet || isCallerStructRet)
2578 // An stdcall caller is expected to clean up its arguments; the callee
2579 // isn't going to do that.
2580 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2583 // Do not sibcall optimize vararg calls unless all arguments are passed via
2585 if (isVarArg && !Outs.empty()) {
2587 // Optimizing for varargs on Win64 is unlikely to be safe without
2588 // additional testing.
2589 if (Subtarget->isTargetWin64())
2592 SmallVector<CCValAssign, 16> ArgLocs;
2593 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2594 getTargetMachine(), ArgLocs, *DAG.getContext());
2596 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2597 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2598 if (!ArgLocs[i].isRegLoc())
2602 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2603 // Therefore if it's not used by the call it is not safe to optimize this into
2605 bool Unused = false;
2606 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2613 SmallVector<CCValAssign, 16> RVLocs;
2614 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2615 getTargetMachine(), RVLocs, *DAG.getContext());
2616 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2617 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2618 CCValAssign &VA = RVLocs[i];
2619 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2624 // If the calling conventions do not match, then we'd better make sure the
2625 // results are returned in the same way as what the caller expects.
2627 SmallVector<CCValAssign, 16> RVLocs1;
2628 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2629 getTargetMachine(), RVLocs1, *DAG.getContext());
2630 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2632 SmallVector<CCValAssign, 16> RVLocs2;
2633 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2634 getTargetMachine(), RVLocs2, *DAG.getContext());
2635 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2637 if (RVLocs1.size() != RVLocs2.size())
2639 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2640 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2642 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2644 if (RVLocs1[i].isRegLoc()) {
2645 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2648 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2654 // If the callee takes no arguments then go on to check the results of the
2656 if (!Outs.empty()) {
2657 // Check if stack adjustment is needed. For now, do not do this if any
2658 // argument is passed on the stack.
2659 SmallVector<CCValAssign, 16> ArgLocs;
2660 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2661 getTargetMachine(), ArgLocs, *DAG.getContext());
2663 // Allocate shadow area for Win64
2664 if (Subtarget->isTargetWin64()) {
2665 CCInfo.AllocateStack(32, 8);
2668 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2669 if (CCInfo.getNextStackOffset()) {
2670 MachineFunction &MF = DAG.getMachineFunction();
2671 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2674 // Check if the arguments are already laid out in the right way as
2675 // the caller's fixed stack objects.
2676 MachineFrameInfo *MFI = MF.getFrameInfo();
2677 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2678 const X86InstrInfo *TII =
2679 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2680 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2681 CCValAssign &VA = ArgLocs[i];
2682 SDValue Arg = OutVals[i];
2683 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2684 if (VA.getLocInfo() == CCValAssign::Indirect)
2686 if (!VA.isRegLoc()) {
2687 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2694 // If the tailcall address may be in a register, then make sure it's
2695 // possible to register allocate for it. In 32-bit, the call address can
2696 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2697 // callee-saved registers are restored. These happen to be the same
2698 // registers used to pass 'inreg' arguments so watch out for those.
2699 if (!Subtarget->is64Bit() &&
2700 !isa<GlobalAddressSDNode>(Callee) &&
2701 !isa<ExternalSymbolSDNode>(Callee)) {
2702 unsigned NumInRegs = 0;
2703 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2704 CCValAssign &VA = ArgLocs[i];
2707 unsigned Reg = VA.getLocReg();
2710 case X86::EAX: case X86::EDX: case X86::ECX:
2711 if (++NumInRegs == 3)
2723 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2724 return X86::createFastISel(funcInfo);
2728 //===----------------------------------------------------------------------===//
2729 // Other Lowering Hooks
2730 //===----------------------------------------------------------------------===//
2732 static bool MayFoldLoad(SDValue Op) {
2733 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2736 static bool MayFoldIntoStore(SDValue Op) {
2737 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2740 static bool isTargetShuffle(unsigned Opcode) {
2742 default: return false;
2743 case X86ISD::PSHUFD:
2744 case X86ISD::PSHUFHW:
2745 case X86ISD::PSHUFLW:
2746 case X86ISD::SHUFPD:
2747 case X86ISD::PALIGN:
2748 case X86ISD::SHUFPS:
2749 case X86ISD::MOVLHPS:
2750 case X86ISD::MOVLHPD:
2751 case X86ISD::MOVHLPS:
2752 case X86ISD::MOVLPS:
2753 case X86ISD::MOVLPD:
2754 case X86ISD::MOVSHDUP:
2755 case X86ISD::MOVSLDUP:
2756 case X86ISD::MOVDDUP:
2759 case X86ISD::UNPCKLPS:
2760 case X86ISD::UNPCKLPD:
2761 case X86ISD::VUNPCKLPS:
2762 case X86ISD::VUNPCKLPD:
2763 case X86ISD::VUNPCKLPSY:
2764 case X86ISD::VUNPCKLPDY:
2765 case X86ISD::PUNPCKLWD:
2766 case X86ISD::PUNPCKLBW:
2767 case X86ISD::PUNPCKLDQ:
2768 case X86ISD::PUNPCKLQDQ:
2769 case X86ISD::UNPCKHPS:
2770 case X86ISD::UNPCKHPD:
2771 case X86ISD::PUNPCKHWD:
2772 case X86ISD::PUNPCKHBW:
2773 case X86ISD::PUNPCKHDQ:
2774 case X86ISD::PUNPCKHQDQ:
2780 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2781 SDValue V1, SelectionDAG &DAG) {
2783 default: llvm_unreachable("Unknown x86 shuffle node");
2784 case X86ISD::MOVSHDUP:
2785 case X86ISD::MOVSLDUP:
2786 case X86ISD::MOVDDUP:
2787 return DAG.getNode(Opc, dl, VT, V1);
2793 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2794 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2796 default: llvm_unreachable("Unknown x86 shuffle node");
2797 case X86ISD::PSHUFD:
2798 case X86ISD::PSHUFHW:
2799 case X86ISD::PSHUFLW:
2800 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2806 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2807 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2809 default: llvm_unreachable("Unknown x86 shuffle node");
2810 case X86ISD::PALIGN:
2811 case X86ISD::SHUFPD:
2812 case X86ISD::SHUFPS:
2813 return DAG.getNode(Opc, dl, VT, V1, V2,
2814 DAG.getConstant(TargetMask, MVT::i8));
2819 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2820 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2822 default: llvm_unreachable("Unknown x86 shuffle node");
2823 case X86ISD::MOVLHPS:
2824 case X86ISD::MOVLHPD:
2825 case X86ISD::MOVHLPS:
2826 case X86ISD::MOVLPS:
2827 case X86ISD::MOVLPD:
2830 case X86ISD::UNPCKLPS:
2831 case X86ISD::UNPCKLPD:
2832 case X86ISD::VUNPCKLPS:
2833 case X86ISD::VUNPCKLPD:
2834 case X86ISD::VUNPCKLPSY:
2835 case X86ISD::VUNPCKLPDY:
2836 case X86ISD::PUNPCKLWD:
2837 case X86ISD::PUNPCKLBW:
2838 case X86ISD::PUNPCKLDQ:
2839 case X86ISD::PUNPCKLQDQ:
2840 case X86ISD::UNPCKHPS:
2841 case X86ISD::UNPCKHPD:
2842 case X86ISD::PUNPCKHWD:
2843 case X86ISD::PUNPCKHBW:
2844 case X86ISD::PUNPCKHDQ:
2845 case X86ISD::PUNPCKHQDQ:
2846 return DAG.getNode(Opc, dl, VT, V1, V2);
2851 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2852 MachineFunction &MF = DAG.getMachineFunction();
2853 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2854 int ReturnAddrIndex = FuncInfo->getRAIndex();
2856 if (ReturnAddrIndex == 0) {
2857 // Set up a frame object for the return address.
2858 uint64_t SlotSize = TD->getPointerSize();
2859 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2861 FuncInfo->setRAIndex(ReturnAddrIndex);
2864 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2868 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2869 bool hasSymbolicDisplacement) {
2870 // Offset should fit into 32 bit immediate field.
2871 if (!isInt<32>(Offset))
2874 // If we don't have a symbolic displacement - we don't have any extra
2876 if (!hasSymbolicDisplacement)
2879 // FIXME: Some tweaks might be needed for medium code model.
2880 if (M != CodeModel::Small && M != CodeModel::Kernel)
2883 // For small code model we assume that latest object is 16MB before end of 31
2884 // bits boundary. We may also accept pretty large negative constants knowing
2885 // that all objects are in the positive half of address space.
2886 if (M == CodeModel::Small && Offset < 16*1024*1024)
2889 // For kernel code model we know that all object resist in the negative half
2890 // of 32bits address space. We may not accept negative offsets, since they may
2891 // be just off and we may accept pretty large positive ones.
2892 if (M == CodeModel::Kernel && Offset > 0)
2898 /// isCalleePop - Determines whether the callee is required to pop its
2899 /// own arguments. Callee pop is necessary to support tail calls.
2900 bool X86::isCalleePop(CallingConv::ID CallingConv,
2901 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2905 switch (CallingConv) {
2908 case CallingConv::X86_StdCall:
2910 case CallingConv::X86_FastCall:
2912 case CallingConv::X86_ThisCall:
2914 case CallingConv::Fast:
2916 case CallingConv::GHC:
2921 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2922 /// specific condition code, returning the condition code and the LHS/RHS of the
2923 /// comparison to make.
2924 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2925 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2927 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2928 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2929 // X > -1 -> X == 0, jump !sign.
2930 RHS = DAG.getConstant(0, RHS.getValueType());
2931 return X86::COND_NS;
2932 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2933 // X < 0 -> X == 0, jump on sign.
2935 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2937 RHS = DAG.getConstant(0, RHS.getValueType());
2938 return X86::COND_LE;
2942 switch (SetCCOpcode) {
2943 default: llvm_unreachable("Invalid integer condition!");
2944 case ISD::SETEQ: return X86::COND_E;
2945 case ISD::SETGT: return X86::COND_G;
2946 case ISD::SETGE: return X86::COND_GE;
2947 case ISD::SETLT: return X86::COND_L;
2948 case ISD::SETLE: return X86::COND_LE;
2949 case ISD::SETNE: return X86::COND_NE;
2950 case ISD::SETULT: return X86::COND_B;
2951 case ISD::SETUGT: return X86::COND_A;
2952 case ISD::SETULE: return X86::COND_BE;
2953 case ISD::SETUGE: return X86::COND_AE;
2957 // First determine if it is required or is profitable to flip the operands.
2959 // If LHS is a foldable load, but RHS is not, flip the condition.
2960 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2961 !ISD::isNON_EXTLoad(RHS.getNode())) {
2962 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2963 std::swap(LHS, RHS);
2966 switch (SetCCOpcode) {
2972 std::swap(LHS, RHS);
2976 // On a floating point condition, the flags are set as follows:
2978 // 0 | 0 | 0 | X > Y
2979 // 0 | 0 | 1 | X < Y
2980 // 1 | 0 | 0 | X == Y
2981 // 1 | 1 | 1 | unordered
2982 switch (SetCCOpcode) {
2983 default: llvm_unreachable("Condcode should be pre-legalized away");
2985 case ISD::SETEQ: return X86::COND_E;
2986 case ISD::SETOLT: // flipped
2988 case ISD::SETGT: return X86::COND_A;
2989 case ISD::SETOLE: // flipped
2991 case ISD::SETGE: return X86::COND_AE;
2992 case ISD::SETUGT: // flipped
2994 case ISD::SETLT: return X86::COND_B;
2995 case ISD::SETUGE: // flipped
2997 case ISD::SETLE: return X86::COND_BE;
2999 case ISD::SETNE: return X86::COND_NE;
3000 case ISD::SETUO: return X86::COND_P;
3001 case ISD::SETO: return X86::COND_NP;
3003 case ISD::SETUNE: return X86::COND_INVALID;
3007 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3008 /// code. Current x86 isa includes the following FP cmov instructions:
3009 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3010 static bool hasFPCMov(unsigned X86CC) {
3026 /// isFPImmLegal - Returns true if the target can instruction select the
3027 /// specified FP immediate natively. If false, the legalizer will
3028 /// materialize the FP immediate as a load from a constant pool.
3029 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3030 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3031 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3037 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3038 /// the specified range (L, H].
3039 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3040 return (Val < 0) || (Val >= Low && Val < Hi);
3043 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3044 /// specified value.
3045 static bool isUndefOrEqual(int Val, int CmpVal) {
3046 if (Val < 0 || Val == CmpVal)
3051 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3052 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3053 /// the second operand.
3054 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3055 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3056 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3057 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3058 return (Mask[0] < 2 && Mask[1] < 2);
3062 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3063 SmallVector<int, 8> M;
3065 return ::isPSHUFDMask(M, N->getValueType(0));
3068 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3069 /// is suitable for input to PSHUFHW.
3070 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3071 if (VT != MVT::v8i16)
3074 // Lower quadword copied in order or undef.
3075 for (int i = 0; i != 4; ++i)
3076 if (Mask[i] >= 0 && Mask[i] != i)
3079 // Upper quadword shuffled.
3080 for (int i = 4; i != 8; ++i)
3081 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3087 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3088 SmallVector<int, 8> M;
3090 return ::isPSHUFHWMask(M, N->getValueType(0));
3093 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3094 /// is suitable for input to PSHUFLW.
3095 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3096 if (VT != MVT::v8i16)
3099 // Upper quadword copied in order.
3100 for (int i = 4; i != 8; ++i)
3101 if (Mask[i] >= 0 && Mask[i] != i)
3104 // Lower quadword shuffled.
3105 for (int i = 0; i != 4; ++i)
3112 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3113 SmallVector<int, 8> M;
3115 return ::isPSHUFLWMask(M, N->getValueType(0));
3118 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3119 /// is suitable for input to PALIGNR.
3120 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3122 int i, e = VT.getVectorNumElements();
3124 // Do not handle v2i64 / v2f64 shuffles with palignr.
3125 if (e < 4 || !hasSSSE3)
3128 for (i = 0; i != e; ++i)
3132 // All undef, not a palignr.
3136 // Determine if it's ok to perform a palignr with only the LHS, since we
3137 // don't have access to the actual shuffle elements to see if RHS is undef.
3138 bool Unary = Mask[i] < (int)e;
3139 bool NeedsUnary = false;
3141 int s = Mask[i] - i;
3143 // Check the rest of the elements to see if they are consecutive.
3144 for (++i; i != e; ++i) {
3149 Unary = Unary && (m < (int)e);
3150 NeedsUnary = NeedsUnary || (m < s);
3152 if (NeedsUnary && !Unary)
3154 if (Unary && m != ((s+i) & (e-1)))
3156 if (!Unary && m != (s+i))
3162 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3163 SmallVector<int, 8> M;
3165 return ::isPALIGNRMask(M, N->getValueType(0), true);
3168 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3169 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3170 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3171 int NumElems = VT.getVectorNumElements();
3172 if (NumElems != 2 && NumElems != 4)
3175 int Half = NumElems / 2;
3176 for (int i = 0; i < Half; ++i)
3177 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3179 for (int i = Half; i < NumElems; ++i)
3180 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3186 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3187 SmallVector<int, 8> M;
3189 return ::isSHUFPMask(M, N->getValueType(0));
3192 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3193 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3194 /// half elements to come from vector 1 (which would equal the dest.) and
3195 /// the upper half to come from vector 2.
3196 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3197 int NumElems = VT.getVectorNumElements();
3199 if (NumElems != 2 && NumElems != 4)
3202 int Half = NumElems / 2;
3203 for (int i = 0; i < Half; ++i)
3204 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3206 for (int i = Half; i < NumElems; ++i)
3207 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3212 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3213 SmallVector<int, 8> M;
3215 return isCommutedSHUFPMask(M, N->getValueType(0));
3218 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3219 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3220 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3221 if (N->getValueType(0).getVectorNumElements() != 4)
3224 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3225 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3226 isUndefOrEqual(N->getMaskElt(1), 7) &&
3227 isUndefOrEqual(N->getMaskElt(2), 2) &&
3228 isUndefOrEqual(N->getMaskElt(3), 3);
3231 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3232 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3234 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3235 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3240 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3241 isUndefOrEqual(N->getMaskElt(1), 3) &&
3242 isUndefOrEqual(N->getMaskElt(2), 2) &&
3243 isUndefOrEqual(N->getMaskElt(3), 3);
3246 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3247 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3248 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3249 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3251 if (NumElems != 2 && NumElems != 4)
3254 for (unsigned i = 0; i < NumElems/2; ++i)
3255 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3258 for (unsigned i = NumElems/2; i < NumElems; ++i)
3259 if (!isUndefOrEqual(N->getMaskElt(i), i))
3265 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3266 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3267 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3268 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3270 if ((NumElems != 2 && NumElems != 4)
3271 || N->getValueType(0).getSizeInBits() > 128)
3274 for (unsigned i = 0; i < NumElems/2; ++i)
3275 if (!isUndefOrEqual(N->getMaskElt(i), i))
3278 for (unsigned i = 0; i < NumElems/2; ++i)
3279 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3285 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3286 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3287 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3288 bool V2IsSplat = false) {
3289 int NumElts = VT.getVectorNumElements();
3290 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3293 // Handle vector lengths > 128 bits. Define a "section" as a set of
3294 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3296 unsigned NumSections = VT.getSizeInBits() / 128;
3297 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3298 unsigned NumSectionElts = NumElts / NumSections;
3301 unsigned End = NumSectionElts;
3302 for (unsigned s = 0; s < NumSections; ++s) {
3303 for (unsigned i = Start, j = s * NumSectionElts;
3307 int BitI1 = Mask[i+1];
3308 if (!isUndefOrEqual(BitI, j))
3311 if (!isUndefOrEqual(BitI1, NumElts))
3314 if (!isUndefOrEqual(BitI1, j + NumElts))
3318 // Process the next 128 bits.
3319 Start += NumSectionElts;
3320 End += NumSectionElts;
3326 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3327 SmallVector<int, 8> M;
3329 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3332 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3333 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3334 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3335 bool V2IsSplat = false) {
3336 int NumElts = VT.getVectorNumElements();
3337 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3340 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3342 int BitI1 = Mask[i+1];
3343 if (!isUndefOrEqual(BitI, j + NumElts/2))
3346 if (isUndefOrEqual(BitI1, NumElts))
3349 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3356 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3357 SmallVector<int, 8> M;
3359 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3362 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3363 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3365 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3366 int NumElems = VT.getVectorNumElements();
3367 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3370 // Handle vector lengths > 128 bits. Define a "section" as a set of
3371 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3373 unsigned NumSections = VT.getSizeInBits() / 128;
3374 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3375 unsigned NumSectionElts = NumElems / NumSections;
3377 for (unsigned s = 0; s < NumSections; ++s) {
3378 for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3379 i != NumSectionElts * (s + 1);
3382 int BitI1 = Mask[i+1];
3384 if (!isUndefOrEqual(BitI, j))
3386 if (!isUndefOrEqual(BitI1, j))
3394 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3395 SmallVector<int, 8> M;
3397 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3400 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3401 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3403 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3404 int NumElems = VT.getVectorNumElements();
3405 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3408 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3410 int BitI1 = Mask[i+1];
3411 if (!isUndefOrEqual(BitI, j))
3413 if (!isUndefOrEqual(BitI1, j))
3419 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3420 SmallVector<int, 8> M;
3422 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3425 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3426 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3427 /// MOVSD, and MOVD, i.e. setting the lowest element.
3428 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3429 if (VT.getVectorElementType().getSizeInBits() < 32)
3432 int NumElts = VT.getVectorNumElements();
3434 if (!isUndefOrEqual(Mask[0], NumElts))
3437 for (int i = 1; i < NumElts; ++i)
3438 if (!isUndefOrEqual(Mask[i], i))
3444 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3445 SmallVector<int, 8> M;
3447 return ::isMOVLMask(M, N->getValueType(0));
3450 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3451 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3452 /// element of vector 2 and the other elements to come from vector 1 in order.
3453 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3454 bool V2IsSplat = false, bool V2IsUndef = false) {
3455 int NumOps = VT.getVectorNumElements();
3456 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3459 if (!isUndefOrEqual(Mask[0], 0))
3462 for (int i = 1; i < NumOps; ++i)
3463 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3464 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3465 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3471 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3472 bool V2IsUndef = false) {
3473 SmallVector<int, 8> M;
3475 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3478 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3479 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3480 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3481 if (N->getValueType(0).getVectorNumElements() != 4)
3484 // Expect 1, 1, 3, 3
3485 for (unsigned i = 0; i < 2; ++i) {
3486 int Elt = N->getMaskElt(i);
3487 if (Elt >= 0 && Elt != 1)
3492 for (unsigned i = 2; i < 4; ++i) {
3493 int Elt = N->getMaskElt(i);
3494 if (Elt >= 0 && Elt != 3)
3499 // Don't use movshdup if it can be done with a shufps.
3500 // FIXME: verify that matching u, u, 3, 3 is what we want.
3504 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3505 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3506 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3507 if (N->getValueType(0).getVectorNumElements() != 4)
3510 // Expect 0, 0, 2, 2
3511 for (unsigned i = 0; i < 2; ++i)
3512 if (N->getMaskElt(i) > 0)
3516 for (unsigned i = 2; i < 4; ++i) {
3517 int Elt = N->getMaskElt(i);
3518 if (Elt >= 0 && Elt != 2)
3523 // Don't use movsldup if it can be done with a shufps.
3527 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3528 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3529 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3530 int e = N->getValueType(0).getVectorNumElements() / 2;
3532 for (int i = 0; i < e; ++i)
3533 if (!isUndefOrEqual(N->getMaskElt(i), i))
3535 for (int i = 0; i < e; ++i)
3536 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3541 /// isVEXTRACTF128Index - Return true if the specified
3542 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3543 /// suitable for input to VEXTRACTF128.
3544 bool X86::isVEXTRACTF128Index(SDNode *N) {
3545 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3548 // The index should be aligned on a 128-bit boundary.
3550 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3552 unsigned VL = N->getValueType(0).getVectorNumElements();
3553 unsigned VBits = N->getValueType(0).getSizeInBits();
3554 unsigned ElSize = VBits / VL;
3555 bool Result = (Index * ElSize) % 128 == 0;
3560 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3561 /// operand specifies a subvector insert that is suitable for input to
3563 bool X86::isVINSERTF128Index(SDNode *N) {
3564 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3567 // The index should be aligned on a 128-bit boundary.
3569 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3571 unsigned VL = N->getValueType(0).getVectorNumElements();
3572 unsigned VBits = N->getValueType(0).getSizeInBits();
3573 unsigned ElSize = VBits / VL;
3574 bool Result = (Index * ElSize) % 128 == 0;
3579 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3580 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3581 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3582 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3583 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3585 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3587 for (int i = 0; i < NumOperands; ++i) {
3588 int Val = SVOp->getMaskElt(NumOperands-i-1);
3589 if (Val < 0) Val = 0;
3590 if (Val >= NumOperands) Val -= NumOperands;
3592 if (i != NumOperands - 1)
3598 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3599 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3600 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3601 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3603 // 8 nodes, but we only care about the last 4.
3604 for (unsigned i = 7; i >= 4; --i) {
3605 int Val = SVOp->getMaskElt(i);
3614 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3615 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3616 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3617 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3619 // 8 nodes, but we only care about the first 4.
3620 for (int i = 3; i >= 0; --i) {
3621 int Val = SVOp->getMaskElt(i);
3630 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3631 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3632 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3633 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3634 EVT VVT = N->getValueType(0);
3635 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3639 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3640 Val = SVOp->getMaskElt(i);
3644 return (Val - i) * EltSize;
3647 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3648 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3650 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3651 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3652 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3655 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3657 EVT VecVT = N->getOperand(0).getValueType();
3658 EVT ElVT = VecVT.getVectorElementType();
3660 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3662 return Index / NumElemsPerChunk;
3665 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3666 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3668 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3669 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3670 llvm_unreachable("Illegal insert subvector for VINSERTF128");
3673 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3675 EVT VecVT = N->getValueType(0);
3676 EVT ElVT = VecVT.getVectorElementType();
3678 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3680 return Index / NumElemsPerChunk;
3683 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3685 bool X86::isZeroNode(SDValue Elt) {
3686 return ((isa<ConstantSDNode>(Elt) &&
3687 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3688 (isa<ConstantFPSDNode>(Elt) &&
3689 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3692 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3693 /// their permute mask.
3694 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3695 SelectionDAG &DAG) {
3696 EVT VT = SVOp->getValueType(0);
3697 unsigned NumElems = VT.getVectorNumElements();
3698 SmallVector<int, 8> MaskVec;
3700 for (unsigned i = 0; i != NumElems; ++i) {
3701 int idx = SVOp->getMaskElt(i);
3703 MaskVec.push_back(idx);
3704 else if (idx < (int)NumElems)
3705 MaskVec.push_back(idx + NumElems);
3707 MaskVec.push_back(idx - NumElems);
3709 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3710 SVOp->getOperand(0), &MaskVec[0]);
3713 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3714 /// the two vector operands have swapped position.
3715 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3716 unsigned NumElems = VT.getVectorNumElements();
3717 for (unsigned i = 0; i != NumElems; ++i) {
3721 else if (idx < (int)NumElems)
3722 Mask[i] = idx + NumElems;
3724 Mask[i] = idx - NumElems;
3728 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3729 /// match movhlps. The lower half elements should come from upper half of
3730 /// V1 (and in order), and the upper half elements should come from the upper
3731 /// half of V2 (and in order).
3732 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3733 if (Op->getValueType(0).getVectorNumElements() != 4)
3735 for (unsigned i = 0, e = 2; i != e; ++i)
3736 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3738 for (unsigned i = 2; i != 4; ++i)
3739 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3744 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3745 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3747 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3748 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3750 N = N->getOperand(0).getNode();
3751 if (!ISD::isNON_EXTLoad(N))
3754 *LD = cast<LoadSDNode>(N);
3758 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3759 /// match movlp{s|d}. The lower half elements should come from lower half of
3760 /// V1 (and in order), and the upper half elements should come from the upper
3761 /// half of V2 (and in order). And since V1 will become the source of the
3762 /// MOVLP, it must be either a vector load or a scalar load to vector.
3763 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3764 ShuffleVectorSDNode *Op) {
3765 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3767 // Is V2 is a vector load, don't do this transformation. We will try to use
3768 // load folding shufps op.
3769 if (ISD::isNON_EXTLoad(V2))
3772 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3774 if (NumElems != 2 && NumElems != 4)
3776 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3777 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3779 for (unsigned i = NumElems/2; i != NumElems; ++i)
3780 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3785 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3787 static bool isSplatVector(SDNode *N) {
3788 if (N->getOpcode() != ISD::BUILD_VECTOR)
3791 SDValue SplatValue = N->getOperand(0);
3792 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3793 if (N->getOperand(i) != SplatValue)
3798 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3799 /// to an zero vector.
3800 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3801 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3802 SDValue V1 = N->getOperand(0);
3803 SDValue V2 = N->getOperand(1);
3804 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3805 for (unsigned i = 0; i != NumElems; ++i) {
3806 int Idx = N->getMaskElt(i);
3807 if (Idx >= (int)NumElems) {
3808 unsigned Opc = V2.getOpcode();
3809 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3811 if (Opc != ISD::BUILD_VECTOR ||
3812 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3814 } else if (Idx >= 0) {
3815 unsigned Opc = V1.getOpcode();
3816 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3818 if (Opc != ISD::BUILD_VECTOR ||
3819 !X86::isZeroNode(V1.getOperand(Idx)))
3826 /// getZeroVector - Returns a vector of specified type with all zero elements.
3828 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3830 assert(VT.isVector() && "Expected a vector type");
3832 // Always build SSE zero vectors as <4 x i32> bitcasted
3833 // to their dest type. This ensures they get CSE'd.
3835 if (VT.getSizeInBits() == 128) { // SSE
3836 if (HasSSE2) { // SSE2
3837 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3838 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3840 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3841 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3843 } else if (VT.getSizeInBits() == 256) { // AVX
3844 // 256-bit logic and arithmetic instructions in AVX are
3845 // all floating-point, no support for integer ops. Default
3846 // to emitting fp zeroed vectors then.
3847 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3848 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3849 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3851 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3854 /// getOnesVector - Returns a vector of specified type with all bits set.
3856 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3857 assert(VT.isVector() && "Expected a vector type");
3859 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3860 // type. This ensures they get CSE'd.
3861 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3863 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3864 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3868 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3869 /// that point to V2 points to its first element.
3870 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3871 EVT VT = SVOp->getValueType(0);
3872 unsigned NumElems = VT.getVectorNumElements();
3874 bool Changed = false;
3875 SmallVector<int, 8> MaskVec;
3876 SVOp->getMask(MaskVec);
3878 for (unsigned i = 0; i != NumElems; ++i) {
3879 if (MaskVec[i] > (int)NumElems) {
3880 MaskVec[i] = NumElems;
3885 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3886 SVOp->getOperand(1), &MaskVec[0]);
3887 return SDValue(SVOp, 0);
3890 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3891 /// operation of specified width.
3892 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3894 unsigned NumElems = VT.getVectorNumElements();
3895 SmallVector<int, 8> Mask;
3896 Mask.push_back(NumElems);
3897 for (unsigned i = 1; i != NumElems; ++i)
3899 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3902 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3903 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3905 unsigned NumElems = VT.getVectorNumElements();
3906 SmallVector<int, 8> Mask;
3907 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3909 Mask.push_back(i + NumElems);
3911 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3914 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3915 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3917 unsigned NumElems = VT.getVectorNumElements();
3918 unsigned Half = NumElems/2;
3919 SmallVector<int, 8> Mask;
3920 for (unsigned i = 0; i != Half; ++i) {
3921 Mask.push_back(i + Half);
3922 Mask.push_back(i + NumElems + Half);
3924 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3927 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3928 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3929 EVT PVT = MVT::v4f32;
3930 EVT VT = SV->getValueType(0);
3931 DebugLoc dl = SV->getDebugLoc();
3932 SDValue V1 = SV->getOperand(0);
3933 int NumElems = VT.getVectorNumElements();
3934 int EltNo = SV->getSplatIndex();
3936 // unpack elements to the correct location
3937 while (NumElems > 4) {
3938 if (EltNo < NumElems/2) {
3939 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3941 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3942 EltNo -= NumElems/2;
3947 // Perform the splat.
3948 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3949 V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3950 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3951 return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3954 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3955 /// vector of zero or undef vector. This produces a shuffle where the low
3956 /// element of V2 is swizzled into the zero/undef vector, landing at element
3957 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3958 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3959 bool isZero, bool HasSSE2,
3960 SelectionDAG &DAG) {
3961 EVT VT = V2.getValueType();
3963 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3964 unsigned NumElems = VT.getVectorNumElements();
3965 SmallVector<int, 16> MaskVec;
3966 for (unsigned i = 0; i != NumElems; ++i)
3967 // If this is the insertion idx, put the low elt of V2 here.
3968 MaskVec.push_back(i == Idx ? NumElems : i);
3969 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3972 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3973 /// element of the result of the vector shuffle.
3974 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3977 return SDValue(); // Limit search depth.
3979 SDValue V = SDValue(N, 0);
3980 EVT VT = V.getValueType();
3981 unsigned Opcode = V.getOpcode();
3983 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3984 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3985 Index = SV->getMaskElt(Index);
3988 return DAG.getUNDEF(VT.getVectorElementType());
3990 int NumElems = VT.getVectorNumElements();
3991 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3992 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3995 // Recurse into target specific vector shuffles to find scalars.
3996 if (isTargetShuffle(Opcode)) {
3997 int NumElems = VT.getVectorNumElements();
3998 SmallVector<unsigned, 16> ShuffleMask;
4002 case X86ISD::SHUFPS:
4003 case X86ISD::SHUFPD:
4004 ImmN = N->getOperand(N->getNumOperands()-1);
4005 DecodeSHUFPSMask(NumElems,
4006 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4009 case X86ISD::PUNPCKHBW:
4010 case X86ISD::PUNPCKHWD:
4011 case X86ISD::PUNPCKHDQ:
4012 case X86ISD::PUNPCKHQDQ:
4013 DecodePUNPCKHMask(NumElems, ShuffleMask);
4015 case X86ISD::UNPCKHPS:
4016 case X86ISD::UNPCKHPD:
4017 DecodeUNPCKHPMask(NumElems, ShuffleMask);
4019 case X86ISD::PUNPCKLBW:
4020 case X86ISD::PUNPCKLWD:
4021 case X86ISD::PUNPCKLDQ:
4022 case X86ISD::PUNPCKLQDQ:
4023 DecodePUNPCKLMask(VT, ShuffleMask);
4025 case X86ISD::UNPCKLPS:
4026 case X86ISD::UNPCKLPD:
4027 case X86ISD::VUNPCKLPS:
4028 case X86ISD::VUNPCKLPD:
4029 case X86ISD::VUNPCKLPSY:
4030 case X86ISD::VUNPCKLPDY:
4031 DecodeUNPCKLPMask(VT, ShuffleMask);
4033 case X86ISD::MOVHLPS:
4034 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4036 case X86ISD::MOVLHPS:
4037 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4039 case X86ISD::PSHUFD:
4040 ImmN = N->getOperand(N->getNumOperands()-1);
4041 DecodePSHUFMask(NumElems,
4042 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4045 case X86ISD::PSHUFHW:
4046 ImmN = N->getOperand(N->getNumOperands()-1);
4047 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4050 case X86ISD::PSHUFLW:
4051 ImmN = N->getOperand(N->getNumOperands()-1);
4052 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4056 case X86ISD::MOVSD: {
4057 // The index 0 always comes from the first element of the second source,
4058 // this is why MOVSS and MOVSD are used in the first place. The other
4059 // elements come from the other positions of the first source vector.
4060 unsigned OpNum = (Index == 0) ? 1 : 0;
4061 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4065 assert("not implemented for target shuffle node");
4069 Index = ShuffleMask[Index];
4071 return DAG.getUNDEF(VT.getVectorElementType());
4073 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4074 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4078 // Actual nodes that may contain scalar elements
4079 if (Opcode == ISD::BITCAST) {
4080 V = V.getOperand(0);
4081 EVT SrcVT = V.getValueType();
4082 unsigned NumElems = VT.getVectorNumElements();
4084 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4088 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4089 return (Index == 0) ? V.getOperand(0)
4090 : DAG.getUNDEF(VT.getVectorElementType());
4092 if (V.getOpcode() == ISD::BUILD_VECTOR)
4093 return V.getOperand(Index);
4098 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4099 /// shuffle operation which come from a consecutively from a zero. The
4100 /// search can start in two different directions, from left or right.
4102 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4103 bool ZerosFromLeft, SelectionDAG &DAG) {
4106 while (i < NumElems) {
4107 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4108 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4109 if (!(Elt.getNode() &&
4110 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4118 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4119 /// MaskE correspond consecutively to elements from one of the vector operands,
4120 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4122 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4123 int OpIdx, int NumElems, unsigned &OpNum) {
4124 bool SeenV1 = false;
4125 bool SeenV2 = false;
4127 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4128 int Idx = SVOp->getMaskElt(i);
4129 // Ignore undef indicies
4138 // Only accept consecutive elements from the same vector
4139 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4143 OpNum = SeenV1 ? 0 : 1;
4147 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4148 /// logical left shift of a vector.
4149 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4150 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4151 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4152 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4153 false /* check zeros from right */, DAG);
4159 // Considering the elements in the mask that are not consecutive zeros,
4160 // check if they consecutively come from only one of the source vectors.
4162 // V1 = {X, A, B, C} 0
4164 // vector_shuffle V1, V2 <1, 2, 3, X>
4166 if (!isShuffleMaskConsecutive(SVOp,
4167 0, // Mask Start Index
4168 NumElems-NumZeros-1, // Mask End Index
4169 NumZeros, // Where to start looking in the src vector
4170 NumElems, // Number of elements in vector
4171 OpSrc)) // Which source operand ?
4176 ShVal = SVOp->getOperand(OpSrc);
4180 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4181 /// logical left shift of a vector.
4182 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4183 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4184 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4185 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4186 true /* check zeros from left */, DAG);
4192 // Considering the elements in the mask that are not consecutive zeros,
4193 // check if they consecutively come from only one of the source vectors.
4195 // 0 { A, B, X, X } = V2
4197 // vector_shuffle V1, V2 <X, X, 4, 5>
4199 if (!isShuffleMaskConsecutive(SVOp,
4200 NumZeros, // Mask Start Index
4201 NumElems-1, // Mask End Index
4202 0, // Where to start looking in the src vector
4203 NumElems, // Number of elements in vector
4204 OpSrc)) // Which source operand ?
4209 ShVal = SVOp->getOperand(OpSrc);
4213 /// isVectorShift - Returns true if the shuffle can be implemented as a
4214 /// logical left or right shift of a vector.
4215 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4216 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4217 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4218 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4224 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4226 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4227 unsigned NumNonZero, unsigned NumZero,
4229 const TargetLowering &TLI) {
4233 DebugLoc dl = Op.getDebugLoc();
4236 for (unsigned i = 0; i < 16; ++i) {
4237 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4238 if (ThisIsNonZero && First) {
4240 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4242 V = DAG.getUNDEF(MVT::v8i16);
4247 SDValue ThisElt(0, 0), LastElt(0, 0);
4248 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4249 if (LastIsNonZero) {
4250 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4251 MVT::i16, Op.getOperand(i-1));
4253 if (ThisIsNonZero) {
4254 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4255 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4256 ThisElt, DAG.getConstant(8, MVT::i8));
4258 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4262 if (ThisElt.getNode())
4263 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4264 DAG.getIntPtrConstant(i/2));
4268 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4271 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4273 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4274 unsigned NumNonZero, unsigned NumZero,
4276 const TargetLowering &TLI) {
4280 DebugLoc dl = Op.getDebugLoc();
4283 for (unsigned i = 0; i < 8; ++i) {
4284 bool isNonZero = (NonZeros & (1 << i)) != 0;
4288 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4290 V = DAG.getUNDEF(MVT::v8i16);
4293 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4294 MVT::v8i16, V, Op.getOperand(i),
4295 DAG.getIntPtrConstant(i));
4302 /// getVShift - Return a vector logical shift node.
4304 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4305 unsigned NumBits, SelectionDAG &DAG,
4306 const TargetLowering &TLI, DebugLoc dl) {
4307 EVT ShVT = MVT::v2i64;
4308 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4309 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4310 return DAG.getNode(ISD::BITCAST, dl, VT,
4311 DAG.getNode(Opc, dl, ShVT, SrcOp,
4312 DAG.getConstant(NumBits,
4313 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4317 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4318 SelectionDAG &DAG) const {
4320 // Check if the scalar load can be widened into a vector load. And if
4321 // the address is "base + cst" see if the cst can be "absorbed" into
4322 // the shuffle mask.
4323 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4324 SDValue Ptr = LD->getBasePtr();
4325 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4327 EVT PVT = LD->getValueType(0);
4328 if (PVT != MVT::i32 && PVT != MVT::f32)
4333 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4334 FI = FINode->getIndex();
4336 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4337 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4338 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4339 Offset = Ptr.getConstantOperandVal(1);
4340 Ptr = Ptr.getOperand(0);
4345 SDValue Chain = LD->getChain();
4346 // Make sure the stack object alignment is at least 16.
4347 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4348 if (DAG.InferPtrAlignment(Ptr) < 16) {
4349 if (MFI->isFixedObjectIndex(FI)) {
4350 // Can't change the alignment. FIXME: It's possible to compute
4351 // the exact stack offset and reference FI + adjust offset instead.
4352 // If someone *really* cares about this. That's the way to implement it.
4355 MFI->setObjectAlignment(FI, 16);
4359 // (Offset % 16) must be multiple of 4. Then address is then
4360 // Ptr + (Offset & ~15).
4363 if ((Offset % 16) & 3)
4365 int64_t StartOffset = Offset & ~15;
4367 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4368 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4370 int EltNo = (Offset - StartOffset) >> 2;
4371 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4372 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4373 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4374 LD->getPointerInfo().getWithOffset(StartOffset),
4376 // Canonicalize it to a v4i32 shuffle.
4377 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4378 return DAG.getNode(ISD::BITCAST, dl, VT,
4379 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4380 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4386 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4387 /// vector of type 'VT', see if the elements can be replaced by a single large
4388 /// load which has the same value as a build_vector whose operands are 'elts'.
4390 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4392 /// FIXME: we'd also like to handle the case where the last elements are zero
4393 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4394 /// There's even a handy isZeroNode for that purpose.
4395 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4396 DebugLoc &DL, SelectionDAG &DAG) {
4397 EVT EltVT = VT.getVectorElementType();
4398 unsigned NumElems = Elts.size();
4400 LoadSDNode *LDBase = NULL;
4401 unsigned LastLoadedElt = -1U;
4403 // For each element in the initializer, see if we've found a load or an undef.
4404 // If we don't find an initial load element, or later load elements are
4405 // non-consecutive, bail out.
4406 for (unsigned i = 0; i < NumElems; ++i) {
4407 SDValue Elt = Elts[i];
4409 if (!Elt.getNode() ||
4410 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4413 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4415 LDBase = cast<LoadSDNode>(Elt.getNode());
4419 if (Elt.getOpcode() == ISD::UNDEF)
4422 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4423 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4428 // If we have found an entire vector of loads and undefs, then return a large
4429 // load of the entire vector width starting at the base pointer. If we found
4430 // consecutive loads for the low half, generate a vzext_load node.
4431 if (LastLoadedElt == NumElems - 1) {
4432 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4433 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4434 LDBase->getPointerInfo(),
4435 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4436 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4437 LDBase->getPointerInfo(),
4438 LDBase->isVolatile(), LDBase->isNonTemporal(),
4439 LDBase->getAlignment());
4440 } else if (NumElems == 4 && LastLoadedElt == 1) {
4441 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4442 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4443 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4445 LDBase->getMemOperand());
4446 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4452 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4453 DebugLoc dl = Op.getDebugLoc();
4455 EVT VT = Op.getValueType();
4456 EVT ExtVT = VT.getVectorElementType();
4458 unsigned NumElems = Op.getNumOperands();
4460 // For AVX-length vectors, build the individual 128-bit pieces and
4461 // use shuffles to put them in place.
4462 if (VT.getSizeInBits() > 256 &&
4463 Subtarget->hasAVX() &&
4464 !ISD::isBuildVectorAllZeros(Op.getNode())) {
4465 SmallVector<SDValue, 8> V;
4467 for (unsigned i = 0; i < NumElems; ++i) {
4468 V[i] = Op.getOperand(i);
4471 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4473 // Build the lower subvector.
4474 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4475 // Build the upper subvector.
4476 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4479 return ConcatVectors(Lower, Upper, DAG);
4482 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4483 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4484 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4485 // is present, so AllOnes is ignored.
4486 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4487 (Op.getValueType().getSizeInBits() != 256 &&
4488 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4489 // Canonicalize this to <4 x i32> (SSE) to
4490 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4491 // eliminated on x86-32 hosts.
4492 if (Op.getValueType() == MVT::v4i32)
4495 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4496 return getOnesVector(Op.getValueType(), DAG, dl);
4497 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4500 unsigned EVTBits = ExtVT.getSizeInBits();
4502 unsigned NumZero = 0;
4503 unsigned NumNonZero = 0;
4504 unsigned NonZeros = 0;
4505 bool IsAllConstants = true;
4506 SmallSet<SDValue, 8> Values;
4507 for (unsigned i = 0; i < NumElems; ++i) {
4508 SDValue Elt = Op.getOperand(i);
4509 if (Elt.getOpcode() == ISD::UNDEF)
4512 if (Elt.getOpcode() != ISD::Constant &&
4513 Elt.getOpcode() != ISD::ConstantFP)
4514 IsAllConstants = false;
4515 if (X86::isZeroNode(Elt))
4518 NonZeros |= (1 << i);
4523 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4524 if (NumNonZero == 0)
4525 return DAG.getUNDEF(VT);
4527 // Special case for single non-zero, non-undef, element.
4528 if (NumNonZero == 1) {
4529 unsigned Idx = CountTrailingZeros_32(NonZeros);
4530 SDValue Item = Op.getOperand(Idx);
4532 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4533 // the value are obviously zero, truncate the value to i32 and do the
4534 // insertion that way. Only do this if the value is non-constant or if the
4535 // value is a constant being inserted into element 0. It is cheaper to do
4536 // a constant pool load than it is to do a movd + shuffle.
4537 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4538 (!IsAllConstants || Idx == 0)) {
4539 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4541 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4542 EVT VecVT = MVT::v4i32;
4543 unsigned VecElts = 4;
4545 // Truncate the value (which may itself be a constant) to i32, and
4546 // convert it to a vector with movd (S2V+shuffle to zero extend).
4547 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4548 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4549 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4550 Subtarget->hasSSE2(), DAG);
4552 // Now we have our 32-bit value zero extended in the low element of
4553 // a vector. If Idx != 0, swizzle it into place.
4555 SmallVector<int, 4> Mask;
4556 Mask.push_back(Idx);
4557 for (unsigned i = 1; i != VecElts; ++i)
4559 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4560 DAG.getUNDEF(Item.getValueType()),
4563 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4567 // If we have a constant or non-constant insertion into the low element of
4568 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4569 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4570 // depending on what the source datatype is.
4573 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4574 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4575 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4576 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4577 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4578 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4580 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4581 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4582 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4583 EVT MiddleVT = MVT::v4i32;
4584 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4585 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4586 Subtarget->hasSSE2(), DAG);
4587 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4591 // Is it a vector logical left shift?
4592 if (NumElems == 2 && Idx == 1 &&
4593 X86::isZeroNode(Op.getOperand(0)) &&
4594 !X86::isZeroNode(Op.getOperand(1))) {
4595 unsigned NumBits = VT.getSizeInBits();
4596 return getVShift(true, VT,
4597 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4598 VT, Op.getOperand(1)),
4599 NumBits/2, DAG, *this, dl);
4602 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4605 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4606 // is a non-constant being inserted into an element other than the low one,
4607 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4608 // movd/movss) to move this into the low element, then shuffle it into
4610 if (EVTBits == 32) {
4611 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4613 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4614 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4615 Subtarget->hasSSE2(), DAG);
4616 SmallVector<int, 8> MaskVec;
4617 for (unsigned i = 0; i < NumElems; i++)
4618 MaskVec.push_back(i == Idx ? 0 : 1);
4619 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4623 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4624 if (Values.size() == 1) {
4625 if (EVTBits == 32) {
4626 // Instead of a shuffle like this:
4627 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4628 // Check if it's possible to issue this instead.
4629 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4630 unsigned Idx = CountTrailingZeros_32(NonZeros);
4631 SDValue Item = Op.getOperand(Idx);
4632 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4633 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4638 // A vector full of immediates; various special cases are already
4639 // handled, so this is best done with a single constant-pool load.
4643 // Let legalizer expand 2-wide build_vectors.
4644 if (EVTBits == 64) {
4645 if (NumNonZero == 1) {
4646 // One half is zero or undef.
4647 unsigned Idx = CountTrailingZeros_32(NonZeros);
4648 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4649 Op.getOperand(Idx));
4650 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4651 Subtarget->hasSSE2(), DAG);
4656 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4657 if (EVTBits == 8 && NumElems == 16) {
4658 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4660 if (V.getNode()) return V;
4663 if (EVTBits == 16 && NumElems == 8) {
4664 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4666 if (V.getNode()) return V;
4669 // If element VT is == 32 bits, turn it into a number of shuffles.
4670 SmallVector<SDValue, 8> V;
4672 if (NumElems == 4 && NumZero > 0) {
4673 for (unsigned i = 0; i < 4; ++i) {
4674 bool isZero = !(NonZeros & (1 << i));
4676 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4678 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4681 for (unsigned i = 0; i < 2; ++i) {
4682 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4685 V[i] = V[i*2]; // Must be a zero vector.
4688 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4691 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4694 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4699 SmallVector<int, 8> MaskVec;
4700 bool Reverse = (NonZeros & 0x3) == 2;
4701 for (unsigned i = 0; i < 2; ++i)
4702 MaskVec.push_back(Reverse ? 1-i : i);
4703 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4704 for (unsigned i = 0; i < 2; ++i)
4705 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4706 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4709 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4710 // Check for a build vector of consecutive loads.
4711 for (unsigned i = 0; i < NumElems; ++i)
4712 V[i] = Op.getOperand(i);
4714 // Check for elements which are consecutive loads.
4715 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4719 // For SSE 4.1, use insertps to put the high elements into the low element.
4720 if (getSubtarget()->hasSSE41()) {
4722 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4723 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4725 Result = DAG.getUNDEF(VT);
4727 for (unsigned i = 1; i < NumElems; ++i) {
4728 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4729 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4730 Op.getOperand(i), DAG.getIntPtrConstant(i));
4735 // Otherwise, expand into a number of unpckl*, start by extending each of
4736 // our (non-undef) elements to the full vector width with the element in the
4737 // bottom slot of the vector (which generates no code for SSE).
4738 for (unsigned i = 0; i < NumElems; ++i) {
4739 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4740 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4742 V[i] = DAG.getUNDEF(VT);
4745 // Next, we iteratively mix elements, e.g. for v4f32:
4746 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4747 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4748 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4749 unsigned EltStride = NumElems >> 1;
4750 while (EltStride != 0) {
4751 for (unsigned i = 0; i < EltStride; ++i) {
4752 // If V[i+EltStride] is undef and this is the first round of mixing,
4753 // then it is safe to just drop this shuffle: V[i] is already in the
4754 // right place, the one element (since it's the first round) being
4755 // inserted as undef can be dropped. This isn't safe for successive
4756 // rounds because they will permute elements within both vectors.
4757 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4758 EltStride == NumElems/2)
4761 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4771 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4772 // We support concatenate two MMX registers and place them in a MMX
4773 // register. This is better than doing a stack convert.
4774 DebugLoc dl = Op.getDebugLoc();
4775 EVT ResVT = Op.getValueType();
4776 assert(Op.getNumOperands() == 2);
4777 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4778 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4780 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4781 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4782 InVec = Op.getOperand(1);
4783 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4784 unsigned NumElts = ResVT.getVectorNumElements();
4785 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4786 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4787 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4789 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4790 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4791 Mask[0] = 0; Mask[1] = 2;
4792 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4794 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4797 // v8i16 shuffles - Prefer shuffles in the following order:
4798 // 1. [all] pshuflw, pshufhw, optional move
4799 // 2. [ssse3] 1 x pshufb
4800 // 3. [ssse3] 2 x pshufb + 1 x por
4801 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4803 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4804 SelectionDAG &DAG) const {
4805 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4806 SDValue V1 = SVOp->getOperand(0);
4807 SDValue V2 = SVOp->getOperand(1);
4808 DebugLoc dl = SVOp->getDebugLoc();
4809 SmallVector<int, 8> MaskVals;
4811 // Determine if more than 1 of the words in each of the low and high quadwords
4812 // of the result come from the same quadword of one of the two inputs. Undef
4813 // mask values count as coming from any quadword, for better codegen.
4814 SmallVector<unsigned, 4> LoQuad(4);
4815 SmallVector<unsigned, 4> HiQuad(4);
4816 BitVector InputQuads(4);
4817 for (unsigned i = 0; i < 8; ++i) {
4818 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4819 int EltIdx = SVOp->getMaskElt(i);
4820 MaskVals.push_back(EltIdx);
4829 InputQuads.set(EltIdx / 4);
4832 int BestLoQuad = -1;
4833 unsigned MaxQuad = 1;
4834 for (unsigned i = 0; i < 4; ++i) {
4835 if (LoQuad[i] > MaxQuad) {
4837 MaxQuad = LoQuad[i];
4841 int BestHiQuad = -1;
4843 for (unsigned i = 0; i < 4; ++i) {
4844 if (HiQuad[i] > MaxQuad) {
4846 MaxQuad = HiQuad[i];
4850 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4851 // of the two input vectors, shuffle them into one input vector so only a
4852 // single pshufb instruction is necessary. If There are more than 2 input
4853 // quads, disable the next transformation since it does not help SSSE3.
4854 bool V1Used = InputQuads[0] || InputQuads[1];
4855 bool V2Used = InputQuads[2] || InputQuads[3];
4856 if (Subtarget->hasSSSE3()) {
4857 if (InputQuads.count() == 2 && V1Used && V2Used) {
4858 BestLoQuad = InputQuads.find_first();
4859 BestHiQuad = InputQuads.find_next(BestLoQuad);
4861 if (InputQuads.count() > 2) {
4867 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4868 // the shuffle mask. If a quad is scored as -1, that means that it contains
4869 // words from all 4 input quadwords.
4871 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4872 SmallVector<int, 8> MaskV;
4873 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4874 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4875 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4876 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4877 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4878 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4880 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4881 // source words for the shuffle, to aid later transformations.
4882 bool AllWordsInNewV = true;
4883 bool InOrder[2] = { true, true };
4884 for (unsigned i = 0; i != 8; ++i) {
4885 int idx = MaskVals[i];
4887 InOrder[i/4] = false;
4888 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4890 AllWordsInNewV = false;
4894 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4895 if (AllWordsInNewV) {
4896 for (int i = 0; i != 8; ++i) {
4897 int idx = MaskVals[i];
4900 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4901 if ((idx != i) && idx < 4)
4903 if ((idx != i) && idx > 3)
4912 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4913 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4914 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4915 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4916 unsigned TargetMask = 0;
4917 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4918 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4919 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4920 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4921 V1 = NewV.getOperand(0);
4922 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4926 // If we have SSSE3, and all words of the result are from 1 input vector,
4927 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4928 // is present, fall back to case 4.
4929 if (Subtarget->hasSSSE3()) {
4930 SmallVector<SDValue,16> pshufbMask;
4932 // If we have elements from both input vectors, set the high bit of the
4933 // shuffle mask element to zero out elements that come from V2 in the V1
4934 // mask, and elements that come from V1 in the V2 mask, so that the two
4935 // results can be OR'd together.
4936 bool TwoInputs = V1Used && V2Used;
4937 for (unsigned i = 0; i != 8; ++i) {
4938 int EltIdx = MaskVals[i] * 2;
4939 if (TwoInputs && (EltIdx >= 16)) {
4940 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4941 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4944 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4945 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4947 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4948 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4949 DAG.getNode(ISD::BUILD_VECTOR, dl,
4950 MVT::v16i8, &pshufbMask[0], 16));
4952 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4954 // Calculate the shuffle mask for the second input, shuffle it, and
4955 // OR it with the first shuffled input.
4957 for (unsigned i = 0; i != 8; ++i) {
4958 int EltIdx = MaskVals[i] * 2;
4960 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4961 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4964 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4965 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4967 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4968 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4969 DAG.getNode(ISD::BUILD_VECTOR, dl,
4970 MVT::v16i8, &pshufbMask[0], 16));
4971 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4972 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4975 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4976 // and update MaskVals with new element order.
4977 BitVector InOrder(8);
4978 if (BestLoQuad >= 0) {
4979 SmallVector<int, 8> MaskV;
4980 for (int i = 0; i != 4; ++i) {
4981 int idx = MaskVals[i];
4983 MaskV.push_back(-1);
4985 } else if ((idx / 4) == BestLoQuad) {
4986 MaskV.push_back(idx & 3);
4989 MaskV.push_back(-1);
4992 for (unsigned i = 4; i != 8; ++i)
4994 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4997 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4998 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5000 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5004 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5005 // and update MaskVals with the new element order.
5006 if (BestHiQuad >= 0) {
5007 SmallVector<int, 8> MaskV;
5008 for (unsigned i = 0; i != 4; ++i)
5010 for (unsigned i = 4; i != 8; ++i) {
5011 int idx = MaskVals[i];
5013 MaskV.push_back(-1);
5015 } else if ((idx / 4) == BestHiQuad) {
5016 MaskV.push_back((idx & 3) + 4);
5019 MaskV.push_back(-1);
5022 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5025 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5026 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5028 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5032 // In case BestHi & BestLo were both -1, which means each quadword has a word
5033 // from each of the four input quadwords, calculate the InOrder bitvector now
5034 // before falling through to the insert/extract cleanup.
5035 if (BestLoQuad == -1 && BestHiQuad == -1) {
5037 for (int i = 0; i != 8; ++i)
5038 if (MaskVals[i] < 0 || MaskVals[i] == i)
5042 // The other elements are put in the right place using pextrw and pinsrw.
5043 for (unsigned i = 0; i != 8; ++i) {
5046 int EltIdx = MaskVals[i];
5049 SDValue ExtOp = (EltIdx < 8)
5050 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5051 DAG.getIntPtrConstant(EltIdx))
5052 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5053 DAG.getIntPtrConstant(EltIdx - 8));
5054 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5055 DAG.getIntPtrConstant(i));
5060 // v16i8 shuffles - Prefer shuffles in the following order:
5061 // 1. [ssse3] 1 x pshufb
5062 // 2. [ssse3] 2 x pshufb + 1 x por
5063 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5065 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5067 const X86TargetLowering &TLI) {
5068 SDValue V1 = SVOp->getOperand(0);
5069 SDValue V2 = SVOp->getOperand(1);
5070 DebugLoc dl = SVOp->getDebugLoc();
5071 SmallVector<int, 16> MaskVals;
5072 SVOp->getMask(MaskVals);
5074 // If we have SSSE3, case 1 is generated when all result bytes come from
5075 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5076 // present, fall back to case 3.
5077 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5080 for (unsigned i = 0; i < 16; ++i) {
5081 int EltIdx = MaskVals[i];
5090 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5091 if (TLI.getSubtarget()->hasSSSE3()) {
5092 SmallVector<SDValue,16> pshufbMask;
5094 // If all result elements are from one input vector, then only translate
5095 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5097 // Otherwise, we have elements from both input vectors, and must zero out
5098 // elements that come from V2 in the first mask, and V1 in the second mask
5099 // so that we can OR them together.
5100 bool TwoInputs = !(V1Only || V2Only);
5101 for (unsigned i = 0; i != 16; ++i) {
5102 int EltIdx = MaskVals[i];
5103 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5104 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5107 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5109 // If all the elements are from V2, assign it to V1 and return after
5110 // building the first pshufb.
5113 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5114 DAG.getNode(ISD::BUILD_VECTOR, dl,
5115 MVT::v16i8, &pshufbMask[0], 16));
5119 // Calculate the shuffle mask for the second input, shuffle it, and
5120 // OR it with the first shuffled input.
5122 for (unsigned i = 0; i != 16; ++i) {
5123 int EltIdx = MaskVals[i];
5125 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5128 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5130 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5131 DAG.getNode(ISD::BUILD_VECTOR, dl,
5132 MVT::v16i8, &pshufbMask[0], 16));
5133 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5136 // No SSSE3 - Calculate in place words and then fix all out of place words
5137 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5138 // the 16 different words that comprise the two doublequadword input vectors.
5139 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5140 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5141 SDValue NewV = V2Only ? V2 : V1;
5142 for (int i = 0; i != 8; ++i) {
5143 int Elt0 = MaskVals[i*2];
5144 int Elt1 = MaskVals[i*2+1];
5146 // This word of the result is all undef, skip it.
5147 if (Elt0 < 0 && Elt1 < 0)
5150 // This word of the result is already in the correct place, skip it.
5151 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5153 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5156 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5157 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5160 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5161 // using a single extract together, load it and store it.
5162 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5163 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5164 DAG.getIntPtrConstant(Elt1 / 2));
5165 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5166 DAG.getIntPtrConstant(i));
5170 // If Elt1 is defined, extract it from the appropriate source. If the
5171 // source byte is not also odd, shift the extracted word left 8 bits
5172 // otherwise clear the bottom 8 bits if we need to do an or.
5174 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5175 DAG.getIntPtrConstant(Elt1 / 2));
5176 if ((Elt1 & 1) == 0)
5177 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5179 TLI.getShiftAmountTy(InsElt.getValueType())));
5181 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5182 DAG.getConstant(0xFF00, MVT::i16));
5184 // If Elt0 is defined, extract it from the appropriate source. If the
5185 // source byte is not also even, shift the extracted word right 8 bits. If
5186 // Elt1 was also defined, OR the extracted values together before
5187 // inserting them in the result.
5189 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5190 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5191 if ((Elt0 & 1) != 0)
5192 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5194 TLI.getShiftAmountTy(InsElt0.getValueType())));
5196 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5197 DAG.getConstant(0x00FF, MVT::i16));
5198 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5201 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5202 DAG.getIntPtrConstant(i));
5204 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5207 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5208 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5209 /// done when every pair / quad of shuffle mask elements point to elements in
5210 /// the right sequence. e.g.
5211 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5213 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5214 SelectionDAG &DAG, DebugLoc dl) {
5215 EVT VT = SVOp->getValueType(0);
5216 SDValue V1 = SVOp->getOperand(0);
5217 SDValue V2 = SVOp->getOperand(1);
5218 unsigned NumElems = VT.getVectorNumElements();
5219 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5221 switch (VT.getSimpleVT().SimpleTy) {
5222 default: assert(false && "Unexpected!");
5223 case MVT::v4f32: NewVT = MVT::v2f64; break;
5224 case MVT::v4i32: NewVT = MVT::v2i64; break;
5225 case MVT::v8i16: NewVT = MVT::v4i32; break;
5226 case MVT::v16i8: NewVT = MVT::v4i32; break;
5229 int Scale = NumElems / NewWidth;
5230 SmallVector<int, 8> MaskVec;
5231 for (unsigned i = 0; i < NumElems; i += Scale) {
5233 for (int j = 0; j < Scale; ++j) {
5234 int EltIdx = SVOp->getMaskElt(i+j);
5238 StartIdx = EltIdx - (EltIdx % Scale);
5239 if (EltIdx != StartIdx + j)
5243 MaskVec.push_back(-1);
5245 MaskVec.push_back(StartIdx / Scale);
5248 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5249 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5250 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5253 /// getVZextMovL - Return a zero-extending vector move low node.
5255 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5256 SDValue SrcOp, SelectionDAG &DAG,
5257 const X86Subtarget *Subtarget, DebugLoc dl) {
5258 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5259 LoadSDNode *LD = NULL;
5260 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5261 LD = dyn_cast<LoadSDNode>(SrcOp);
5263 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5265 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5266 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5267 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5268 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5269 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5271 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5272 return DAG.getNode(ISD::BITCAST, dl, VT,
5273 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5274 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5282 return DAG.getNode(ISD::BITCAST, dl, VT,
5283 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5284 DAG.getNode(ISD::BITCAST, dl,
5288 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5291 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5292 SDValue V1 = SVOp->getOperand(0);
5293 SDValue V2 = SVOp->getOperand(1);
5294 DebugLoc dl = SVOp->getDebugLoc();
5295 EVT VT = SVOp->getValueType(0);
5297 SmallVector<std::pair<int, int>, 8> Locs;
5299 SmallVector<int, 8> Mask1(4U, -1);
5300 SmallVector<int, 8> PermMask;
5301 SVOp->getMask(PermMask);
5305 for (unsigned i = 0; i != 4; ++i) {
5306 int Idx = PermMask[i];
5308 Locs[i] = std::make_pair(-1, -1);
5310 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5312 Locs[i] = std::make_pair(0, NumLo);
5316 Locs[i] = std::make_pair(1, NumHi);
5318 Mask1[2+NumHi] = Idx;
5324 if (NumLo <= 2 && NumHi <= 2) {
5325 // If no more than two elements come from either vector. This can be
5326 // implemented with two shuffles. First shuffle gather the elements.
5327 // The second shuffle, which takes the first shuffle as both of its
5328 // vector operands, put the elements into the right order.
5329 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5331 SmallVector<int, 8> Mask2(4U, -1);
5333 for (unsigned i = 0; i != 4; ++i) {
5334 if (Locs[i].first == -1)
5337 unsigned Idx = (i < 2) ? 0 : 4;
5338 Idx += Locs[i].first * 2 + Locs[i].second;
5343 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5344 } else if (NumLo == 3 || NumHi == 3) {
5345 // Otherwise, we must have three elements from one vector, call it X, and
5346 // one element from the other, call it Y. First, use a shufps to build an
5347 // intermediate vector with the one element from Y and the element from X
5348 // that will be in the same half in the final destination (the indexes don't
5349 // matter). Then, use a shufps to build the final vector, taking the half
5350 // containing the element from Y from the intermediate, and the other half
5353 // Normalize it so the 3 elements come from V1.
5354 CommuteVectorShuffleMask(PermMask, VT);
5358 // Find the element from V2.
5360 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5361 int Val = PermMask[HiIndex];
5368 Mask1[0] = PermMask[HiIndex];
5370 Mask1[2] = PermMask[HiIndex^1];
5372 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5375 Mask1[0] = PermMask[0];
5376 Mask1[1] = PermMask[1];
5377 Mask1[2] = HiIndex & 1 ? 6 : 4;
5378 Mask1[3] = HiIndex & 1 ? 4 : 6;
5379 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5381 Mask1[0] = HiIndex & 1 ? 2 : 0;
5382 Mask1[1] = HiIndex & 1 ? 0 : 2;
5383 Mask1[2] = PermMask[2];
5384 Mask1[3] = PermMask[3];
5389 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5393 // Break it into (shuffle shuffle_hi, shuffle_lo).
5396 SmallVector<int,8> LoMask(4U, -1);
5397 SmallVector<int,8> HiMask(4U, -1);
5399 SmallVector<int,8> *MaskPtr = &LoMask;
5400 unsigned MaskIdx = 0;
5403 for (unsigned i = 0; i != 4; ++i) {
5410 int Idx = PermMask[i];
5412 Locs[i] = std::make_pair(-1, -1);
5413 } else if (Idx < 4) {
5414 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5415 (*MaskPtr)[LoIdx] = Idx;
5418 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5419 (*MaskPtr)[HiIdx] = Idx;
5424 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5425 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5426 SmallVector<int, 8> MaskOps;
5427 for (unsigned i = 0; i != 4; ++i) {
5428 if (Locs[i].first == -1) {
5429 MaskOps.push_back(-1);
5431 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5432 MaskOps.push_back(Idx);
5435 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5438 static bool MayFoldVectorLoad(SDValue V) {
5439 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5440 V = V.getOperand(0);
5441 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5442 V = V.getOperand(0);
5448 // FIXME: the version above should always be used. Since there's
5449 // a bug where several vector shuffles can't be folded because the
5450 // DAG is not updated during lowering and a node claims to have two
5451 // uses while it only has one, use this version, and let isel match
5452 // another instruction if the load really happens to have more than
5453 // one use. Remove this version after this bug get fixed.
5454 // rdar://8434668, PR8156
5455 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5456 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5457 V = V.getOperand(0);
5458 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5459 V = V.getOperand(0);
5460 if (ISD::isNormalLoad(V.getNode()))
5465 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5466 /// a vector extract, and if both can be later optimized into a single load.
5467 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5468 /// here because otherwise a target specific shuffle node is going to be
5469 /// emitted for this shuffle, and the optimization not done.
5470 /// FIXME: This is probably not the best approach, but fix the problem
5471 /// until the right path is decided.
5473 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5474 const TargetLowering &TLI) {
5475 EVT VT = V.getValueType();
5476 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5478 // Be sure that the vector shuffle is present in a pattern like this:
5479 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5483 SDNode *N = *V.getNode()->use_begin();
5484 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5487 SDValue EltNo = N->getOperand(1);
5488 if (!isa<ConstantSDNode>(EltNo))
5491 // If the bit convert changed the number of elements, it is unsafe
5492 // to examine the mask.
5493 bool HasShuffleIntoBitcast = false;
5494 if (V.getOpcode() == ISD::BITCAST) {
5495 EVT SrcVT = V.getOperand(0).getValueType();
5496 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5498 V = V.getOperand(0);
5499 HasShuffleIntoBitcast = true;
5502 // Select the input vector, guarding against out of range extract vector.
5503 unsigned NumElems = VT.getVectorNumElements();
5504 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5505 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5506 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5508 // Skip one more bit_convert if necessary
5509 if (V.getOpcode() == ISD::BITCAST)
5510 V = V.getOperand(0);
5512 if (ISD::isNormalLoad(V.getNode())) {
5513 // Is the original load suitable?
5514 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5516 // FIXME: avoid the multi-use bug that is preventing lots of
5517 // of foldings to be detected, this is still wrong of course, but
5518 // give the temporary desired behavior, and if it happens that
5519 // the load has real more uses, during isel it will not fold, and
5520 // will generate poor code.
5521 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5524 if (!HasShuffleIntoBitcast)
5527 // If there's a bitcast before the shuffle, check if the load type and
5528 // alignment is valid.
5529 unsigned Align = LN0->getAlignment();
5531 TLI.getTargetData()->getABITypeAlignment(
5532 VT.getTypeForEVT(*DAG.getContext()));
5534 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5542 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5543 EVT VT = Op.getValueType();
5545 // Canonizalize to v2f64.
5546 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5547 return DAG.getNode(ISD::BITCAST, dl, VT,
5548 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5553 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5555 SDValue V1 = Op.getOperand(0);
5556 SDValue V2 = Op.getOperand(1);
5557 EVT VT = Op.getValueType();
5559 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5561 if (HasSSE2 && VT == MVT::v2f64)
5562 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5565 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5569 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5570 SDValue V1 = Op.getOperand(0);
5571 SDValue V2 = Op.getOperand(1);
5572 EVT VT = Op.getValueType();
5574 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5575 "unsupported shuffle type");
5577 if (V2.getOpcode() == ISD::UNDEF)
5581 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5585 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5586 SDValue V1 = Op.getOperand(0);
5587 SDValue V2 = Op.getOperand(1);
5588 EVT VT = Op.getValueType();
5589 unsigned NumElems = VT.getVectorNumElements();
5591 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5592 // operand of these instructions is only memory, so check if there's a
5593 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5595 bool CanFoldLoad = false;
5597 // Trivial case, when V2 comes from a load.
5598 if (MayFoldVectorLoad(V2))
5601 // When V1 is a load, it can be folded later into a store in isel, example:
5602 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5604 // (MOVLPSmr addr:$src1, VR128:$src2)
5605 // So, recognize this potential and also use MOVLPS or MOVLPD
5606 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5609 // Both of them can't be memory operations though.
5610 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5611 CanFoldLoad = false;
5614 if (HasSSE2 && NumElems == 2)
5615 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5618 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5621 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5622 // movl and movlp will both match v2i64, but v2i64 is never matched by
5623 // movl earlier because we make it strict to avoid messing with the movlp load
5624 // folding logic (see the code above getMOVLP call). Match it here then,
5625 // this is horrible, but will stay like this until we move all shuffle
5626 // matching to x86 specific nodes. Note that for the 1st condition all
5627 // types are matched with movsd.
5628 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5629 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5631 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5634 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5636 // Invert the operand order and use SHUFPS to match it.
5637 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5638 X86::getShuffleSHUFImmediate(SVOp), DAG);
5641 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5642 switch(VT.getSimpleVT().SimpleTy) {
5643 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5644 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5646 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5648 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5649 case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5650 case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5651 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5652 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5654 llvm_unreachable("Unknown type for unpckl");
5659 static inline unsigned getUNPCKHOpcode(EVT VT) {
5660 switch(VT.getSimpleVT().SimpleTy) {
5661 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5662 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5663 case MVT::v4f32: return X86ISD::UNPCKHPS;
5664 case MVT::v2f64: return X86ISD::UNPCKHPD;
5665 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5666 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5668 llvm_unreachable("Unknown type for unpckh");
5674 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5675 const TargetLowering &TLI,
5676 const X86Subtarget *Subtarget) {
5677 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5678 EVT VT = Op.getValueType();
5679 DebugLoc dl = Op.getDebugLoc();
5680 SDValue V1 = Op.getOperand(0);
5681 SDValue V2 = Op.getOperand(1);
5683 if (isZeroShuffle(SVOp))
5684 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5686 // Handle splat operations
5687 if (SVOp->isSplat()) {
5688 // Special case, this is the only place now where it's
5689 // allowed to return a vector_shuffle operation without
5690 // using a target specific node, because *hopefully* it
5691 // will be optimized away by the dag combiner.
5692 if (VT.getVectorNumElements() <= 4 &&
5693 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5696 // Handle splats by matching through known masks
5697 if (VT.getVectorNumElements() <= 4)
5700 // Canonicalize all of the remaining to v4f32.
5701 return PromoteSplat(SVOp, DAG);
5704 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5706 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5707 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5708 if (NewOp.getNode())
5709 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5710 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5711 // FIXME: Figure out a cleaner way to do this.
5712 // Try to make use of movq to zero out the top part.
5713 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5714 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5715 if (NewOp.getNode()) {
5716 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5717 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5718 DAG, Subtarget, dl);
5720 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5721 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5722 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5723 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5724 DAG, Subtarget, dl);
5731 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5732 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5733 SDValue V1 = Op.getOperand(0);
5734 SDValue V2 = Op.getOperand(1);
5735 EVT VT = Op.getValueType();
5736 DebugLoc dl = Op.getDebugLoc();
5737 unsigned NumElems = VT.getVectorNumElements();
5738 bool isMMX = VT.getSizeInBits() == 64;
5739 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5740 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5741 bool V1IsSplat = false;
5742 bool V2IsSplat = false;
5743 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5744 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5745 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5746 MachineFunction &MF = DAG.getMachineFunction();
5747 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5749 // Shuffle operations on MMX not supported.
5753 // Vector shuffle lowering takes 3 steps:
5755 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5756 // narrowing and commutation of operands should be handled.
5757 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5759 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5760 // so the shuffle can be broken into other shuffles and the legalizer can
5761 // try the lowering again.
5763 // The general ideia is that no vector_shuffle operation should be left to
5764 // be matched during isel, all of them must be converted to a target specific
5767 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5768 // narrowing and commutation of operands should be handled. The actual code
5769 // doesn't include all of those, work in progress...
5770 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5771 if (NewOp.getNode())
5774 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5775 // unpckh_undef). Only use pshufd if speed is more important than size.
5776 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5777 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5778 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5779 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5780 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5781 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5783 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5784 RelaxedMayFoldVectorLoad(V1))
5785 return getMOVDDup(Op, dl, V1, DAG);
5787 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5788 return getMOVHighToLow(Op, dl, DAG);
5790 // Use to match splats
5791 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5792 (VT == MVT::v2f64 || VT == MVT::v2i64))
5793 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5795 if (X86::isPSHUFDMask(SVOp)) {
5796 // The actual implementation will match the mask in the if above and then
5797 // during isel it can match several different instructions, not only pshufd
5798 // as its name says, sad but true, emulate the behavior for now...
5799 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5800 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5802 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5804 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5805 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5807 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5808 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5811 if (VT == MVT::v4f32)
5812 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5816 // Check if this can be converted into a logical shift.
5817 bool isLeft = false;
5820 bool isShift = getSubtarget()->hasSSE2() &&
5821 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5822 if (isShift && ShVal.hasOneUse()) {
5823 // If the shifted value has multiple uses, it may be cheaper to use
5824 // v_set0 + movlhps or movhlps, etc.
5825 EVT EltVT = VT.getVectorElementType();
5826 ShAmt *= EltVT.getSizeInBits();
5827 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5830 if (X86::isMOVLMask(SVOp)) {
5833 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5834 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5835 if (!X86::isMOVLPMask(SVOp)) {
5836 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5837 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5839 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5840 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5844 // FIXME: fold these into legal mask.
5845 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5846 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5848 if (X86::isMOVHLPSMask(SVOp))
5849 return getMOVHighToLow(Op, dl, DAG);
5851 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5852 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5854 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5855 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5857 if (X86::isMOVLPMask(SVOp))
5858 return getMOVLP(Op, dl, DAG, HasSSE2);
5860 if (ShouldXformToMOVHLPS(SVOp) ||
5861 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5862 return CommuteVectorShuffle(SVOp, DAG);
5865 // No better options. Use a vshl / vsrl.
5866 EVT EltVT = VT.getVectorElementType();
5867 ShAmt *= EltVT.getSizeInBits();
5868 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5871 bool Commuted = false;
5872 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5873 // 1,1,1,1 -> v8i16 though.
5874 V1IsSplat = isSplatVector(V1.getNode());
5875 V2IsSplat = isSplatVector(V2.getNode());
5877 // Canonicalize the splat or undef, if present, to be on the RHS.
5878 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5879 Op = CommuteVectorShuffle(SVOp, DAG);
5880 SVOp = cast<ShuffleVectorSDNode>(Op);
5881 V1 = SVOp->getOperand(0);
5882 V2 = SVOp->getOperand(1);
5883 std::swap(V1IsSplat, V2IsSplat);
5884 std::swap(V1IsUndef, V2IsUndef);
5888 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5889 // Shuffling low element of v1 into undef, just return v1.
5892 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5893 // the instruction selector will not match, so get a canonical MOVL with
5894 // swapped operands to undo the commute.
5895 return getMOVL(DAG, dl, VT, V2, V1);
5898 if (X86::isUNPCKLMask(SVOp))
5899 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5900 dl, VT, V1, V2, DAG);
5902 if (X86::isUNPCKHMask(SVOp))
5903 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5906 // Normalize mask so all entries that point to V2 points to its first
5907 // element then try to match unpck{h|l} again. If match, return a
5908 // new vector_shuffle with the corrected mask.
5909 SDValue NewMask = NormalizeMask(SVOp, DAG);
5910 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5911 if (NSVOp != SVOp) {
5912 if (X86::isUNPCKLMask(NSVOp, true)) {
5914 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5921 // Commute is back and try unpck* again.
5922 // FIXME: this seems wrong.
5923 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5924 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5926 if (X86::isUNPCKLMask(NewSVOp))
5927 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5928 dl, VT, V2, V1, DAG);
5930 if (X86::isUNPCKHMask(NewSVOp))
5931 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5934 // Normalize the node to match x86 shuffle ops if needed
5935 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5936 return CommuteVectorShuffle(SVOp, DAG);
5938 // The checks below are all present in isShuffleMaskLegal, but they are
5939 // inlined here right now to enable us to directly emit target specific
5940 // nodes, and remove one by one until they don't return Op anymore.
5941 SmallVector<int, 16> M;
5944 if (isPALIGNRMask(M, VT, HasSSSE3))
5945 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5946 X86::getShufflePALIGNRImmediate(SVOp),
5949 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5950 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5951 if (VT == MVT::v2f64) {
5952 X86ISD::NodeType Opcode =
5953 getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5954 return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5956 if (VT == MVT::v2i64)
5957 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5960 if (isPSHUFHWMask(M, VT))
5961 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5962 X86::getShufflePSHUFHWImmediate(SVOp),
5965 if (isPSHUFLWMask(M, VT))
5966 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5967 X86::getShufflePSHUFLWImmediate(SVOp),
5970 if (isSHUFPMask(M, VT)) {
5971 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5972 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5973 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5975 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5976 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5980 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5981 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5982 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5983 dl, VT, V1, V1, DAG);
5984 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5985 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5986 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5988 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5989 if (VT == MVT::v8i16) {
5990 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5991 if (NewOp.getNode())
5995 if (VT == MVT::v16i8) {
5996 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5997 if (NewOp.getNode())
6001 // Handle all 4 wide cases with a number of shuffles.
6003 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
6009 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6010 SelectionDAG &DAG) const {
6011 EVT VT = Op.getValueType();
6012 DebugLoc dl = Op.getDebugLoc();
6013 if (VT.getSizeInBits() == 8) {
6014 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6015 Op.getOperand(0), Op.getOperand(1));
6016 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6017 DAG.getValueType(VT));
6018 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6019 } else if (VT.getSizeInBits() == 16) {
6020 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6021 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6023 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6024 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6025 DAG.getNode(ISD::BITCAST, dl,
6029 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6030 Op.getOperand(0), Op.getOperand(1));
6031 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6032 DAG.getValueType(VT));
6033 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6034 } else if (VT == MVT::f32) {
6035 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6036 // the result back to FR32 register. It's only worth matching if the
6037 // result has a single use which is a store or a bitcast to i32. And in
6038 // the case of a store, it's not worth it if the index is a constant 0,
6039 // because a MOVSSmr can be used instead, which is smaller and faster.
6040 if (!Op.hasOneUse())
6042 SDNode *User = *Op.getNode()->use_begin();
6043 if ((User->getOpcode() != ISD::STORE ||
6044 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6045 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6046 (User->getOpcode() != ISD::BITCAST ||
6047 User->getValueType(0) != MVT::i32))
6049 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6050 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6053 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6054 } else if (VT == MVT::i32) {
6055 // ExtractPS works with constant index.
6056 if (isa<ConstantSDNode>(Op.getOperand(1)))
6064 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6065 SelectionDAG &DAG) const {
6066 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6069 SDValue Vec = Op.getOperand(0);
6070 EVT VecVT = Vec.getValueType();
6072 // If this is a 256-bit vector result, first extract the 128-bit
6073 // vector and then extract from the 128-bit vector.
6074 if (VecVT.getSizeInBits() > 128) {
6075 DebugLoc dl = Op.getNode()->getDebugLoc();
6076 unsigned NumElems = VecVT.getVectorNumElements();
6077 SDValue Idx = Op.getOperand(1);
6079 if (!isa<ConstantSDNode>(Idx))
6082 unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6083 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6085 // Get the 128-bit vector.
6086 bool Upper = IdxVal >= ExtractNumElems;
6087 Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6090 SDValue ScaledIdx = Idx;
6092 ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6093 DAG.getConstant(ExtractNumElems,
6094 Idx.getValueType()));
6095 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6099 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6101 if (Subtarget->hasSSE41()) {
6102 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6107 EVT VT = Op.getValueType();
6108 DebugLoc dl = Op.getDebugLoc();
6109 // TODO: handle v16i8.
6110 if (VT.getSizeInBits() == 16) {
6111 SDValue Vec = Op.getOperand(0);
6112 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6114 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6115 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6116 DAG.getNode(ISD::BITCAST, dl,
6119 // Transform it so it match pextrw which produces a 32-bit result.
6120 EVT EltVT = MVT::i32;
6121 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6122 Op.getOperand(0), Op.getOperand(1));
6123 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6124 DAG.getValueType(VT));
6125 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6126 } else if (VT.getSizeInBits() == 32) {
6127 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6131 // SHUFPS the element to the lowest double word, then movss.
6132 int Mask[4] = { Idx, -1, -1, -1 };
6133 EVT VVT = Op.getOperand(0).getValueType();
6134 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6135 DAG.getUNDEF(VVT), Mask);
6136 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6137 DAG.getIntPtrConstant(0));
6138 } else if (VT.getSizeInBits() == 64) {
6139 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6140 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6141 // to match extract_elt for f64.
6142 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6146 // UNPCKHPD the element to the lowest double word, then movsd.
6147 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6148 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6149 int Mask[2] = { 1, -1 };
6150 EVT VVT = Op.getOperand(0).getValueType();
6151 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6152 DAG.getUNDEF(VVT), Mask);
6153 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6154 DAG.getIntPtrConstant(0));
6161 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6162 SelectionDAG &DAG) const {
6163 EVT VT = Op.getValueType();
6164 EVT EltVT = VT.getVectorElementType();
6165 DebugLoc dl = Op.getDebugLoc();
6167 SDValue N0 = Op.getOperand(0);
6168 SDValue N1 = Op.getOperand(1);
6169 SDValue N2 = Op.getOperand(2);
6171 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6172 isa<ConstantSDNode>(N2)) {
6174 if (VT == MVT::v8i16)
6175 Opc = X86ISD::PINSRW;
6176 else if (VT == MVT::v16i8)
6177 Opc = X86ISD::PINSRB;
6179 Opc = X86ISD::PINSRB;
6181 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6183 if (N1.getValueType() != MVT::i32)
6184 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6185 if (N2.getValueType() != MVT::i32)
6186 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6187 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6188 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6189 // Bits [7:6] of the constant are the source select. This will always be
6190 // zero here. The DAG Combiner may combine an extract_elt index into these
6191 // bits. For example (insert (extract, 3), 2) could be matched by putting
6192 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6193 // Bits [5:4] of the constant are the destination select. This is the
6194 // value of the incoming immediate.
6195 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6196 // combine either bitwise AND or insert of float 0.0 to set these bits.
6197 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6198 // Create this as a scalar to vector..
6199 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6200 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6201 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6202 // PINSR* works with constant index.
6209 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6210 EVT VT = Op.getValueType();
6211 EVT EltVT = VT.getVectorElementType();
6213 DebugLoc dl = Op.getDebugLoc();
6214 SDValue N0 = Op.getOperand(0);
6215 SDValue N1 = Op.getOperand(1);
6216 SDValue N2 = Op.getOperand(2);
6218 // If this is a 256-bit vector result, first insert into a 128-bit
6219 // vector and then insert into the 256-bit vector.
6220 if (VT.getSizeInBits() > 128) {
6221 if (!isa<ConstantSDNode>(N2))
6224 // Get the 128-bit vector.
6225 unsigned NumElems = VT.getVectorNumElements();
6226 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6227 bool Upper = IdxVal >= NumElems / 2;
6229 SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6232 SDValue ScaledN2 = N2;
6234 ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6235 DAG.getConstant(NumElems /
6236 (VT.getSizeInBits() / 128),
6237 N2.getValueType()));
6238 Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6241 // Insert the 128-bit vector
6242 // FIXME: Why UNDEF?
6243 return Insert128BitVector(N0, Op, N2, DAG, dl);
6246 if (Subtarget->hasSSE41())
6247 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6249 if (EltVT == MVT::i8)
6252 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6253 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6254 // as its second argument.
6255 if (N1.getValueType() != MVT::i32)
6256 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6257 if (N2.getValueType() != MVT::i32)
6258 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6259 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6265 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6266 LLVMContext *Context = DAG.getContext();
6267 DebugLoc dl = Op.getDebugLoc();
6268 EVT OpVT = Op.getValueType();
6270 // If this is a 256-bit vector result, first insert into a 128-bit
6271 // vector and then insert into the 256-bit vector.
6272 if (OpVT.getSizeInBits() > 128) {
6273 // Insert into a 128-bit vector.
6274 EVT VT128 = EVT::getVectorVT(*Context,
6275 OpVT.getVectorElementType(),
6276 OpVT.getVectorNumElements() / 2);
6278 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6280 // Insert the 128-bit vector.
6281 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6282 DAG.getConstant(0, MVT::i32),
6286 if (Op.getValueType() == MVT::v1i64 &&
6287 Op.getOperand(0).getValueType() == MVT::i64)
6288 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6290 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6291 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6292 "Expected an SSE type!");
6293 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6294 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6297 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
6298 // a simple subregister reference or explicit instructions to grab
6299 // upper bits of a vector.
6301 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6302 if (Subtarget->hasAVX()) {
6303 DebugLoc dl = Op.getNode()->getDebugLoc();
6304 SDValue Vec = Op.getNode()->getOperand(0);
6305 SDValue Idx = Op.getNode()->getOperand(1);
6307 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6308 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6309 return Extract128BitVector(Vec, Idx, DAG, dl);
6315 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
6316 // simple superregister reference or explicit instructions to insert
6317 // the upper bits of a vector.
6319 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6320 if (Subtarget->hasAVX()) {
6321 DebugLoc dl = Op.getNode()->getDebugLoc();
6322 SDValue Vec = Op.getNode()->getOperand(0);
6323 SDValue SubVec = Op.getNode()->getOperand(1);
6324 SDValue Idx = Op.getNode()->getOperand(2);
6326 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6327 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6328 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6334 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6335 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6336 // one of the above mentioned nodes. It has to be wrapped because otherwise
6337 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6338 // be used to form addressing mode. These wrapped nodes will be selected
6341 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6342 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6344 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6346 unsigned char OpFlag = 0;
6347 unsigned WrapperKind = X86ISD::Wrapper;
6348 CodeModel::Model M = getTargetMachine().getCodeModel();
6350 if (Subtarget->isPICStyleRIPRel() &&
6351 (M == CodeModel::Small || M == CodeModel::Kernel))
6352 WrapperKind = X86ISD::WrapperRIP;
6353 else if (Subtarget->isPICStyleGOT())
6354 OpFlag = X86II::MO_GOTOFF;
6355 else if (Subtarget->isPICStyleStubPIC())
6356 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6358 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6360 CP->getOffset(), OpFlag);
6361 DebugLoc DL = CP->getDebugLoc();
6362 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6363 // With PIC, the address is actually $g + Offset.
6365 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6366 DAG.getNode(X86ISD::GlobalBaseReg,
6367 DebugLoc(), getPointerTy()),
6374 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6375 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6377 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6379 unsigned char OpFlag = 0;
6380 unsigned WrapperKind = X86ISD::Wrapper;
6381 CodeModel::Model M = getTargetMachine().getCodeModel();
6383 if (Subtarget->isPICStyleRIPRel() &&
6384 (M == CodeModel::Small || M == CodeModel::Kernel))
6385 WrapperKind = X86ISD::WrapperRIP;
6386 else if (Subtarget->isPICStyleGOT())
6387 OpFlag = X86II::MO_GOTOFF;
6388 else if (Subtarget->isPICStyleStubPIC())
6389 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6391 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6393 DebugLoc DL = JT->getDebugLoc();
6394 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6396 // With PIC, the address is actually $g + Offset.
6398 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6399 DAG.getNode(X86ISD::GlobalBaseReg,
6400 DebugLoc(), getPointerTy()),
6407 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6408 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6410 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6412 unsigned char OpFlag = 0;
6413 unsigned WrapperKind = X86ISD::Wrapper;
6414 CodeModel::Model M = getTargetMachine().getCodeModel();
6416 if (Subtarget->isPICStyleRIPRel() &&
6417 (M == CodeModel::Small || M == CodeModel::Kernel))
6418 WrapperKind = X86ISD::WrapperRIP;
6419 else if (Subtarget->isPICStyleGOT())
6420 OpFlag = X86II::MO_GOTOFF;
6421 else if (Subtarget->isPICStyleStubPIC())
6422 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6424 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6426 DebugLoc DL = Op.getDebugLoc();
6427 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6430 // With PIC, the address is actually $g + Offset.
6431 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6432 !Subtarget->is64Bit()) {
6433 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6434 DAG.getNode(X86ISD::GlobalBaseReg,
6435 DebugLoc(), getPointerTy()),
6443 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6444 // Create the TargetBlockAddressAddress node.
6445 unsigned char OpFlags =
6446 Subtarget->ClassifyBlockAddressReference();
6447 CodeModel::Model M = getTargetMachine().getCodeModel();
6448 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6449 DebugLoc dl = Op.getDebugLoc();
6450 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6451 /*isTarget=*/true, OpFlags);
6453 if (Subtarget->isPICStyleRIPRel() &&
6454 (M == CodeModel::Small || M == CodeModel::Kernel))
6455 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6457 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6459 // With PIC, the address is actually $g + Offset.
6460 if (isGlobalRelativeToPICBase(OpFlags)) {
6461 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6462 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6470 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6472 SelectionDAG &DAG) const {
6473 // Create the TargetGlobalAddress node, folding in the constant
6474 // offset if it is legal.
6475 unsigned char OpFlags =
6476 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6477 CodeModel::Model M = getTargetMachine().getCodeModel();
6479 if (OpFlags == X86II::MO_NO_FLAG &&
6480 X86::isOffsetSuitableForCodeModel(Offset, M)) {
6481 // A direct static reference to a global.
6482 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6485 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6488 if (Subtarget->isPICStyleRIPRel() &&
6489 (M == CodeModel::Small || M == CodeModel::Kernel))
6490 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6492 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6494 // With PIC, the address is actually $g + Offset.
6495 if (isGlobalRelativeToPICBase(OpFlags)) {
6496 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6497 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6501 // For globals that require a load from a stub to get the address, emit the
6503 if (isGlobalStubReference(OpFlags))
6504 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6505 MachinePointerInfo::getGOT(), false, false, 0);
6507 // If there was a non-zero offset that we didn't fold, create an explicit
6510 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6511 DAG.getConstant(Offset, getPointerTy()));
6517 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6518 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6519 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6520 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6524 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6525 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6526 unsigned char OperandFlags) {
6527 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6528 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6529 DebugLoc dl = GA->getDebugLoc();
6530 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6531 GA->getValueType(0),
6535 SDValue Ops[] = { Chain, TGA, *InFlag };
6536 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6538 SDValue Ops[] = { Chain, TGA };
6539 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6542 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6543 MFI->setAdjustsStack(true);
6545 SDValue Flag = Chain.getValue(1);
6546 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6549 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6551 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6554 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6555 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6556 DAG.getNode(X86ISD::GlobalBaseReg,
6557 DebugLoc(), PtrVT), InFlag);
6558 InFlag = Chain.getValue(1);
6560 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6563 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6565 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6567 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6568 X86::RAX, X86II::MO_TLSGD);
6571 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6572 // "local exec" model.
6573 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6574 const EVT PtrVT, TLSModel::Model model,
6576 DebugLoc dl = GA->getDebugLoc();
6578 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6579 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6580 is64Bit ? 257 : 256));
6582 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6583 DAG.getIntPtrConstant(0),
6584 MachinePointerInfo(Ptr), false, false, 0);
6586 unsigned char OperandFlags = 0;
6587 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6589 unsigned WrapperKind = X86ISD::Wrapper;
6590 if (model == TLSModel::LocalExec) {
6591 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6592 } else if (is64Bit) {
6593 assert(model == TLSModel::InitialExec);
6594 OperandFlags = X86II::MO_GOTTPOFF;
6595 WrapperKind = X86ISD::WrapperRIP;
6597 assert(model == TLSModel::InitialExec);
6598 OperandFlags = X86II::MO_INDNTPOFF;
6601 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6603 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6604 GA->getValueType(0),
6605 GA->getOffset(), OperandFlags);
6606 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6608 if (model == TLSModel::InitialExec)
6609 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6610 MachinePointerInfo::getGOT(), false, false, 0);
6612 // The address of the thread local variable is the add of the thread
6613 // pointer with the offset of the variable.
6614 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6618 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6620 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6621 const GlobalValue *GV = GA->getGlobal();
6623 if (Subtarget->isTargetELF()) {
6624 // TODO: implement the "local dynamic" model
6625 // TODO: implement the "initial exec"model for pic executables
6627 // If GV is an alias then use the aliasee for determining
6628 // thread-localness.
6629 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6630 GV = GA->resolveAliasedGlobal(false);
6632 TLSModel::Model model
6633 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6636 case TLSModel::GeneralDynamic:
6637 case TLSModel::LocalDynamic: // not implemented
6638 if (Subtarget->is64Bit())
6639 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6640 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6642 case TLSModel::InitialExec:
6643 case TLSModel::LocalExec:
6644 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6645 Subtarget->is64Bit());
6647 } else if (Subtarget->isTargetDarwin()) {
6648 // Darwin only has one model of TLS. Lower to that.
6649 unsigned char OpFlag = 0;
6650 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6651 X86ISD::WrapperRIP : X86ISD::Wrapper;
6653 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6655 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6656 !Subtarget->is64Bit();
6658 OpFlag = X86II::MO_TLVP_PIC_BASE;
6660 OpFlag = X86II::MO_TLVP;
6661 DebugLoc DL = Op.getDebugLoc();
6662 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6663 GA->getValueType(0),
6664 GA->getOffset(), OpFlag);
6665 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6667 // With PIC32, the address is actually $g + Offset.
6669 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6670 DAG.getNode(X86ISD::GlobalBaseReg,
6671 DebugLoc(), getPointerTy()),
6674 // Lowering the machine isd will make sure everything is in the right
6676 SDValue Chain = DAG.getEntryNode();
6677 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6678 SDValue Args[] = { Chain, Offset };
6679 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6681 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6682 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6683 MFI->setAdjustsStack(true);
6685 // And our return value (tls address) is in the standard call return value
6687 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6688 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6692 "TLS not implemented for this target.");
6694 llvm_unreachable("Unreachable");
6699 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6700 /// take a 2 x i32 value to shift plus a shift amount.
6701 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6702 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6703 EVT VT = Op.getValueType();
6704 unsigned VTBits = VT.getSizeInBits();
6705 DebugLoc dl = Op.getDebugLoc();
6706 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6707 SDValue ShOpLo = Op.getOperand(0);
6708 SDValue ShOpHi = Op.getOperand(1);
6709 SDValue ShAmt = Op.getOperand(2);
6710 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6711 DAG.getConstant(VTBits - 1, MVT::i8))
6712 : DAG.getConstant(0, VT);
6715 if (Op.getOpcode() == ISD::SHL_PARTS) {
6716 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6717 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6719 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6720 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6723 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6724 DAG.getConstant(VTBits, MVT::i8));
6725 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6726 AndNode, DAG.getConstant(0, MVT::i8));
6729 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6730 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6731 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6733 if (Op.getOpcode() == ISD::SHL_PARTS) {
6734 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6735 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6737 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6738 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6741 SDValue Ops[2] = { Lo, Hi };
6742 return DAG.getMergeValues(Ops, 2, dl);
6745 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6746 SelectionDAG &DAG) const {
6747 EVT SrcVT = Op.getOperand(0).getValueType();
6749 if (SrcVT.isVector())
6752 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6753 "Unknown SINT_TO_FP to lower!");
6755 // These are really Legal; return the operand so the caller accepts it as
6757 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6759 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6760 Subtarget->is64Bit()) {
6764 DebugLoc dl = Op.getDebugLoc();
6765 unsigned Size = SrcVT.getSizeInBits()/8;
6766 MachineFunction &MF = DAG.getMachineFunction();
6767 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6768 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6769 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6771 MachinePointerInfo::getFixedStack(SSFI),
6773 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6776 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6778 SelectionDAG &DAG) const {
6780 DebugLoc DL = Op.getDebugLoc();
6782 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6784 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6786 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6788 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6790 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
6791 MachineMemOperand *MMO;
6793 int SSFI = FI->getIndex();
6795 DAG.getMachineFunction()
6796 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6797 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6799 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
6800 StackSlot = StackSlot.getOperand(1);
6802 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6803 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6805 Tys, Ops, array_lengthof(Ops),
6809 Chain = Result.getValue(1);
6810 SDValue InFlag = Result.getValue(2);
6812 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6813 // shouldn't be necessary except that RFP cannot be live across
6814 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6815 MachineFunction &MF = DAG.getMachineFunction();
6816 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6817 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6818 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6819 Tys = DAG.getVTList(MVT::Other);
6821 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6823 MachineMemOperand *MMO =
6824 DAG.getMachineFunction()
6825 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6826 MachineMemOperand::MOStore, SSFISize, SSFISize);
6828 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6829 Ops, array_lengthof(Ops),
6830 Op.getValueType(), MMO);
6831 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6832 MachinePointerInfo::getFixedStack(SSFI),
6839 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6840 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6841 SelectionDAG &DAG) const {
6842 // This algorithm is not obvious. Here it is in C code, more or less:
6844 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6845 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6846 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6848 // Copy ints to xmm registers.
6849 __m128i xh = _mm_cvtsi32_si128( hi );
6850 __m128i xl = _mm_cvtsi32_si128( lo );
6852 // Combine into low half of a single xmm register.
6853 __m128i x = _mm_unpacklo_epi32( xh, xl );
6857 // Merge in appropriate exponents to give the integer bits the right
6859 x = _mm_unpacklo_epi32( x, exp );
6861 // Subtract away the biases to deal with the IEEE-754 double precision
6863 d = _mm_sub_pd( (__m128d) x, bias );
6865 // All conversions up to here are exact. The correctly rounded result is
6866 // calculated using the current rounding mode using the following
6868 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6869 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6870 // store doesn't really need to be here (except
6871 // maybe to zero the other double)
6876 DebugLoc dl = Op.getDebugLoc();
6877 LLVMContext *Context = DAG.getContext();
6879 // Build some magic constants.
6880 std::vector<Constant*> CV0;
6881 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6882 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6883 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6884 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6885 Constant *C0 = ConstantVector::get(CV0);
6886 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6888 std::vector<Constant*> CV1;
6890 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6892 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6893 Constant *C1 = ConstantVector::get(CV1);
6894 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6896 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6897 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6899 DAG.getIntPtrConstant(1)));
6900 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6901 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6903 DAG.getIntPtrConstant(0)));
6904 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6905 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6906 MachinePointerInfo::getConstantPool(),
6908 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6909 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6910 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6911 MachinePointerInfo::getConstantPool(),
6913 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6915 // Add the halves; easiest way is to swap them into another reg first.
6916 int ShufMask[2] = { 1, -1 };
6917 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6918 DAG.getUNDEF(MVT::v2f64), ShufMask);
6919 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6920 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6921 DAG.getIntPtrConstant(0));
6924 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6925 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6926 SelectionDAG &DAG) const {
6927 DebugLoc dl = Op.getDebugLoc();
6928 // FP constant to bias correct the final result.
6929 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6932 // Load the 32-bit value into an XMM register.
6933 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6934 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6936 DAG.getIntPtrConstant(0)));
6938 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6939 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6940 DAG.getIntPtrConstant(0));
6942 // Or the load with the bias.
6943 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6944 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6945 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6947 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6948 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6949 MVT::v2f64, Bias)));
6950 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6951 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6952 DAG.getIntPtrConstant(0));
6954 // Subtract the bias.
6955 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6957 // Handle final rounding.
6958 EVT DestVT = Op.getValueType();
6960 if (DestVT.bitsLT(MVT::f64)) {
6961 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6962 DAG.getIntPtrConstant(0));
6963 } else if (DestVT.bitsGT(MVT::f64)) {
6964 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6967 // Handle final rounding.
6971 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6972 SelectionDAG &DAG) const {
6973 SDValue N0 = Op.getOperand(0);
6974 DebugLoc dl = Op.getDebugLoc();
6976 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6977 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6978 // the optimization here.
6979 if (DAG.SignBitIsZero(N0))
6980 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6982 EVT SrcVT = N0.getValueType();
6983 EVT DstVT = Op.getValueType();
6984 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6985 return LowerUINT_TO_FP_i64(Op, DAG);
6986 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6987 return LowerUINT_TO_FP_i32(Op, DAG);
6989 // Make a 64-bit buffer, and use it to build an FILD.
6990 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6991 if (SrcVT == MVT::i32) {
6992 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6993 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6994 getPointerTy(), StackSlot, WordOff);
6995 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6996 StackSlot, MachinePointerInfo(),
6998 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6999 OffsetSlot, MachinePointerInfo(),
7001 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7005 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7006 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7007 StackSlot, MachinePointerInfo(),
7009 // For i64 source, we need to add the appropriate power of 2 if the input
7010 // was negative. This is the same as the optimization in
7011 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7012 // we must be careful to do the computation in x87 extended precision, not
7013 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7014 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7015 MachineMemOperand *MMO =
7016 DAG.getMachineFunction()
7017 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7018 MachineMemOperand::MOLoad, 8, 8);
7020 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7021 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7022 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7025 APInt FF(32, 0x5F800000ULL);
7027 // Check whether the sign bit is set.
7028 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7029 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7032 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7033 SDValue FudgePtr = DAG.getConstantPool(
7034 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7037 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7038 SDValue Zero = DAG.getIntPtrConstant(0);
7039 SDValue Four = DAG.getIntPtrConstant(4);
7040 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7042 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7044 // Load the value out, extending it from f32 to f80.
7045 // FIXME: Avoid the extend by constructing the right constant pool?
7046 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7047 FudgePtr, MachinePointerInfo::getConstantPool(),
7048 MVT::f32, false, false, 4);
7049 // Extend everything to 80 bits to force it to be done on x87.
7050 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7051 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7054 std::pair<SDValue,SDValue> X86TargetLowering::
7055 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7056 DebugLoc DL = Op.getDebugLoc();
7058 EVT DstTy = Op.getValueType();
7061 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7065 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7066 DstTy.getSimpleVT() >= MVT::i16 &&
7067 "Unknown FP_TO_SINT to lower!");
7069 // These are really Legal.
7070 if (DstTy == MVT::i32 &&
7071 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7072 return std::make_pair(SDValue(), SDValue());
7073 if (Subtarget->is64Bit() &&
7074 DstTy == MVT::i64 &&
7075 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7076 return std::make_pair(SDValue(), SDValue());
7078 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7080 MachineFunction &MF = DAG.getMachineFunction();
7081 unsigned MemSize = DstTy.getSizeInBits()/8;
7082 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7083 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7088 switch (DstTy.getSimpleVT().SimpleTy) {
7089 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7090 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7091 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7092 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7095 SDValue Chain = DAG.getEntryNode();
7096 SDValue Value = Op.getOperand(0);
7097 EVT TheVT = Op.getOperand(0).getValueType();
7098 if (isScalarFPTypeInSSEReg(TheVT)) {
7099 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7100 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7101 MachinePointerInfo::getFixedStack(SSFI),
7103 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7105 Chain, StackSlot, DAG.getValueType(TheVT)
7108 MachineMemOperand *MMO =
7109 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7110 MachineMemOperand::MOLoad, MemSize, MemSize);
7111 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7113 Chain = Value.getValue(1);
7114 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7115 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7118 MachineMemOperand *MMO =
7119 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7120 MachineMemOperand::MOStore, MemSize, MemSize);
7122 // Build the FP_TO_INT*_IN_MEM
7123 SDValue Ops[] = { Chain, Value, StackSlot };
7124 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7125 Ops, 3, DstTy, MMO);
7127 return std::make_pair(FIST, StackSlot);
7130 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7131 SelectionDAG &DAG) const {
7132 if (Op.getValueType().isVector())
7135 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7136 SDValue FIST = Vals.first, StackSlot = Vals.second;
7137 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7138 if (FIST.getNode() == 0) return Op;
7141 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7142 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7145 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7146 SelectionDAG &DAG) const {
7147 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7148 SDValue FIST = Vals.first, StackSlot = Vals.second;
7149 assert(FIST.getNode() && "Unexpected failure");
7152 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7153 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7156 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7157 SelectionDAG &DAG) const {
7158 LLVMContext *Context = DAG.getContext();
7159 DebugLoc dl = Op.getDebugLoc();
7160 EVT VT = Op.getValueType();
7163 EltVT = VT.getVectorElementType();
7164 std::vector<Constant*> CV;
7165 if (EltVT == MVT::f64) {
7166 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7170 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7176 Constant *C = ConstantVector::get(CV);
7177 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7178 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7179 MachinePointerInfo::getConstantPool(),
7181 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7184 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7185 LLVMContext *Context = DAG.getContext();
7186 DebugLoc dl = Op.getDebugLoc();
7187 EVT VT = Op.getValueType();
7190 EltVT = VT.getVectorElementType();
7191 std::vector<Constant*> CV;
7192 if (EltVT == MVT::f64) {
7193 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7197 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7203 Constant *C = ConstantVector::get(CV);
7204 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7205 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7206 MachinePointerInfo::getConstantPool(),
7208 if (VT.isVector()) {
7209 return DAG.getNode(ISD::BITCAST, dl, VT,
7210 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7211 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7213 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7215 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7219 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7220 LLVMContext *Context = DAG.getContext();
7221 SDValue Op0 = Op.getOperand(0);
7222 SDValue Op1 = Op.getOperand(1);
7223 DebugLoc dl = Op.getDebugLoc();
7224 EVT VT = Op.getValueType();
7225 EVT SrcVT = Op1.getValueType();
7227 // If second operand is smaller, extend it first.
7228 if (SrcVT.bitsLT(VT)) {
7229 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7232 // And if it is bigger, shrink it first.
7233 if (SrcVT.bitsGT(VT)) {
7234 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7238 // At this point the operands and the result should have the same
7239 // type, and that won't be f80 since that is not custom lowered.
7241 // First get the sign bit of second operand.
7242 std::vector<Constant*> CV;
7243 if (SrcVT == MVT::f64) {
7244 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7245 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7247 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7248 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7249 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7250 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7252 Constant *C = ConstantVector::get(CV);
7253 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7254 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7255 MachinePointerInfo::getConstantPool(),
7257 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7259 // Shift sign bit right or left if the two operands have different types.
7260 if (SrcVT.bitsGT(VT)) {
7261 // Op0 is MVT::f32, Op1 is MVT::f64.
7262 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7263 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7264 DAG.getConstant(32, MVT::i32));
7265 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7266 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7267 DAG.getIntPtrConstant(0));
7270 // Clear first operand sign bit.
7272 if (VT == MVT::f64) {
7273 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7274 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7276 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7277 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7278 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7279 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7281 C = ConstantVector::get(CV);
7282 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7283 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7284 MachinePointerInfo::getConstantPool(),
7286 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7288 // Or the value with the sign bit.
7289 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7292 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7293 SDValue N0 = Op.getOperand(0);
7294 DebugLoc dl = Op.getDebugLoc();
7295 EVT VT = Op.getValueType();
7297 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7298 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7299 DAG.getConstant(1, VT));
7300 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7303 /// Emit nodes that will be selected as "test Op0,Op0", or something
7305 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7306 SelectionDAG &DAG) const {
7307 DebugLoc dl = Op.getDebugLoc();
7309 // CF and OF aren't always set the way we want. Determine which
7310 // of these we need.
7311 bool NeedCF = false;
7312 bool NeedOF = false;
7315 case X86::COND_A: case X86::COND_AE:
7316 case X86::COND_B: case X86::COND_BE:
7319 case X86::COND_G: case X86::COND_GE:
7320 case X86::COND_L: case X86::COND_LE:
7321 case X86::COND_O: case X86::COND_NO:
7326 // See if we can use the EFLAGS value from the operand instead of
7327 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7328 // we prove that the arithmetic won't overflow, we can't use OF or CF.
7329 if (Op.getResNo() != 0 || NeedOF || NeedCF)
7330 // Emit a CMP with 0, which is the TEST pattern.
7331 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7332 DAG.getConstant(0, Op.getValueType()));
7334 unsigned Opcode = 0;
7335 unsigned NumOperands = 0;
7336 switch (Op.getNode()->getOpcode()) {
7338 // Due to an isel shortcoming, be conservative if this add is likely to be
7339 // selected as part of a load-modify-store instruction. When the root node
7340 // in a match is a store, isel doesn't know how to remap non-chain non-flag
7341 // uses of other nodes in the match, such as the ADD in this case. This
7342 // leads to the ADD being left around and reselected, with the result being
7343 // two adds in the output. Alas, even if none our users are stores, that
7344 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
7345 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
7346 // climbing the DAG back to the root, and it doesn't seem to be worth the
7348 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7349 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7350 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7353 if (ConstantSDNode *C =
7354 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7355 // An add of one will be selected as an INC.
7356 if (C->getAPIntValue() == 1) {
7357 Opcode = X86ISD::INC;
7362 // An add of negative one (subtract of one) will be selected as a DEC.
7363 if (C->getAPIntValue().isAllOnesValue()) {
7364 Opcode = X86ISD::DEC;
7370 // Otherwise use a regular EFLAGS-setting add.
7371 Opcode = X86ISD::ADD;
7375 // If the primary and result isn't used, don't bother using X86ISD::AND,
7376 // because a TEST instruction will be better.
7377 bool NonFlagUse = false;
7378 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7379 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7381 unsigned UOpNo = UI.getOperandNo();
7382 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7383 // Look pass truncate.
7384 UOpNo = User->use_begin().getOperandNo();
7385 User = *User->use_begin();
7388 if (User->getOpcode() != ISD::BRCOND &&
7389 User->getOpcode() != ISD::SETCC &&
7390 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7403 // Due to the ISEL shortcoming noted above, be conservative if this op is
7404 // likely to be selected as part of a load-modify-store instruction.
7405 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7406 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7407 if (UI->getOpcode() == ISD::STORE)
7410 // Otherwise use a regular EFLAGS-setting instruction.
7411 switch (Op.getNode()->getOpcode()) {
7412 default: llvm_unreachable("unexpected operator!");
7413 case ISD::SUB: Opcode = X86ISD::SUB; break;
7414 case ISD::OR: Opcode = X86ISD::OR; break;
7415 case ISD::XOR: Opcode = X86ISD::XOR; break;
7416 case ISD::AND: Opcode = X86ISD::AND; break;
7428 return SDValue(Op.getNode(), 1);
7435 // Emit a CMP with 0, which is the TEST pattern.
7436 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7437 DAG.getConstant(0, Op.getValueType()));
7439 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7440 SmallVector<SDValue, 4> Ops;
7441 for (unsigned i = 0; i != NumOperands; ++i)
7442 Ops.push_back(Op.getOperand(i));
7444 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7445 DAG.ReplaceAllUsesWith(Op, New);
7446 return SDValue(New.getNode(), 1);
7449 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7451 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7452 SelectionDAG &DAG) const {
7453 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7454 if (C->getAPIntValue() == 0)
7455 return EmitTest(Op0, X86CC, DAG);
7457 DebugLoc dl = Op0.getDebugLoc();
7458 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7461 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7462 /// if it's possible.
7463 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7464 DebugLoc dl, SelectionDAG &DAG) const {
7465 SDValue Op0 = And.getOperand(0);
7466 SDValue Op1 = And.getOperand(1);
7467 if (Op0.getOpcode() == ISD::TRUNCATE)
7468 Op0 = Op0.getOperand(0);
7469 if (Op1.getOpcode() == ISD::TRUNCATE)
7470 Op1 = Op1.getOperand(0);
7473 if (Op1.getOpcode() == ISD::SHL)
7474 std::swap(Op0, Op1);
7475 if (Op0.getOpcode() == ISD::SHL) {
7476 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7477 if (And00C->getZExtValue() == 1) {
7478 // If we looked past a truncate, check that it's only truncating away
7480 unsigned BitWidth = Op0.getValueSizeInBits();
7481 unsigned AndBitWidth = And.getValueSizeInBits();
7482 if (BitWidth > AndBitWidth) {
7483 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7484 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7485 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7489 RHS = Op0.getOperand(1);
7491 } else if (Op1.getOpcode() == ISD::Constant) {
7492 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7493 SDValue AndLHS = Op0;
7494 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7495 LHS = AndLHS.getOperand(0);
7496 RHS = AndLHS.getOperand(1);
7500 if (LHS.getNode()) {
7501 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
7502 // instruction. Since the shift amount is in-range-or-undefined, we know
7503 // that doing a bittest on the i32 value is ok. We extend to i32 because
7504 // the encoding for the i16 version is larger than the i32 version.
7505 // Also promote i16 to i32 for performance / code size reason.
7506 if (LHS.getValueType() == MVT::i8 ||
7507 LHS.getValueType() == MVT::i16)
7508 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7510 // If the operand types disagree, extend the shift amount to match. Since
7511 // BT ignores high bits (like shifts) we can use anyextend.
7512 if (LHS.getValueType() != RHS.getValueType())
7513 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7515 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7516 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7517 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7518 DAG.getConstant(Cond, MVT::i8), BT);
7524 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7525 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7526 SDValue Op0 = Op.getOperand(0);
7527 SDValue Op1 = Op.getOperand(1);
7528 DebugLoc dl = Op.getDebugLoc();
7529 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7531 // Optimize to BT if possible.
7532 // Lower (X & (1 << N)) == 0 to BT(X, N).
7533 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7534 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7535 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7536 Op1.getOpcode() == ISD::Constant &&
7537 cast<ConstantSDNode>(Op1)->isNullValue() &&
7538 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7539 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7540 if (NewSetCC.getNode())
7544 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
7546 if (Op1.getOpcode() == ISD::Constant &&
7547 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7548 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7549 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7551 // If the input is a setcc, then reuse the input setcc or use a new one with
7552 // the inverted condition.
7553 if (Op0.getOpcode() == X86ISD::SETCC) {
7554 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7555 bool Invert = (CC == ISD::SETNE) ^
7556 cast<ConstantSDNode>(Op1)->isNullValue();
7557 if (!Invert) return Op0;
7559 CCode = X86::GetOppositeBranchCondition(CCode);
7560 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7561 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7565 bool isFP = Op1.getValueType().isFloatingPoint();
7566 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7567 if (X86CC == X86::COND_INVALID)
7570 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7571 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7572 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7575 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7577 SDValue Op0 = Op.getOperand(0);
7578 SDValue Op1 = Op.getOperand(1);
7579 SDValue CC = Op.getOperand(2);
7580 EVT VT = Op.getValueType();
7581 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7582 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7583 DebugLoc dl = Op.getDebugLoc();
7587 EVT VT0 = Op0.getValueType();
7588 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7589 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7592 switch (SetCCOpcode) {
7595 case ISD::SETEQ: SSECC = 0; break;
7597 case ISD::SETGT: Swap = true; // Fallthrough
7599 case ISD::SETOLT: SSECC = 1; break;
7601 case ISD::SETGE: Swap = true; // Fallthrough
7603 case ISD::SETOLE: SSECC = 2; break;
7604 case ISD::SETUO: SSECC = 3; break;
7606 case ISD::SETNE: SSECC = 4; break;
7607 case ISD::SETULE: Swap = true;
7608 case ISD::SETUGE: SSECC = 5; break;
7609 case ISD::SETULT: Swap = true;
7610 case ISD::SETUGT: SSECC = 6; break;
7611 case ISD::SETO: SSECC = 7; break;
7614 std::swap(Op0, Op1);
7616 // In the two special cases we can't handle, emit two comparisons.
7618 if (SetCCOpcode == ISD::SETUEQ) {
7620 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7621 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7622 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7624 else if (SetCCOpcode == ISD::SETONE) {
7626 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7627 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7628 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7630 llvm_unreachable("Illegal FP comparison");
7632 // Handle all other FP comparisons here.
7633 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7636 // We are handling one of the integer comparisons here. Since SSE only has
7637 // GT and EQ comparisons for integer, swapping operands and multiple
7638 // operations may be required for some comparisons.
7639 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7640 bool Swap = false, Invert = false, FlipSigns = false;
7642 switch (VT.getSimpleVT().SimpleTy) {
7644 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7645 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7646 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7647 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7650 switch (SetCCOpcode) {
7652 case ISD::SETNE: Invert = true;
7653 case ISD::SETEQ: Opc = EQOpc; break;
7654 case ISD::SETLT: Swap = true;
7655 case ISD::SETGT: Opc = GTOpc; break;
7656 case ISD::SETGE: Swap = true;
7657 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7658 case ISD::SETULT: Swap = true;
7659 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7660 case ISD::SETUGE: Swap = true;
7661 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7664 std::swap(Op0, Op1);
7666 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7667 // bits of the inputs before performing those operations.
7669 EVT EltVT = VT.getVectorElementType();
7670 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7672 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7673 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7675 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7676 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7679 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7681 // If the logical-not of the result is required, perform that now.
7683 Result = DAG.getNOT(dl, Result, VT);
7688 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7689 static bool isX86LogicalCmp(SDValue Op) {
7690 unsigned Opc = Op.getNode()->getOpcode();
7691 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7693 if (Op.getResNo() == 1 &&
7694 (Opc == X86ISD::ADD ||
7695 Opc == X86ISD::SUB ||
7696 Opc == X86ISD::ADC ||
7697 Opc == X86ISD::SBB ||
7698 Opc == X86ISD::SMUL ||
7699 Opc == X86ISD::UMUL ||
7700 Opc == X86ISD::INC ||
7701 Opc == X86ISD::DEC ||
7702 Opc == X86ISD::OR ||
7703 Opc == X86ISD::XOR ||
7704 Opc == X86ISD::AND))
7707 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7713 static bool isZero(SDValue V) {
7714 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7715 return C && C->isNullValue();
7718 static bool isAllOnes(SDValue V) {
7719 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7720 return C && C->isAllOnesValue();
7723 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7724 bool addTest = true;
7725 SDValue Cond = Op.getOperand(0);
7726 SDValue Op1 = Op.getOperand(1);
7727 SDValue Op2 = Op.getOperand(2);
7728 DebugLoc DL = Op.getDebugLoc();
7731 if (Cond.getOpcode() == ISD::SETCC) {
7732 SDValue NewCond = LowerSETCC(Cond, DAG);
7733 if (NewCond.getNode())
7737 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7738 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7739 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7740 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7741 if (Cond.getOpcode() == X86ISD::SETCC &&
7742 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7743 isZero(Cond.getOperand(1).getOperand(1))) {
7744 SDValue Cmp = Cond.getOperand(1);
7746 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7748 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7749 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7750 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7752 SDValue CmpOp0 = Cmp.getOperand(0);
7753 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7754 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7756 SDValue Res = // Res = 0 or -1.
7757 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7758 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7760 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7761 Res = DAG.getNOT(DL, Res, Res.getValueType());
7763 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7764 if (N2C == 0 || !N2C->isNullValue())
7765 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7770 // Look past (and (setcc_carry (cmp ...)), 1).
7771 if (Cond.getOpcode() == ISD::AND &&
7772 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7773 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7774 if (C && C->getAPIntValue() == 1)
7775 Cond = Cond.getOperand(0);
7778 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7779 // setting operand in place of the X86ISD::SETCC.
7780 if (Cond.getOpcode() == X86ISD::SETCC ||
7781 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7782 CC = Cond.getOperand(0);
7784 SDValue Cmp = Cond.getOperand(1);
7785 unsigned Opc = Cmp.getOpcode();
7786 EVT VT = Op.getValueType();
7788 bool IllegalFPCMov = false;
7789 if (VT.isFloatingPoint() && !VT.isVector() &&
7790 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7791 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7793 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7794 Opc == X86ISD::BT) { // FIXME
7801 // Look pass the truncate.
7802 if (Cond.getOpcode() == ISD::TRUNCATE)
7803 Cond = Cond.getOperand(0);
7805 // We know the result of AND is compared against zero. Try to match
7807 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7808 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7809 if (NewSetCC.getNode()) {
7810 CC = NewSetCC.getOperand(0);
7811 Cond = NewSetCC.getOperand(1);
7818 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7819 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7822 // a < b ? -1 : 0 -> RES = ~setcc_carry
7823 // a < b ? 0 : -1 -> RES = setcc_carry
7824 // a >= b ? -1 : 0 -> RES = setcc_carry
7825 // a >= b ? 0 : -1 -> RES = ~setcc_carry
7826 if (Cond.getOpcode() == X86ISD::CMP) {
7827 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7829 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7830 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7831 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7832 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7833 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7834 return DAG.getNOT(DL, Res, Res.getValueType());
7839 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7840 // condition is true.
7841 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7842 SDValue Ops[] = { Op2, Op1, CC, Cond };
7843 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7846 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7847 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7848 // from the AND / OR.
7849 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7850 Opc = Op.getOpcode();
7851 if (Opc != ISD::OR && Opc != ISD::AND)
7853 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7854 Op.getOperand(0).hasOneUse() &&
7855 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7856 Op.getOperand(1).hasOneUse());
7859 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7860 // 1 and that the SETCC node has a single use.
7861 static bool isXor1OfSetCC(SDValue Op) {
7862 if (Op.getOpcode() != ISD::XOR)
7864 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7865 if (N1C && N1C->getAPIntValue() == 1) {
7866 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7867 Op.getOperand(0).hasOneUse();
7872 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7873 bool addTest = true;
7874 SDValue Chain = Op.getOperand(0);
7875 SDValue Cond = Op.getOperand(1);
7876 SDValue Dest = Op.getOperand(2);
7877 DebugLoc dl = Op.getDebugLoc();
7880 if (Cond.getOpcode() == ISD::SETCC) {
7881 SDValue NewCond = LowerSETCC(Cond, DAG);
7882 if (NewCond.getNode())
7886 // FIXME: LowerXALUO doesn't handle these!!
7887 else if (Cond.getOpcode() == X86ISD::ADD ||
7888 Cond.getOpcode() == X86ISD::SUB ||
7889 Cond.getOpcode() == X86ISD::SMUL ||
7890 Cond.getOpcode() == X86ISD::UMUL)
7891 Cond = LowerXALUO(Cond, DAG);
7894 // Look pass (and (setcc_carry (cmp ...)), 1).
7895 if (Cond.getOpcode() == ISD::AND &&
7896 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7897 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7898 if (C && C->getAPIntValue() == 1)
7899 Cond = Cond.getOperand(0);
7902 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7903 // setting operand in place of the X86ISD::SETCC.
7904 if (Cond.getOpcode() == X86ISD::SETCC ||
7905 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7906 CC = Cond.getOperand(0);
7908 SDValue Cmp = Cond.getOperand(1);
7909 unsigned Opc = Cmp.getOpcode();
7910 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7911 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7915 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7919 // These can only come from an arithmetic instruction with overflow,
7920 // e.g. SADDO, UADDO.
7921 Cond = Cond.getNode()->getOperand(1);
7928 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7929 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7930 if (CondOpc == ISD::OR) {
7931 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7932 // two branches instead of an explicit OR instruction with a
7934 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7935 isX86LogicalCmp(Cmp)) {
7936 CC = Cond.getOperand(0).getOperand(0);
7937 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7938 Chain, Dest, CC, Cmp);
7939 CC = Cond.getOperand(1).getOperand(0);
7943 } else { // ISD::AND
7944 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7945 // two branches instead of an explicit AND instruction with a
7946 // separate test. However, we only do this if this block doesn't
7947 // have a fall-through edge, because this requires an explicit
7948 // jmp when the condition is false.
7949 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7950 isX86LogicalCmp(Cmp) &&
7951 Op.getNode()->hasOneUse()) {
7952 X86::CondCode CCode =
7953 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7954 CCode = X86::GetOppositeBranchCondition(CCode);
7955 CC = DAG.getConstant(CCode, MVT::i8);
7956 SDNode *User = *Op.getNode()->use_begin();
7957 // Look for an unconditional branch following this conditional branch.
7958 // We need this because we need to reverse the successors in order
7959 // to implement FCMP_OEQ.
7960 if (User->getOpcode() == ISD::BR) {
7961 SDValue FalseBB = User->getOperand(1);
7963 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7964 assert(NewBR == User);
7968 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7969 Chain, Dest, CC, Cmp);
7970 X86::CondCode CCode =
7971 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7972 CCode = X86::GetOppositeBranchCondition(CCode);
7973 CC = DAG.getConstant(CCode, MVT::i8);
7979 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7980 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7981 // It should be transformed during dag combiner except when the condition
7982 // is set by a arithmetics with overflow node.
7983 X86::CondCode CCode =
7984 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7985 CCode = X86::GetOppositeBranchCondition(CCode);
7986 CC = DAG.getConstant(CCode, MVT::i8);
7987 Cond = Cond.getOperand(0).getOperand(1);
7993 // Look pass the truncate.
7994 if (Cond.getOpcode() == ISD::TRUNCATE)
7995 Cond = Cond.getOperand(0);
7997 // We know the result of AND is compared against zero. Try to match
7999 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8000 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8001 if (NewSetCC.getNode()) {
8002 CC = NewSetCC.getOperand(0);
8003 Cond = NewSetCC.getOperand(1);
8010 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8011 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8013 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8014 Chain, Dest, CC, Cond);
8018 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8019 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8020 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8021 // that the guard pages used by the OS virtual memory manager are allocated in
8022 // correct sequence.
8024 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8025 SelectionDAG &DAG) const {
8026 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8027 "This should be used only on Windows targets");
8028 assert(!Subtarget->isTargetEnvMacho());
8029 DebugLoc dl = Op.getDebugLoc();
8032 SDValue Chain = Op.getOperand(0);
8033 SDValue Size = Op.getOperand(1);
8034 // FIXME: Ensure alignment here
8038 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8039 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8041 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8042 Flag = Chain.getValue(1);
8044 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8046 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8047 Flag = Chain.getValue(1);
8049 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8051 SDValue Ops1[2] = { Chain.getValue(0), Chain };
8052 return DAG.getMergeValues(Ops1, 2, dl);
8055 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8056 MachineFunction &MF = DAG.getMachineFunction();
8057 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8059 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8060 DebugLoc DL = Op.getDebugLoc();
8062 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8063 // vastart just stores the address of the VarArgsFrameIndex slot into the
8064 // memory location argument.
8065 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8067 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8068 MachinePointerInfo(SV), false, false, 0);
8072 // gp_offset (0 - 6 * 8)
8073 // fp_offset (48 - 48 + 8 * 16)
8074 // overflow_arg_area (point to parameters coming in memory).
8076 SmallVector<SDValue, 8> MemOps;
8077 SDValue FIN = Op.getOperand(1);
8079 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8080 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8082 FIN, MachinePointerInfo(SV), false, false, 0);
8083 MemOps.push_back(Store);
8086 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8087 FIN, DAG.getIntPtrConstant(4));
8088 Store = DAG.getStore(Op.getOperand(0), DL,
8089 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8091 FIN, MachinePointerInfo(SV, 4), false, false, 0);
8092 MemOps.push_back(Store);
8094 // Store ptr to overflow_arg_area
8095 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8096 FIN, DAG.getIntPtrConstant(4));
8097 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8099 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8100 MachinePointerInfo(SV, 8),
8102 MemOps.push_back(Store);
8104 // Store ptr to reg_save_area.
8105 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8106 FIN, DAG.getIntPtrConstant(8));
8107 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8109 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8110 MachinePointerInfo(SV, 16), false, false, 0);
8111 MemOps.push_back(Store);
8112 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8113 &MemOps[0], MemOps.size());
8116 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8117 assert(Subtarget->is64Bit() &&
8118 "LowerVAARG only handles 64-bit va_arg!");
8119 assert((Subtarget->isTargetLinux() ||
8120 Subtarget->isTargetDarwin()) &&
8121 "Unhandled target in LowerVAARG");
8122 assert(Op.getNode()->getNumOperands() == 4);
8123 SDValue Chain = Op.getOperand(0);
8124 SDValue SrcPtr = Op.getOperand(1);
8125 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8126 unsigned Align = Op.getConstantOperandVal(3);
8127 DebugLoc dl = Op.getDebugLoc();
8129 EVT ArgVT = Op.getNode()->getValueType(0);
8130 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8131 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8134 // Decide which area this value should be read from.
8135 // TODO: Implement the AMD64 ABI in its entirety. This simple
8136 // selection mechanism works only for the basic types.
8137 if (ArgVT == MVT::f80) {
8138 llvm_unreachable("va_arg for f80 not yet implemented");
8139 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8140 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
8141 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8142 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
8144 llvm_unreachable("Unhandled argument type in LowerVAARG");
8148 // Sanity Check: Make sure using fp_offset makes sense.
8149 assert(!UseSoftFloat &&
8150 !(DAG.getMachineFunction()
8151 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8152 Subtarget->hasXMM());
8155 // Insert VAARG_64 node into the DAG
8156 // VAARG_64 returns two values: Variable Argument Address, Chain
8157 SmallVector<SDValue, 11> InstOps;
8158 InstOps.push_back(Chain);
8159 InstOps.push_back(SrcPtr);
8160 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8161 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8162 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8163 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8164 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8165 VTs, &InstOps[0], InstOps.size(),
8167 MachinePointerInfo(SV),
8172 Chain = VAARG.getValue(1);
8174 // Load the next argument and return it
8175 return DAG.getLoad(ArgVT, dl,
8178 MachinePointerInfo(),
8182 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8183 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8184 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8185 SDValue Chain = Op.getOperand(0);
8186 SDValue DstPtr = Op.getOperand(1);
8187 SDValue SrcPtr = Op.getOperand(2);
8188 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8189 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8190 DebugLoc DL = Op.getDebugLoc();
8192 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8193 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8195 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8199 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8200 DebugLoc dl = Op.getDebugLoc();
8201 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8203 default: return SDValue(); // Don't custom lower most intrinsics.
8204 // Comparison intrinsics.
8205 case Intrinsic::x86_sse_comieq_ss:
8206 case Intrinsic::x86_sse_comilt_ss:
8207 case Intrinsic::x86_sse_comile_ss:
8208 case Intrinsic::x86_sse_comigt_ss:
8209 case Intrinsic::x86_sse_comige_ss:
8210 case Intrinsic::x86_sse_comineq_ss:
8211 case Intrinsic::x86_sse_ucomieq_ss:
8212 case Intrinsic::x86_sse_ucomilt_ss:
8213 case Intrinsic::x86_sse_ucomile_ss:
8214 case Intrinsic::x86_sse_ucomigt_ss:
8215 case Intrinsic::x86_sse_ucomige_ss:
8216 case Intrinsic::x86_sse_ucomineq_ss:
8217 case Intrinsic::x86_sse2_comieq_sd:
8218 case Intrinsic::x86_sse2_comilt_sd:
8219 case Intrinsic::x86_sse2_comile_sd:
8220 case Intrinsic::x86_sse2_comigt_sd:
8221 case Intrinsic::x86_sse2_comige_sd:
8222 case Intrinsic::x86_sse2_comineq_sd:
8223 case Intrinsic::x86_sse2_ucomieq_sd:
8224 case Intrinsic::x86_sse2_ucomilt_sd:
8225 case Intrinsic::x86_sse2_ucomile_sd:
8226 case Intrinsic::x86_sse2_ucomigt_sd:
8227 case Intrinsic::x86_sse2_ucomige_sd:
8228 case Intrinsic::x86_sse2_ucomineq_sd: {
8230 ISD::CondCode CC = ISD::SETCC_INVALID;
8233 case Intrinsic::x86_sse_comieq_ss:
8234 case Intrinsic::x86_sse2_comieq_sd:
8238 case Intrinsic::x86_sse_comilt_ss:
8239 case Intrinsic::x86_sse2_comilt_sd:
8243 case Intrinsic::x86_sse_comile_ss:
8244 case Intrinsic::x86_sse2_comile_sd:
8248 case Intrinsic::x86_sse_comigt_ss:
8249 case Intrinsic::x86_sse2_comigt_sd:
8253 case Intrinsic::x86_sse_comige_ss:
8254 case Intrinsic::x86_sse2_comige_sd:
8258 case Intrinsic::x86_sse_comineq_ss:
8259 case Intrinsic::x86_sse2_comineq_sd:
8263 case Intrinsic::x86_sse_ucomieq_ss:
8264 case Intrinsic::x86_sse2_ucomieq_sd:
8265 Opc = X86ISD::UCOMI;
8268 case Intrinsic::x86_sse_ucomilt_ss:
8269 case Intrinsic::x86_sse2_ucomilt_sd:
8270 Opc = X86ISD::UCOMI;
8273 case Intrinsic::x86_sse_ucomile_ss:
8274 case Intrinsic::x86_sse2_ucomile_sd:
8275 Opc = X86ISD::UCOMI;
8278 case Intrinsic::x86_sse_ucomigt_ss:
8279 case Intrinsic::x86_sse2_ucomigt_sd:
8280 Opc = X86ISD::UCOMI;
8283 case Intrinsic::x86_sse_ucomige_ss:
8284 case Intrinsic::x86_sse2_ucomige_sd:
8285 Opc = X86ISD::UCOMI;
8288 case Intrinsic::x86_sse_ucomineq_ss:
8289 case Intrinsic::x86_sse2_ucomineq_sd:
8290 Opc = X86ISD::UCOMI;
8295 SDValue LHS = Op.getOperand(1);
8296 SDValue RHS = Op.getOperand(2);
8297 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8298 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8299 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8300 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8301 DAG.getConstant(X86CC, MVT::i8), Cond);
8302 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8304 // ptest and testp intrinsics. The intrinsic these come from are designed to
8305 // return an integer value, not just an instruction so lower it to the ptest
8306 // or testp pattern and a setcc for the result.
8307 case Intrinsic::x86_sse41_ptestz:
8308 case Intrinsic::x86_sse41_ptestc:
8309 case Intrinsic::x86_sse41_ptestnzc:
8310 case Intrinsic::x86_avx_ptestz_256:
8311 case Intrinsic::x86_avx_ptestc_256:
8312 case Intrinsic::x86_avx_ptestnzc_256:
8313 case Intrinsic::x86_avx_vtestz_ps:
8314 case Intrinsic::x86_avx_vtestc_ps:
8315 case Intrinsic::x86_avx_vtestnzc_ps:
8316 case Intrinsic::x86_avx_vtestz_pd:
8317 case Intrinsic::x86_avx_vtestc_pd:
8318 case Intrinsic::x86_avx_vtestnzc_pd:
8319 case Intrinsic::x86_avx_vtestz_ps_256:
8320 case Intrinsic::x86_avx_vtestc_ps_256:
8321 case Intrinsic::x86_avx_vtestnzc_ps_256:
8322 case Intrinsic::x86_avx_vtestz_pd_256:
8323 case Intrinsic::x86_avx_vtestc_pd_256:
8324 case Intrinsic::x86_avx_vtestnzc_pd_256: {
8325 bool IsTestPacked = false;
8328 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8329 case Intrinsic::x86_avx_vtestz_ps:
8330 case Intrinsic::x86_avx_vtestz_pd:
8331 case Intrinsic::x86_avx_vtestz_ps_256:
8332 case Intrinsic::x86_avx_vtestz_pd_256:
8333 IsTestPacked = true; // Fallthrough
8334 case Intrinsic::x86_sse41_ptestz:
8335 case Intrinsic::x86_avx_ptestz_256:
8337 X86CC = X86::COND_E;
8339 case Intrinsic::x86_avx_vtestc_ps:
8340 case Intrinsic::x86_avx_vtestc_pd:
8341 case Intrinsic::x86_avx_vtestc_ps_256:
8342 case Intrinsic::x86_avx_vtestc_pd_256:
8343 IsTestPacked = true; // Fallthrough
8344 case Intrinsic::x86_sse41_ptestc:
8345 case Intrinsic::x86_avx_ptestc_256:
8347 X86CC = X86::COND_B;
8349 case Intrinsic::x86_avx_vtestnzc_ps:
8350 case Intrinsic::x86_avx_vtestnzc_pd:
8351 case Intrinsic::x86_avx_vtestnzc_ps_256:
8352 case Intrinsic::x86_avx_vtestnzc_pd_256:
8353 IsTestPacked = true; // Fallthrough
8354 case Intrinsic::x86_sse41_ptestnzc:
8355 case Intrinsic::x86_avx_ptestnzc_256:
8357 X86CC = X86::COND_A;
8361 SDValue LHS = Op.getOperand(1);
8362 SDValue RHS = Op.getOperand(2);
8363 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8364 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8365 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8366 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8367 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8370 // Fix vector shift instructions where the last operand is a non-immediate
8372 case Intrinsic::x86_sse2_pslli_w:
8373 case Intrinsic::x86_sse2_pslli_d:
8374 case Intrinsic::x86_sse2_pslli_q:
8375 case Intrinsic::x86_sse2_psrli_w:
8376 case Intrinsic::x86_sse2_psrli_d:
8377 case Intrinsic::x86_sse2_psrli_q:
8378 case Intrinsic::x86_sse2_psrai_w:
8379 case Intrinsic::x86_sse2_psrai_d:
8380 case Intrinsic::x86_mmx_pslli_w:
8381 case Intrinsic::x86_mmx_pslli_d:
8382 case Intrinsic::x86_mmx_pslli_q:
8383 case Intrinsic::x86_mmx_psrli_w:
8384 case Intrinsic::x86_mmx_psrli_d:
8385 case Intrinsic::x86_mmx_psrli_q:
8386 case Intrinsic::x86_mmx_psrai_w:
8387 case Intrinsic::x86_mmx_psrai_d: {
8388 SDValue ShAmt = Op.getOperand(2);
8389 if (isa<ConstantSDNode>(ShAmt))
8392 unsigned NewIntNo = 0;
8393 EVT ShAmtVT = MVT::v4i32;
8395 case Intrinsic::x86_sse2_pslli_w:
8396 NewIntNo = Intrinsic::x86_sse2_psll_w;
8398 case Intrinsic::x86_sse2_pslli_d:
8399 NewIntNo = Intrinsic::x86_sse2_psll_d;
8401 case Intrinsic::x86_sse2_pslli_q:
8402 NewIntNo = Intrinsic::x86_sse2_psll_q;
8404 case Intrinsic::x86_sse2_psrli_w:
8405 NewIntNo = Intrinsic::x86_sse2_psrl_w;
8407 case Intrinsic::x86_sse2_psrli_d:
8408 NewIntNo = Intrinsic::x86_sse2_psrl_d;
8410 case Intrinsic::x86_sse2_psrli_q:
8411 NewIntNo = Intrinsic::x86_sse2_psrl_q;
8413 case Intrinsic::x86_sse2_psrai_w:
8414 NewIntNo = Intrinsic::x86_sse2_psra_w;
8416 case Intrinsic::x86_sse2_psrai_d:
8417 NewIntNo = Intrinsic::x86_sse2_psra_d;
8420 ShAmtVT = MVT::v2i32;
8422 case Intrinsic::x86_mmx_pslli_w:
8423 NewIntNo = Intrinsic::x86_mmx_psll_w;
8425 case Intrinsic::x86_mmx_pslli_d:
8426 NewIntNo = Intrinsic::x86_mmx_psll_d;
8428 case Intrinsic::x86_mmx_pslli_q:
8429 NewIntNo = Intrinsic::x86_mmx_psll_q;
8431 case Intrinsic::x86_mmx_psrli_w:
8432 NewIntNo = Intrinsic::x86_mmx_psrl_w;
8434 case Intrinsic::x86_mmx_psrli_d:
8435 NewIntNo = Intrinsic::x86_mmx_psrl_d;
8437 case Intrinsic::x86_mmx_psrli_q:
8438 NewIntNo = Intrinsic::x86_mmx_psrl_q;
8440 case Intrinsic::x86_mmx_psrai_w:
8441 NewIntNo = Intrinsic::x86_mmx_psra_w;
8443 case Intrinsic::x86_mmx_psrai_d:
8444 NewIntNo = Intrinsic::x86_mmx_psra_d;
8446 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8452 // The vector shift intrinsics with scalars uses 32b shift amounts but
8453 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8457 ShOps[1] = DAG.getConstant(0, MVT::i32);
8458 if (ShAmtVT == MVT::v4i32) {
8459 ShOps[2] = DAG.getUNDEF(MVT::i32);
8460 ShOps[3] = DAG.getUNDEF(MVT::i32);
8461 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8463 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8464 // FIXME this must be lowered to get rid of the invalid type.
8467 EVT VT = Op.getValueType();
8468 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8469 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8470 DAG.getConstant(NewIntNo, MVT::i32),
8471 Op.getOperand(1), ShAmt);
8476 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8477 SelectionDAG &DAG) const {
8478 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8479 MFI->setReturnAddressIsTaken(true);
8481 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8482 DebugLoc dl = Op.getDebugLoc();
8485 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8487 DAG.getConstant(TD->getPointerSize(),
8488 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8489 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8490 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8492 MachinePointerInfo(), false, false, 0);
8495 // Just load the return address.
8496 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8497 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8498 RetAddrFI, MachinePointerInfo(), false, false, 0);
8501 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8502 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8503 MFI->setFrameAddressIsTaken(true);
8505 EVT VT = Op.getValueType();
8506 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
8507 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8508 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8509 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8511 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8512 MachinePointerInfo(),
8517 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8518 SelectionDAG &DAG) const {
8519 return DAG.getIntPtrConstant(2*TD->getPointerSize());
8522 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8523 MachineFunction &MF = DAG.getMachineFunction();
8524 SDValue Chain = Op.getOperand(0);
8525 SDValue Offset = Op.getOperand(1);
8526 SDValue Handler = Op.getOperand(2);
8527 DebugLoc dl = Op.getDebugLoc();
8529 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8530 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8532 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8534 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8535 DAG.getIntPtrConstant(TD->getPointerSize()));
8536 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8537 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8539 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8540 MF.getRegInfo().addLiveOut(StoreAddrReg);
8542 return DAG.getNode(X86ISD::EH_RETURN, dl,
8544 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8547 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8548 SelectionDAG &DAG) const {
8549 SDValue Root = Op.getOperand(0);
8550 SDValue Trmp = Op.getOperand(1); // trampoline
8551 SDValue FPtr = Op.getOperand(2); // nested function
8552 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8553 DebugLoc dl = Op.getDebugLoc();
8555 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8557 if (Subtarget->is64Bit()) {
8558 SDValue OutChains[6];
8560 // Large code-model.
8561 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8562 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8564 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8565 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8567 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8569 // Load the pointer to the nested function into R11.
8570 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8571 SDValue Addr = Trmp;
8572 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8573 Addr, MachinePointerInfo(TrmpAddr),
8576 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8577 DAG.getConstant(2, MVT::i64));
8578 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8579 MachinePointerInfo(TrmpAddr, 2),
8582 // Load the 'nest' parameter value into R10.
8583 // R10 is specified in X86CallingConv.td
8584 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8585 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8586 DAG.getConstant(10, MVT::i64));
8587 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8588 Addr, MachinePointerInfo(TrmpAddr, 10),
8591 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8592 DAG.getConstant(12, MVT::i64));
8593 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8594 MachinePointerInfo(TrmpAddr, 12),
8597 // Jump to the nested function.
8598 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8599 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8600 DAG.getConstant(20, MVT::i64));
8601 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8602 Addr, MachinePointerInfo(TrmpAddr, 20),
8605 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8606 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8607 DAG.getConstant(22, MVT::i64));
8608 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8609 MachinePointerInfo(TrmpAddr, 22),
8613 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8614 return DAG.getMergeValues(Ops, 2, dl);
8616 const Function *Func =
8617 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8618 CallingConv::ID CC = Func->getCallingConv();
8623 llvm_unreachable("Unsupported calling convention");
8624 case CallingConv::C:
8625 case CallingConv::X86_StdCall: {
8626 // Pass 'nest' parameter in ECX.
8627 // Must be kept in sync with X86CallingConv.td
8630 // Check that ECX wasn't needed by an 'inreg' parameter.
8631 const FunctionType *FTy = Func->getFunctionType();
8632 const AttrListPtr &Attrs = Func->getAttributes();
8634 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8635 unsigned InRegCount = 0;
8638 for (FunctionType::param_iterator I = FTy->param_begin(),
8639 E = FTy->param_end(); I != E; ++I, ++Idx)
8640 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8641 // FIXME: should only count parameters that are lowered to integers.
8642 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8644 if (InRegCount > 2) {
8645 report_fatal_error("Nest register in use - reduce number of inreg"
8651 case CallingConv::X86_FastCall:
8652 case CallingConv::X86_ThisCall:
8653 case CallingConv::Fast:
8654 // Pass 'nest' parameter in EAX.
8655 // Must be kept in sync with X86CallingConv.td
8660 SDValue OutChains[4];
8663 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8664 DAG.getConstant(10, MVT::i32));
8665 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8667 // This is storing the opcode for MOV32ri.
8668 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8669 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8670 OutChains[0] = DAG.getStore(Root, dl,
8671 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8672 Trmp, MachinePointerInfo(TrmpAddr),
8675 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8676 DAG.getConstant(1, MVT::i32));
8677 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8678 MachinePointerInfo(TrmpAddr, 1),
8681 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8682 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8683 DAG.getConstant(5, MVT::i32));
8684 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8685 MachinePointerInfo(TrmpAddr, 5),
8688 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8689 DAG.getConstant(6, MVT::i32));
8690 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8691 MachinePointerInfo(TrmpAddr, 6),
8695 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8696 return DAG.getMergeValues(Ops, 2, dl);
8700 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8701 SelectionDAG &DAG) const {
8703 The rounding mode is in bits 11:10 of FPSR, and has the following
8710 FLT_ROUNDS, on the other hand, expects the following:
8717 To perform the conversion, we do:
8718 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8721 MachineFunction &MF = DAG.getMachineFunction();
8722 const TargetMachine &TM = MF.getTarget();
8723 const TargetFrameLowering &TFI = *TM.getFrameLowering();
8724 unsigned StackAlignment = TFI.getStackAlignment();
8725 EVT VT = Op.getValueType();
8726 DebugLoc DL = Op.getDebugLoc();
8728 // Save FP Control Word to stack slot
8729 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8730 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8733 MachineMemOperand *MMO =
8734 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8735 MachineMemOperand::MOStore, 2, 2);
8737 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8738 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8739 DAG.getVTList(MVT::Other),
8740 Ops, 2, MVT::i16, MMO);
8742 // Load FP Control Word from stack slot
8743 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8744 MachinePointerInfo(), false, false, 0);
8746 // Transform as necessary
8748 DAG.getNode(ISD::SRL, DL, MVT::i16,
8749 DAG.getNode(ISD::AND, DL, MVT::i16,
8750 CWD, DAG.getConstant(0x800, MVT::i16)),
8751 DAG.getConstant(11, MVT::i8));
8753 DAG.getNode(ISD::SRL, DL, MVT::i16,
8754 DAG.getNode(ISD::AND, DL, MVT::i16,
8755 CWD, DAG.getConstant(0x400, MVT::i16)),
8756 DAG.getConstant(9, MVT::i8));
8759 DAG.getNode(ISD::AND, DL, MVT::i16,
8760 DAG.getNode(ISD::ADD, DL, MVT::i16,
8761 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8762 DAG.getConstant(1, MVT::i16)),
8763 DAG.getConstant(3, MVT::i16));
8766 return DAG.getNode((VT.getSizeInBits() < 16 ?
8767 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8770 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8771 EVT VT = Op.getValueType();
8773 unsigned NumBits = VT.getSizeInBits();
8774 DebugLoc dl = Op.getDebugLoc();
8776 Op = Op.getOperand(0);
8777 if (VT == MVT::i8) {
8778 // Zero extend to i32 since there is not an i8 bsr.
8780 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8783 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8784 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8785 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8787 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8790 DAG.getConstant(NumBits+NumBits-1, OpVT),
8791 DAG.getConstant(X86::COND_E, MVT::i8),
8794 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8796 // Finally xor with NumBits-1.
8797 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8800 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8804 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8805 EVT VT = Op.getValueType();
8807 unsigned NumBits = VT.getSizeInBits();
8808 DebugLoc dl = Op.getDebugLoc();
8810 Op = Op.getOperand(0);
8811 if (VT == MVT::i8) {
8813 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8816 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8817 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8818 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8820 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8823 DAG.getConstant(NumBits, OpVT),
8824 DAG.getConstant(X86::COND_E, MVT::i8),
8827 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8830 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8834 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8835 EVT VT = Op.getValueType();
8836 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8837 DebugLoc dl = Op.getDebugLoc();
8839 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8840 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8841 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8842 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8843 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8845 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8846 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8847 // return AloBlo + AloBhi + AhiBlo;
8849 SDValue A = Op.getOperand(0);
8850 SDValue B = Op.getOperand(1);
8852 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8853 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8854 A, DAG.getConstant(32, MVT::i32));
8855 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8856 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8857 B, DAG.getConstant(32, MVT::i32));
8858 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8859 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8861 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8862 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8864 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8865 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8867 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8868 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8869 AloBhi, DAG.getConstant(32, MVT::i32));
8870 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8871 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8872 AhiBlo, DAG.getConstant(32, MVT::i32));
8873 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8874 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8878 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8880 EVT VT = Op.getValueType();
8881 DebugLoc dl = Op.getDebugLoc();
8882 SDValue R = Op.getOperand(0);
8883 SDValue Amt = Op.getOperand(1);
8885 LLVMContext *Context = DAG.getContext();
8888 if (!Subtarget->hasSSE2()) return SDValue();
8890 // Optimize shl/srl/sra with constant shift amount.
8891 if (isSplatVector(Amt.getNode())) {
8892 SDValue SclrAmt = Amt->getOperand(0);
8893 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8894 uint64_t ShiftAmt = C->getZExtValue();
8896 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8897 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8898 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8899 R, DAG.getConstant(ShiftAmt, MVT::i32));
8901 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
8902 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8903 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8904 R, DAG.getConstant(ShiftAmt, MVT::i32));
8906 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
8907 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8908 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8909 R, DAG.getConstant(ShiftAmt, MVT::i32));
8911 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
8912 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8913 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8914 R, DAG.getConstant(ShiftAmt, MVT::i32));
8916 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
8917 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8918 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8919 R, DAG.getConstant(ShiftAmt, MVT::i32));
8921 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
8922 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8923 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8924 R, DAG.getConstant(ShiftAmt, MVT::i32));
8926 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
8927 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8928 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8929 R, DAG.getConstant(ShiftAmt, MVT::i32));
8931 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
8932 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8933 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8934 R, DAG.getConstant(ShiftAmt, MVT::i32));
8938 // Lower SHL with variable shift amount.
8939 // Cannot lower SHL without SSE2 or later.
8940 if (!Subtarget->hasSSE2()) return SDValue();
8942 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
8943 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8944 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8945 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8947 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8949 std::vector<Constant*> CV(4, CI);
8950 Constant *C = ConstantVector::get(CV);
8951 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8952 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8953 MachinePointerInfo::getConstantPool(),
8956 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8957 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8958 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8959 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8961 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
8963 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8964 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8965 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8967 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8968 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8970 std::vector<Constant*> CVM1(16, CM1);
8971 std::vector<Constant*> CVM2(16, CM2);
8972 Constant *C = ConstantVector::get(CVM1);
8973 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8974 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8975 MachinePointerInfo::getConstantPool(),
8978 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8979 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8980 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8981 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8982 DAG.getConstant(4, MVT::i32));
8983 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8985 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8987 C = ConstantVector::get(CVM2);
8988 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8989 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8990 MachinePointerInfo::getConstantPool(),
8993 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8994 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8995 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8996 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8997 DAG.getConstant(2, MVT::i32));
8998 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9000 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9002 // return pblendv(r, r+r, a);
9003 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
9004 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
9010 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
9011 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
9012 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
9013 // looks for this combo and may remove the "setcc" instruction if the "setcc"
9014 // has only one use.
9015 SDNode *N = Op.getNode();
9016 SDValue LHS = N->getOperand(0);
9017 SDValue RHS = N->getOperand(1);
9018 unsigned BaseOp = 0;
9020 DebugLoc DL = Op.getDebugLoc();
9021 switch (Op.getOpcode()) {
9022 default: llvm_unreachable("Unknown ovf instruction!");
9024 // A subtract of one will be selected as a INC. Note that INC doesn't
9025 // set CF, so we can't do this for UADDO.
9026 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9028 BaseOp = X86ISD::INC;
9032 BaseOp = X86ISD::ADD;
9036 BaseOp = X86ISD::ADD;
9040 // A subtract of one will be selected as a DEC. Note that DEC doesn't
9041 // set CF, so we can't do this for USUBO.
9042 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9044 BaseOp = X86ISD::DEC;
9048 BaseOp = X86ISD::SUB;
9052 BaseOp = X86ISD::SUB;
9056 BaseOp = X86ISD::SMUL;
9059 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9060 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9062 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9065 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9066 DAG.getConstant(X86::COND_O, MVT::i32),
9067 SDValue(Sum.getNode(), 2));
9069 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9074 // Also sets EFLAGS.
9075 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9076 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9079 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9080 DAG.getConstant(Cond, MVT::i32),
9081 SDValue(Sum.getNode(), 1));
9083 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9087 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
9088 DebugLoc dl = Op.getDebugLoc();
9089 SDNode* Node = Op.getNode();
9090 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
9091 EVT VT = Node->getValueType(0);
9093 if (Subtarget->hasSSE2() && VT.isVector()) {
9094 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
9095 ExtraVT.getScalarType().getSizeInBits();
9096 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
9098 unsigned SHLIntrinsicsID = 0;
9099 unsigned SRAIntrinsicsID = 0;
9100 switch (VT.getSimpleVT().SimpleTy) {
9104 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q;
9105 SRAIntrinsicsID = 0;
9109 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
9110 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
9114 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
9115 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
9120 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9121 DAG.getConstant(SHLIntrinsicsID, MVT::i32),
9122 Node->getOperand(0), ShAmt);
9124 // In case of 1 bit sext, no need to shr
9125 if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
9127 if (SRAIntrinsicsID) {
9128 Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9129 DAG.getConstant(SRAIntrinsicsID, MVT::i32),
9139 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9140 DebugLoc dl = Op.getDebugLoc();
9142 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
9143 // There isn't any reason to disable it if the target processor supports it.
9144 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
9145 SDValue Chain = Op.getOperand(0);
9146 SDValue Zero = DAG.getConstant(0, MVT::i32);
9148 DAG.getRegister(X86::ESP, MVT::i32), // Base
9149 DAG.getTargetConstant(1, MVT::i8), // Scale
9150 DAG.getRegister(0, MVT::i32), // Index
9151 DAG.getTargetConstant(0, MVT::i32), // Disp
9152 DAG.getRegister(0, MVT::i32), // Segment.
9157 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9158 array_lengthof(Ops));
9159 return SDValue(Res, 0);
9162 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9164 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9166 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9167 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9168 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9169 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9171 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9172 if (!Op1 && !Op2 && !Op3 && Op4)
9173 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9175 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9176 if (Op1 && !Op2 && !Op3 && !Op4)
9177 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9179 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9181 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9184 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9185 EVT T = Op.getValueType();
9186 DebugLoc DL = Op.getDebugLoc();
9189 switch(T.getSimpleVT().SimpleTy) {
9191 assert(false && "Invalid value type!");
9192 case MVT::i8: Reg = X86::AL; size = 1; break;
9193 case MVT::i16: Reg = X86::AX; size = 2; break;
9194 case MVT::i32: Reg = X86::EAX; size = 4; break;
9196 assert(Subtarget->is64Bit() && "Node not type legal!");
9197 Reg = X86::RAX; size = 8;
9200 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9201 Op.getOperand(2), SDValue());
9202 SDValue Ops[] = { cpIn.getValue(0),
9205 DAG.getTargetConstant(size, MVT::i8),
9207 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9208 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9209 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9212 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9216 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9217 SelectionDAG &DAG) const {
9218 assert(Subtarget->is64Bit() && "Result not type legalized?");
9219 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9220 SDValue TheChain = Op.getOperand(0);
9221 DebugLoc dl = Op.getDebugLoc();
9222 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9223 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9224 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9226 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9227 DAG.getConstant(32, MVT::i8));
9229 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9232 return DAG.getMergeValues(Ops, 2, dl);
9235 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9236 SelectionDAG &DAG) const {
9237 EVT SrcVT = Op.getOperand(0).getValueType();
9238 EVT DstVT = Op.getValueType();
9239 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9240 Subtarget->hasMMX() && "Unexpected custom BITCAST");
9241 assert((DstVT == MVT::i64 ||
9242 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9243 "Unexpected custom BITCAST");
9244 // i64 <=> MMX conversions are Legal.
9245 if (SrcVT==MVT::i64 && DstVT.isVector())
9247 if (DstVT==MVT::i64 && SrcVT.isVector())
9249 // MMX <=> MMX conversions are Legal.
9250 if (SrcVT.isVector() && DstVT.isVector())
9252 // All other conversions need to be expanded.
9256 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9257 SDNode *Node = Op.getNode();
9258 DebugLoc dl = Node->getDebugLoc();
9259 EVT T = Node->getValueType(0);
9260 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9261 DAG.getConstant(0, T), Node->getOperand(2));
9262 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9263 cast<AtomicSDNode>(Node)->getMemoryVT(),
9264 Node->getOperand(0),
9265 Node->getOperand(1), negOp,
9266 cast<AtomicSDNode>(Node)->getSrcValue(),
9267 cast<AtomicSDNode>(Node)->getAlignment());
9270 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9271 EVT VT = Op.getNode()->getValueType(0);
9273 // Let legalize expand this if it isn't a legal type yet.
9274 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9277 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9280 bool ExtraOp = false;
9281 switch (Op.getOpcode()) {
9282 default: assert(0 && "Invalid code");
9283 case ISD::ADDC: Opc = X86ISD::ADD; break;
9284 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9285 case ISD::SUBC: Opc = X86ISD::SUB; break;
9286 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9290 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9292 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9293 Op.getOperand(1), Op.getOperand(2));
9296 /// LowerOperation - Provide custom lowering hooks for some operations.
9298 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9299 switch (Op.getOpcode()) {
9300 default: llvm_unreachable("Should not custom lower this!");
9301 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
9302 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
9303 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
9304 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
9305 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
9306 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
9307 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
9308 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9309 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9310 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
9311 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
9312 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
9313 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9314 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9315 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9316 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
9317 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
9318 case ISD::SHL_PARTS:
9319 case ISD::SRA_PARTS:
9320 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
9321 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
9322 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
9323 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
9324 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
9325 case ISD::FABS: return LowerFABS(Op, DAG);
9326 case ISD::FNEG: return LowerFNEG(Op, DAG);
9327 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
9328 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
9329 case ISD::SETCC: return LowerSETCC(Op, DAG);
9330 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
9331 case ISD::SELECT: return LowerSELECT(Op, DAG);
9332 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
9333 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
9334 case ISD::VASTART: return LowerVASTART(Op, DAG);
9335 case ISD::VAARG: return LowerVAARG(Op, DAG);
9336 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
9337 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9338 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9339 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9340 case ISD::FRAME_TO_ARGS_OFFSET:
9341 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9342 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9343 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
9344 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
9345 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9346 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
9347 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
9348 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
9351 case ISD::SHL: return LowerShift(Op, DAG);
9357 case ISD::UMULO: return LowerXALUO(Op, DAG);
9358 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
9359 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
9363 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9367 void X86TargetLowering::
9368 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9369 SelectionDAG &DAG, unsigned NewOp) const {
9370 EVT T = Node->getValueType(0);
9371 DebugLoc dl = Node->getDebugLoc();
9372 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9374 SDValue Chain = Node->getOperand(0);
9375 SDValue In1 = Node->getOperand(1);
9376 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9377 Node->getOperand(2), DAG.getIntPtrConstant(0));
9378 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9379 Node->getOperand(2), DAG.getIntPtrConstant(1));
9380 SDValue Ops[] = { Chain, In1, In2L, In2H };
9381 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9383 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9384 cast<MemSDNode>(Node)->getMemOperand());
9385 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9386 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9387 Results.push_back(Result.getValue(2));
9390 /// ReplaceNodeResults - Replace a node with an illegal result type
9391 /// with a new node built out of custom code.
9392 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9393 SmallVectorImpl<SDValue>&Results,
9394 SelectionDAG &DAG) const {
9395 DebugLoc dl = N->getDebugLoc();
9396 switch (N->getOpcode()) {
9398 assert(false && "Do not know how to custom type legalize this operation!");
9400 case ISD::SIGN_EXTEND_INREG:
9405 // We don't want to expand or promote these.
9407 case ISD::FP_TO_SINT: {
9408 std::pair<SDValue,SDValue> Vals =
9409 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9410 SDValue FIST = Vals.first, StackSlot = Vals.second;
9411 if (FIST.getNode() != 0) {
9412 EVT VT = N->getValueType(0);
9413 // Return a load from the stack slot.
9414 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9415 MachinePointerInfo(), false, false, 0));
9419 case ISD::READCYCLECOUNTER: {
9420 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9421 SDValue TheChain = N->getOperand(0);
9422 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9423 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9425 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9427 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9428 SDValue Ops[] = { eax, edx };
9429 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9430 Results.push_back(edx.getValue(1));
9433 case ISD::ATOMIC_CMP_SWAP: {
9434 EVT T = N->getValueType(0);
9435 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9436 SDValue cpInL, cpInH;
9437 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9438 DAG.getConstant(0, MVT::i32));
9439 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9440 DAG.getConstant(1, MVT::i32));
9441 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9442 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9444 SDValue swapInL, swapInH;
9445 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9446 DAG.getConstant(0, MVT::i32));
9447 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9448 DAG.getConstant(1, MVT::i32));
9449 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9451 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9452 swapInL.getValue(1));
9453 SDValue Ops[] = { swapInH.getValue(0),
9455 swapInH.getValue(1) };
9456 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9457 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9458 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9460 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9461 MVT::i32, Result.getValue(1));
9462 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9463 MVT::i32, cpOutL.getValue(2));
9464 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9465 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9466 Results.push_back(cpOutH.getValue(1));
9469 case ISD::ATOMIC_LOAD_ADD:
9470 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9472 case ISD::ATOMIC_LOAD_AND:
9473 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9475 case ISD::ATOMIC_LOAD_NAND:
9476 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9478 case ISD::ATOMIC_LOAD_OR:
9479 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9481 case ISD::ATOMIC_LOAD_SUB:
9482 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9484 case ISD::ATOMIC_LOAD_XOR:
9485 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9487 case ISD::ATOMIC_SWAP:
9488 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9493 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9495 default: return NULL;
9496 case X86ISD::BSF: return "X86ISD::BSF";
9497 case X86ISD::BSR: return "X86ISD::BSR";
9498 case X86ISD::SHLD: return "X86ISD::SHLD";
9499 case X86ISD::SHRD: return "X86ISD::SHRD";
9500 case X86ISD::FAND: return "X86ISD::FAND";
9501 case X86ISD::FOR: return "X86ISD::FOR";
9502 case X86ISD::FXOR: return "X86ISD::FXOR";
9503 case X86ISD::FSRL: return "X86ISD::FSRL";
9504 case X86ISD::FILD: return "X86ISD::FILD";
9505 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
9506 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9507 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9508 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9509 case X86ISD::FLD: return "X86ISD::FLD";
9510 case X86ISD::FST: return "X86ISD::FST";
9511 case X86ISD::CALL: return "X86ISD::CALL";
9512 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
9513 case X86ISD::BT: return "X86ISD::BT";
9514 case X86ISD::CMP: return "X86ISD::CMP";
9515 case X86ISD::COMI: return "X86ISD::COMI";
9516 case X86ISD::UCOMI: return "X86ISD::UCOMI";
9517 case X86ISD::SETCC: return "X86ISD::SETCC";
9518 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
9519 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
9520 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
9521 case X86ISD::CMOV: return "X86ISD::CMOV";
9522 case X86ISD::BRCOND: return "X86ISD::BRCOND";
9523 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
9524 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
9525 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
9526 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
9527 case X86ISD::Wrapper: return "X86ISD::Wrapper";
9528 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
9529 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
9530 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
9531 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
9532 case X86ISD::PINSRB: return "X86ISD::PINSRB";
9533 case X86ISD::PINSRW: return "X86ISD::PINSRW";
9534 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
9535 case X86ISD::ANDNP: return "X86ISD::ANDNP";
9536 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
9537 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
9538 case X86ISD::PSIGND: return "X86ISD::PSIGND";
9539 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB";
9540 case X86ISD::FMAX: return "X86ISD::FMAX";
9541 case X86ISD::FMIN: return "X86ISD::FMIN";
9542 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
9543 case X86ISD::FRCP: return "X86ISD::FRCP";
9544 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
9545 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
9546 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
9547 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
9548 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
9549 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
9550 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
9551 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
9552 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
9553 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
9554 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
9555 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
9556 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
9557 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
9558 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
9559 case X86ISD::VSHL: return "X86ISD::VSHL";
9560 case X86ISD::VSRL: return "X86ISD::VSRL";
9561 case X86ISD::CMPPD: return "X86ISD::CMPPD";
9562 case X86ISD::CMPPS: return "X86ISD::CMPPS";
9563 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
9564 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
9565 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
9566 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
9567 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
9568 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
9569 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
9570 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
9571 case X86ISD::ADD: return "X86ISD::ADD";
9572 case X86ISD::SUB: return "X86ISD::SUB";
9573 case X86ISD::ADC: return "X86ISD::ADC";
9574 case X86ISD::SBB: return "X86ISD::SBB";
9575 case X86ISD::SMUL: return "X86ISD::SMUL";
9576 case X86ISD::UMUL: return "X86ISD::UMUL";
9577 case X86ISD::INC: return "X86ISD::INC";
9578 case X86ISD::DEC: return "X86ISD::DEC";
9579 case X86ISD::OR: return "X86ISD::OR";
9580 case X86ISD::XOR: return "X86ISD::XOR";
9581 case X86ISD::AND: return "X86ISD::AND";
9582 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
9583 case X86ISD::PTEST: return "X86ISD::PTEST";
9584 case X86ISD::TESTP: return "X86ISD::TESTP";
9585 case X86ISD::PALIGN: return "X86ISD::PALIGN";
9586 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
9587 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
9588 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
9589 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
9590 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
9591 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
9592 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
9593 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
9594 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
9595 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
9596 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
9597 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
9598 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
9599 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
9600 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
9601 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
9602 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
9603 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
9604 case X86ISD::MOVSD: return "X86ISD::MOVSD";
9605 case X86ISD::MOVSS: return "X86ISD::MOVSS";
9606 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
9607 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
9608 case X86ISD::VUNPCKLPS: return "X86ISD::VUNPCKLPS";
9609 case X86ISD::VUNPCKLPD: return "X86ISD::VUNPCKLPD";
9610 case X86ISD::VUNPCKLPSY: return "X86ISD::VUNPCKLPSY";
9611 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
9612 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
9613 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
9614 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
9615 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
9616 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
9617 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
9618 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
9619 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
9620 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
9621 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
9622 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9623 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
9624 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
9628 // isLegalAddressingMode - Return true if the addressing mode represented
9629 // by AM is legal for this target, for a load/store of the specified type.
9630 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9631 const Type *Ty) const {
9632 // X86 supports extremely general addressing modes.
9633 CodeModel::Model M = getTargetMachine().getCodeModel();
9634 Reloc::Model R = getTargetMachine().getRelocationModel();
9636 // X86 allows a sign-extended 32-bit immediate field as a displacement.
9637 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9642 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9644 // If a reference to this global requires an extra load, we can't fold it.
9645 if (isGlobalStubReference(GVFlags))
9648 // If BaseGV requires a register for the PIC base, we cannot also have a
9649 // BaseReg specified.
9650 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9653 // If lower 4G is not available, then we must use rip-relative addressing.
9654 if ((M != CodeModel::Small || R != Reloc::Static) &&
9655 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9665 // These scales always work.
9670 // These scales are formed with basereg+scalereg. Only accept if there is
9675 default: // Other stuff never works.
9683 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9684 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9686 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9687 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9688 if (NumBits1 <= NumBits2)
9693 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9694 if (!VT1.isInteger() || !VT2.isInteger())
9696 unsigned NumBits1 = VT1.getSizeInBits();
9697 unsigned NumBits2 = VT2.getSizeInBits();
9698 if (NumBits1 <= NumBits2)
9703 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9704 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9705 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9708 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9709 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9710 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9713 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9714 // i16 instructions are longer (0x66 prefix) and potentially slower.
9715 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9718 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9719 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9720 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9721 /// are assumed to be legal.
9723 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9725 // Very little shuffling can be done for 64-bit vectors right now.
9726 if (VT.getSizeInBits() == 64)
9727 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9729 // FIXME: pshufb, blends, shifts.
9730 return (VT.getVectorNumElements() == 2 ||
9731 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9732 isMOVLMask(M, VT) ||
9733 isSHUFPMask(M, VT) ||
9734 isPSHUFDMask(M, VT) ||
9735 isPSHUFHWMask(M, VT) ||
9736 isPSHUFLWMask(M, VT) ||
9737 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9738 isUNPCKLMask(M, VT) ||
9739 isUNPCKHMask(M, VT) ||
9740 isUNPCKL_v_undef_Mask(M, VT) ||
9741 isUNPCKH_v_undef_Mask(M, VT));
9745 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9747 unsigned NumElts = VT.getVectorNumElements();
9748 // FIXME: This collection of masks seems suspect.
9751 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9752 return (isMOVLMask(Mask, VT) ||
9753 isCommutedMOVLMask(Mask, VT, true) ||
9754 isSHUFPMask(Mask, VT) ||
9755 isCommutedSHUFPMask(Mask, VT));
9760 //===----------------------------------------------------------------------===//
9761 // X86 Scheduler Hooks
9762 //===----------------------------------------------------------------------===//
9764 // private utility function
9766 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9767 MachineBasicBlock *MBB,
9774 TargetRegisterClass *RC,
9775 bool invSrc) const {
9776 // For the atomic bitwise operator, we generate
9779 // ld t1 = [bitinstr.addr]
9780 // op t2 = t1, [bitinstr.val]
9782 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9784 // fallthrough -->nextMBB
9785 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9786 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9787 MachineFunction::iterator MBBIter = MBB;
9790 /// First build the CFG
9791 MachineFunction *F = MBB->getParent();
9792 MachineBasicBlock *thisMBB = MBB;
9793 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9794 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9795 F->insert(MBBIter, newMBB);
9796 F->insert(MBBIter, nextMBB);
9798 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9799 nextMBB->splice(nextMBB->begin(), thisMBB,
9800 llvm::next(MachineBasicBlock::iterator(bInstr)),
9802 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9804 // Update thisMBB to fall through to newMBB
9805 thisMBB->addSuccessor(newMBB);
9807 // newMBB jumps to itself and fall through to nextMBB
9808 newMBB->addSuccessor(nextMBB);
9809 newMBB->addSuccessor(newMBB);
9811 // Insert instructions into newMBB based on incoming instruction
9812 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9813 "unexpected number of operands");
9814 DebugLoc dl = bInstr->getDebugLoc();
9815 MachineOperand& destOper = bInstr->getOperand(0);
9816 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9817 int numArgs = bInstr->getNumOperands() - 1;
9818 for (int i=0; i < numArgs; ++i)
9819 argOpers[i] = &bInstr->getOperand(i+1);
9821 // x86 address has 4 operands: base, index, scale, and displacement
9822 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9823 int valArgIndx = lastAddrIndx + 1;
9825 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9826 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9827 for (int i=0; i <= lastAddrIndx; ++i)
9828 (*MIB).addOperand(*argOpers[i]);
9830 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9832 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9837 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9838 assert((argOpers[valArgIndx]->isReg() ||
9839 argOpers[valArgIndx]->isImm()) &&
9841 if (argOpers[valArgIndx]->isReg())
9842 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9844 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9846 (*MIB).addOperand(*argOpers[valArgIndx]);
9848 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9851 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9852 for (int i=0; i <= lastAddrIndx; ++i)
9853 (*MIB).addOperand(*argOpers[i]);
9855 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9856 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9857 bInstr->memoperands_end());
9859 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9863 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9865 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9869 // private utility function: 64 bit atomics on 32 bit host.
9871 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9872 MachineBasicBlock *MBB,
9877 bool invSrc) const {
9878 // For the atomic bitwise operator, we generate
9879 // thisMBB (instructions are in pairs, except cmpxchg8b)
9880 // ld t1,t2 = [bitinstr.addr]
9882 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9883 // op t5, t6 <- out1, out2, [bitinstr.val]
9884 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9885 // mov ECX, EBX <- t5, t6
9886 // mov EAX, EDX <- t1, t2
9887 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9888 // mov t3, t4 <- EAX, EDX
9890 // result in out1, out2
9891 // fallthrough -->nextMBB
9893 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9894 const unsigned LoadOpc = X86::MOV32rm;
9895 const unsigned NotOpc = X86::NOT32r;
9896 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9897 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9898 MachineFunction::iterator MBBIter = MBB;
9901 /// First build the CFG
9902 MachineFunction *F = MBB->getParent();
9903 MachineBasicBlock *thisMBB = MBB;
9904 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9905 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9906 F->insert(MBBIter, newMBB);
9907 F->insert(MBBIter, nextMBB);
9909 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9910 nextMBB->splice(nextMBB->begin(), thisMBB,
9911 llvm::next(MachineBasicBlock::iterator(bInstr)),
9913 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9915 // Update thisMBB to fall through to newMBB
9916 thisMBB->addSuccessor(newMBB);
9918 // newMBB jumps to itself and fall through to nextMBB
9919 newMBB->addSuccessor(nextMBB);
9920 newMBB->addSuccessor(newMBB);
9922 DebugLoc dl = bInstr->getDebugLoc();
9923 // Insert instructions into newMBB based on incoming instruction
9924 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9925 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9926 "unexpected number of operands");
9927 MachineOperand& dest1Oper = bInstr->getOperand(0);
9928 MachineOperand& dest2Oper = bInstr->getOperand(1);
9929 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9930 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9931 argOpers[i] = &bInstr->getOperand(i+2);
9933 // We use some of the operands multiple times, so conservatively just
9934 // clear any kill flags that might be present.
9935 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9936 argOpers[i]->setIsKill(false);
9939 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9940 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9942 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9943 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9944 for (int i=0; i <= lastAddrIndx; ++i)
9945 (*MIB).addOperand(*argOpers[i]);
9946 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9947 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9948 // add 4 to displacement.
9949 for (int i=0; i <= lastAddrIndx-2; ++i)
9950 (*MIB).addOperand(*argOpers[i]);
9951 MachineOperand newOp3 = *(argOpers[3]);
9953 newOp3.setImm(newOp3.getImm()+4);
9955 newOp3.setOffset(newOp3.getOffset()+4);
9956 (*MIB).addOperand(newOp3);
9957 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9959 // t3/4 are defined later, at the bottom of the loop
9960 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9961 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9962 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9963 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9964 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9965 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9967 // The subsequent operations should be using the destination registers of
9968 //the PHI instructions.
9970 t1 = F->getRegInfo().createVirtualRegister(RC);
9971 t2 = F->getRegInfo().createVirtualRegister(RC);
9972 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9973 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9975 t1 = dest1Oper.getReg();
9976 t2 = dest2Oper.getReg();
9979 int valArgIndx = lastAddrIndx + 1;
9980 assert((argOpers[valArgIndx]->isReg() ||
9981 argOpers[valArgIndx]->isImm()) &&
9983 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9984 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9985 if (argOpers[valArgIndx]->isReg())
9986 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9988 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9989 if (regOpcL != X86::MOV32rr)
9991 (*MIB).addOperand(*argOpers[valArgIndx]);
9992 assert(argOpers[valArgIndx + 1]->isReg() ==
9993 argOpers[valArgIndx]->isReg());
9994 assert(argOpers[valArgIndx + 1]->isImm() ==
9995 argOpers[valArgIndx]->isImm());
9996 if (argOpers[valArgIndx + 1]->isReg())
9997 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9999 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
10000 if (regOpcH != X86::MOV32rr)
10002 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
10004 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10006 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
10009 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
10011 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
10014 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
10015 for (int i=0; i <= lastAddrIndx; ++i)
10016 (*MIB).addOperand(*argOpers[i]);
10018 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10019 (*MIB).setMemRefs(bInstr->memoperands_begin(),
10020 bInstr->memoperands_end());
10022 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
10023 MIB.addReg(X86::EAX);
10024 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
10025 MIB.addReg(X86::EDX);
10028 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10030 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
10034 // private utility function
10035 MachineBasicBlock *
10036 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
10037 MachineBasicBlock *MBB,
10038 unsigned cmovOpc) const {
10039 // For the atomic min/max operator, we generate
10042 // ld t1 = [min/max.addr]
10043 // mov t2 = [min/max.val]
10045 // cmov[cond] t2 = t1
10047 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
10049 // fallthrough -->nextMBB
10051 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10052 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10053 MachineFunction::iterator MBBIter = MBB;
10056 /// First build the CFG
10057 MachineFunction *F = MBB->getParent();
10058 MachineBasicBlock *thisMBB = MBB;
10059 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10060 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10061 F->insert(MBBIter, newMBB);
10062 F->insert(MBBIter, nextMBB);
10064 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10065 nextMBB->splice(nextMBB->begin(), thisMBB,
10066 llvm::next(MachineBasicBlock::iterator(mInstr)),
10068 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10070 // Update thisMBB to fall through to newMBB
10071 thisMBB->addSuccessor(newMBB);
10073 // newMBB jumps to newMBB and fall through to nextMBB
10074 newMBB->addSuccessor(nextMBB);
10075 newMBB->addSuccessor(newMBB);
10077 DebugLoc dl = mInstr->getDebugLoc();
10078 // Insert instructions into newMBB based on incoming instruction
10079 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10080 "unexpected number of operands");
10081 MachineOperand& destOper = mInstr->getOperand(0);
10082 MachineOperand* argOpers[2 + X86::AddrNumOperands];
10083 int numArgs = mInstr->getNumOperands() - 1;
10084 for (int i=0; i < numArgs; ++i)
10085 argOpers[i] = &mInstr->getOperand(i+1);
10087 // x86 address has 4 operands: base, index, scale, and displacement
10088 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10089 int valArgIndx = lastAddrIndx + 1;
10091 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10092 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10093 for (int i=0; i <= lastAddrIndx; ++i)
10094 (*MIB).addOperand(*argOpers[i]);
10096 // We only support register and immediate values
10097 assert((argOpers[valArgIndx]->isReg() ||
10098 argOpers[valArgIndx]->isImm()) &&
10099 "invalid operand");
10101 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10102 if (argOpers[valArgIndx]->isReg())
10103 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10105 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10106 (*MIB).addOperand(*argOpers[valArgIndx]);
10108 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10111 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10116 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10117 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10121 // Cmp and exchange if none has modified the memory location
10122 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10123 for (int i=0; i <= lastAddrIndx; ++i)
10124 (*MIB).addOperand(*argOpers[i]);
10126 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10127 (*MIB).setMemRefs(mInstr->memoperands_begin(),
10128 mInstr->memoperands_end());
10130 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10131 MIB.addReg(X86::EAX);
10134 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10136 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
10140 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10141 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10142 // in the .td file.
10143 MachineBasicBlock *
10144 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10145 unsigned numArgs, bool memArg) const {
10146 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10147 "Target must have SSE4.2 or AVX features enabled");
10149 DebugLoc dl = MI->getDebugLoc();
10150 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10152 if (!Subtarget->hasAVX()) {
10154 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10156 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10159 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10161 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10164 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10165 for (unsigned i = 0; i < numArgs; ++i) {
10166 MachineOperand &Op = MI->getOperand(i+1);
10167 if (!(Op.isReg() && Op.isImplicit()))
10168 MIB.addOperand(Op);
10170 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10171 .addReg(X86::XMM0);
10173 MI->eraseFromParent();
10177 MachineBasicBlock *
10178 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10179 DebugLoc dl = MI->getDebugLoc();
10180 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10182 // Address into RAX/EAX, other two args into ECX, EDX.
10183 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10184 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10185 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10186 for (int i = 0; i < X86::AddrNumOperands; ++i)
10187 MIB.addOperand(MI->getOperand(i));
10189 unsigned ValOps = X86::AddrNumOperands;
10190 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10191 .addReg(MI->getOperand(ValOps).getReg());
10192 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10193 .addReg(MI->getOperand(ValOps+1).getReg());
10195 // The instruction doesn't actually take any operands though.
10196 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10198 MI->eraseFromParent(); // The pseudo is gone now.
10202 MachineBasicBlock *
10203 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10204 DebugLoc dl = MI->getDebugLoc();
10205 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10207 // First arg in ECX, the second in EAX.
10208 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10209 .addReg(MI->getOperand(0).getReg());
10210 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10211 .addReg(MI->getOperand(1).getReg());
10213 // The instruction doesn't actually take any operands though.
10214 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10216 MI->eraseFromParent(); // The pseudo is gone now.
10220 MachineBasicBlock *
10221 X86TargetLowering::EmitVAARG64WithCustomInserter(
10223 MachineBasicBlock *MBB) const {
10224 // Emit va_arg instruction on X86-64.
10226 // Operands to this pseudo-instruction:
10227 // 0 ) Output : destination address (reg)
10228 // 1-5) Input : va_list address (addr, i64mem)
10229 // 6 ) ArgSize : Size (in bytes) of vararg type
10230 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10231 // 8 ) Align : Alignment of type
10232 // 9 ) EFLAGS (implicit-def)
10234 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10235 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10237 unsigned DestReg = MI->getOperand(0).getReg();
10238 MachineOperand &Base = MI->getOperand(1);
10239 MachineOperand &Scale = MI->getOperand(2);
10240 MachineOperand &Index = MI->getOperand(3);
10241 MachineOperand &Disp = MI->getOperand(4);
10242 MachineOperand &Segment = MI->getOperand(5);
10243 unsigned ArgSize = MI->getOperand(6).getImm();
10244 unsigned ArgMode = MI->getOperand(7).getImm();
10245 unsigned Align = MI->getOperand(8).getImm();
10247 // Memory Reference
10248 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10249 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10250 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10252 // Machine Information
10253 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10254 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10255 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10256 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10257 DebugLoc DL = MI->getDebugLoc();
10259 // struct va_list {
10262 // i64 overflow_area (address)
10263 // i64 reg_save_area (address)
10265 // sizeof(va_list) = 24
10266 // alignment(va_list) = 8
10268 unsigned TotalNumIntRegs = 6;
10269 unsigned TotalNumXMMRegs = 8;
10270 bool UseGPOffset = (ArgMode == 1);
10271 bool UseFPOffset = (ArgMode == 2);
10272 unsigned MaxOffset = TotalNumIntRegs * 8 +
10273 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10275 /* Align ArgSize to a multiple of 8 */
10276 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10277 bool NeedsAlign = (Align > 8);
10279 MachineBasicBlock *thisMBB = MBB;
10280 MachineBasicBlock *overflowMBB;
10281 MachineBasicBlock *offsetMBB;
10282 MachineBasicBlock *endMBB;
10284 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
10285 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
10286 unsigned OffsetReg = 0;
10288 if (!UseGPOffset && !UseFPOffset) {
10289 // If we only pull from the overflow region, we don't create a branch.
10290 // We don't need to alter control flow.
10291 OffsetDestReg = 0; // unused
10292 OverflowDestReg = DestReg;
10295 overflowMBB = thisMBB;
10298 // First emit code to check if gp_offset (or fp_offset) is below the bound.
10299 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10300 // If not, pull from overflow_area. (branch to overflowMBB)
10305 // offsetMBB overflowMBB
10310 // Registers for the PHI in endMBB
10311 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10312 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10314 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10315 MachineFunction *MF = MBB->getParent();
10316 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10317 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10318 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10320 MachineFunction::iterator MBBIter = MBB;
10323 // Insert the new basic blocks
10324 MF->insert(MBBIter, offsetMBB);
10325 MF->insert(MBBIter, overflowMBB);
10326 MF->insert(MBBIter, endMBB);
10328 // Transfer the remainder of MBB and its successor edges to endMBB.
10329 endMBB->splice(endMBB->begin(), thisMBB,
10330 llvm::next(MachineBasicBlock::iterator(MI)),
10332 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10334 // Make offsetMBB and overflowMBB successors of thisMBB
10335 thisMBB->addSuccessor(offsetMBB);
10336 thisMBB->addSuccessor(overflowMBB);
10338 // endMBB is a successor of both offsetMBB and overflowMBB
10339 offsetMBB->addSuccessor(endMBB);
10340 overflowMBB->addSuccessor(endMBB);
10342 // Load the offset value into a register
10343 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10344 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10348 .addDisp(Disp, UseFPOffset ? 4 : 0)
10349 .addOperand(Segment)
10350 .setMemRefs(MMOBegin, MMOEnd);
10352 // Check if there is enough room left to pull this argument.
10353 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10355 .addImm(MaxOffset + 8 - ArgSizeA8);
10357 // Branch to "overflowMBB" if offset >= max
10358 // Fall through to "offsetMBB" otherwise
10359 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10360 .addMBB(overflowMBB);
10363 // In offsetMBB, emit code to use the reg_save_area.
10365 assert(OffsetReg != 0);
10367 // Read the reg_save_area address.
10368 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10369 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10374 .addOperand(Segment)
10375 .setMemRefs(MMOBegin, MMOEnd);
10377 // Zero-extend the offset
10378 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10379 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10382 .addImm(X86::sub_32bit);
10384 // Add the offset to the reg_save_area to get the final address.
10385 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10386 .addReg(OffsetReg64)
10387 .addReg(RegSaveReg);
10389 // Compute the offset for the next argument
10390 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10391 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10393 .addImm(UseFPOffset ? 16 : 8);
10395 // Store it back into the va_list.
10396 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10400 .addDisp(Disp, UseFPOffset ? 4 : 0)
10401 .addOperand(Segment)
10402 .addReg(NextOffsetReg)
10403 .setMemRefs(MMOBegin, MMOEnd);
10406 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10411 // Emit code to use overflow area
10414 // Load the overflow_area address into a register.
10415 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10416 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10421 .addOperand(Segment)
10422 .setMemRefs(MMOBegin, MMOEnd);
10424 // If we need to align it, do so. Otherwise, just copy the address
10425 // to OverflowDestReg.
10427 // Align the overflow address
10428 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10429 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10431 // aligned_addr = (addr + (align-1)) & ~(align-1)
10432 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10433 .addReg(OverflowAddrReg)
10436 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10438 .addImm(~(uint64_t)(Align-1));
10440 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10441 .addReg(OverflowAddrReg);
10444 // Compute the next overflow address after this argument.
10445 // (the overflow address should be kept 8-byte aligned)
10446 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10447 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10448 .addReg(OverflowDestReg)
10449 .addImm(ArgSizeA8);
10451 // Store the new overflow address.
10452 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10457 .addOperand(Segment)
10458 .addReg(NextAddrReg)
10459 .setMemRefs(MMOBegin, MMOEnd);
10461 // If we branched, emit the PHI to the front of endMBB.
10463 BuildMI(*endMBB, endMBB->begin(), DL,
10464 TII->get(X86::PHI), DestReg)
10465 .addReg(OffsetDestReg).addMBB(offsetMBB)
10466 .addReg(OverflowDestReg).addMBB(overflowMBB);
10469 // Erase the pseudo instruction
10470 MI->eraseFromParent();
10475 MachineBasicBlock *
10476 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10478 MachineBasicBlock *MBB) const {
10479 // Emit code to save XMM registers to the stack. The ABI says that the
10480 // number of registers to save is given in %al, so it's theoretically
10481 // possible to do an indirect jump trick to avoid saving all of them,
10482 // however this code takes a simpler approach and just executes all
10483 // of the stores if %al is non-zero. It's less code, and it's probably
10484 // easier on the hardware branch predictor, and stores aren't all that
10485 // expensive anyway.
10487 // Create the new basic blocks. One block contains all the XMM stores,
10488 // and one block is the final destination regardless of whether any
10489 // stores were performed.
10490 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10491 MachineFunction *F = MBB->getParent();
10492 MachineFunction::iterator MBBIter = MBB;
10494 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10495 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10496 F->insert(MBBIter, XMMSaveMBB);
10497 F->insert(MBBIter, EndMBB);
10499 // Transfer the remainder of MBB and its successor edges to EndMBB.
10500 EndMBB->splice(EndMBB->begin(), MBB,
10501 llvm::next(MachineBasicBlock::iterator(MI)),
10503 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10505 // The original block will now fall through to the XMM save block.
10506 MBB->addSuccessor(XMMSaveMBB);
10507 // The XMMSaveMBB will fall through to the end block.
10508 XMMSaveMBB->addSuccessor(EndMBB);
10510 // Now add the instructions.
10511 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10512 DebugLoc DL = MI->getDebugLoc();
10514 unsigned CountReg = MI->getOperand(0).getReg();
10515 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10516 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10518 if (!Subtarget->isTargetWin64()) {
10519 // If %al is 0, branch around the XMM save block.
10520 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10521 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10522 MBB->addSuccessor(EndMBB);
10525 // In the XMM save block, save all the XMM argument registers.
10526 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10527 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10528 MachineMemOperand *MMO =
10529 F->getMachineMemOperand(
10530 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10531 MachineMemOperand::MOStore,
10532 /*Size=*/16, /*Align=*/16);
10533 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10534 .addFrameIndex(RegSaveFrameIndex)
10535 .addImm(/*Scale=*/1)
10536 .addReg(/*IndexReg=*/0)
10537 .addImm(/*Disp=*/Offset)
10538 .addReg(/*Segment=*/0)
10539 .addReg(MI->getOperand(i).getReg())
10540 .addMemOperand(MMO);
10543 MI->eraseFromParent(); // The pseudo instruction is gone now.
10548 MachineBasicBlock *
10549 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10550 MachineBasicBlock *BB) const {
10551 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10552 DebugLoc DL = MI->getDebugLoc();
10554 // To "insert" a SELECT_CC instruction, we actually have to insert the
10555 // diamond control-flow pattern. The incoming instruction knows the
10556 // destination vreg to set, the condition code register to branch on, the
10557 // true/false values to select between, and a branch opcode to use.
10558 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10559 MachineFunction::iterator It = BB;
10565 // cmpTY ccX, r1, r2
10567 // fallthrough --> copy0MBB
10568 MachineBasicBlock *thisMBB = BB;
10569 MachineFunction *F = BB->getParent();
10570 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10571 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10572 F->insert(It, copy0MBB);
10573 F->insert(It, sinkMBB);
10575 // If the EFLAGS register isn't dead in the terminator, then claim that it's
10576 // live into the sink and copy blocks.
10577 const MachineFunction *MF = BB->getParent();
10578 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10579 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10581 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10582 const MachineOperand &MO = MI->getOperand(I);
10583 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10584 unsigned Reg = MO.getReg();
10585 if (Reg != X86::EFLAGS) continue;
10586 copy0MBB->addLiveIn(Reg);
10587 sinkMBB->addLiveIn(Reg);
10590 // Transfer the remainder of BB and its successor edges to sinkMBB.
10591 sinkMBB->splice(sinkMBB->begin(), BB,
10592 llvm::next(MachineBasicBlock::iterator(MI)),
10594 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10596 // Add the true and fallthrough blocks as its successors.
10597 BB->addSuccessor(copy0MBB);
10598 BB->addSuccessor(sinkMBB);
10600 // Create the conditional branch instruction.
10602 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10603 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10606 // %FalseValue = ...
10607 // # fallthrough to sinkMBB
10608 copy0MBB->addSuccessor(sinkMBB);
10611 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10613 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10614 TII->get(X86::PHI), MI->getOperand(0).getReg())
10615 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10616 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10618 MI->eraseFromParent(); // The pseudo instruction is gone now.
10622 MachineBasicBlock *
10623 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10624 MachineBasicBlock *BB) const {
10625 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10626 DebugLoc DL = MI->getDebugLoc();
10628 assert(!Subtarget->isTargetEnvMacho());
10630 // The lowering is pretty easy: we're just emitting the call to _alloca. The
10631 // non-trivial part is impdef of ESP.
10633 if (Subtarget->isTargetWin64()) {
10634 if (Subtarget->isTargetCygMing()) {
10635 // ___chkstk(Mingw64):
10636 // Clobbers R10, R11, RAX and EFLAGS.
10638 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10639 .addExternalSymbol("___chkstk")
10640 .addReg(X86::RAX, RegState::Implicit)
10641 .addReg(X86::RSP, RegState::Implicit)
10642 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10643 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10644 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10646 // __chkstk(MSVCRT): does not update stack pointer.
10647 // Clobbers R10, R11 and EFLAGS.
10648 // FIXME: RAX(allocated size) might be reused and not killed.
10649 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10650 .addExternalSymbol("__chkstk")
10651 .addReg(X86::RAX, RegState::Implicit)
10652 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10653 // RAX has the offset to subtracted from RSP.
10654 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10659 const char *StackProbeSymbol =
10660 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10662 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10663 .addExternalSymbol(StackProbeSymbol)
10664 .addReg(X86::EAX, RegState::Implicit)
10665 .addReg(X86::ESP, RegState::Implicit)
10666 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10667 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10668 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10671 MI->eraseFromParent(); // The pseudo instruction is gone now.
10675 MachineBasicBlock *
10676 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10677 MachineBasicBlock *BB) const {
10678 // This is pretty easy. We're taking the value that we received from
10679 // our load from the relocation, sticking it in either RDI (x86-64)
10680 // or EAX and doing an indirect call. The return value will then
10681 // be in the normal return register.
10682 const X86InstrInfo *TII
10683 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10684 DebugLoc DL = MI->getDebugLoc();
10685 MachineFunction *F = BB->getParent();
10687 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10688 assert(MI->getOperand(3).isGlobal() && "This should be a global");
10690 if (Subtarget->is64Bit()) {
10691 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10692 TII->get(X86::MOV64rm), X86::RDI)
10694 .addImm(0).addReg(0)
10695 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10696 MI->getOperand(3).getTargetFlags())
10698 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10699 addDirectMem(MIB, X86::RDI);
10700 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10701 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10702 TII->get(X86::MOV32rm), X86::EAX)
10704 .addImm(0).addReg(0)
10705 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10706 MI->getOperand(3).getTargetFlags())
10708 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10709 addDirectMem(MIB, X86::EAX);
10711 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10712 TII->get(X86::MOV32rm), X86::EAX)
10713 .addReg(TII->getGlobalBaseReg(F))
10714 .addImm(0).addReg(0)
10715 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10716 MI->getOperand(3).getTargetFlags())
10718 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10719 addDirectMem(MIB, X86::EAX);
10722 MI->eraseFromParent(); // The pseudo instruction is gone now.
10726 MachineBasicBlock *
10727 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10728 MachineBasicBlock *BB) const {
10729 switch (MI->getOpcode()) {
10730 default: assert(false && "Unexpected instr type to insert");
10731 case X86::TAILJMPd64:
10732 case X86::TAILJMPr64:
10733 case X86::TAILJMPm64:
10734 assert(!"TAILJMP64 would not be touched here.");
10735 case X86::TCRETURNdi64:
10736 case X86::TCRETURNri64:
10737 case X86::TCRETURNmi64:
10738 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10739 // On AMD64, additional defs should be added before register allocation.
10740 if (!Subtarget->isTargetWin64()) {
10741 MI->addRegisterDefined(X86::RSI);
10742 MI->addRegisterDefined(X86::RDI);
10743 MI->addRegisterDefined(X86::XMM6);
10744 MI->addRegisterDefined(X86::XMM7);
10745 MI->addRegisterDefined(X86::XMM8);
10746 MI->addRegisterDefined(X86::XMM9);
10747 MI->addRegisterDefined(X86::XMM10);
10748 MI->addRegisterDefined(X86::XMM11);
10749 MI->addRegisterDefined(X86::XMM12);
10750 MI->addRegisterDefined(X86::XMM13);
10751 MI->addRegisterDefined(X86::XMM14);
10752 MI->addRegisterDefined(X86::XMM15);
10755 case X86::WIN_ALLOCA:
10756 return EmitLoweredWinAlloca(MI, BB);
10757 case X86::TLSCall_32:
10758 case X86::TLSCall_64:
10759 return EmitLoweredTLSCall(MI, BB);
10760 case X86::CMOV_GR8:
10761 case X86::CMOV_FR32:
10762 case X86::CMOV_FR64:
10763 case X86::CMOV_V4F32:
10764 case X86::CMOV_V2F64:
10765 case X86::CMOV_V2I64:
10766 case X86::CMOV_GR16:
10767 case X86::CMOV_GR32:
10768 case X86::CMOV_RFP32:
10769 case X86::CMOV_RFP64:
10770 case X86::CMOV_RFP80:
10771 return EmitLoweredSelect(MI, BB);
10773 case X86::FP32_TO_INT16_IN_MEM:
10774 case X86::FP32_TO_INT32_IN_MEM:
10775 case X86::FP32_TO_INT64_IN_MEM:
10776 case X86::FP64_TO_INT16_IN_MEM:
10777 case X86::FP64_TO_INT32_IN_MEM:
10778 case X86::FP64_TO_INT64_IN_MEM:
10779 case X86::FP80_TO_INT16_IN_MEM:
10780 case X86::FP80_TO_INT32_IN_MEM:
10781 case X86::FP80_TO_INT64_IN_MEM: {
10782 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10783 DebugLoc DL = MI->getDebugLoc();
10785 // Change the floating point control register to use "round towards zero"
10786 // mode when truncating to an integer value.
10787 MachineFunction *F = BB->getParent();
10788 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10789 addFrameReference(BuildMI(*BB, MI, DL,
10790 TII->get(X86::FNSTCW16m)), CWFrameIdx);
10792 // Load the old value of the high byte of the control word...
10794 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10795 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10798 // Set the high part to be round to zero...
10799 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10802 // Reload the modified control word now...
10803 addFrameReference(BuildMI(*BB, MI, DL,
10804 TII->get(X86::FLDCW16m)), CWFrameIdx);
10806 // Restore the memory image of control word to original value
10807 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10810 // Get the X86 opcode to use.
10812 switch (MI->getOpcode()) {
10813 default: llvm_unreachable("illegal opcode!");
10814 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10815 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10816 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10817 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10818 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10819 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10820 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10821 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10822 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10826 MachineOperand &Op = MI->getOperand(0);
10828 AM.BaseType = X86AddressMode::RegBase;
10829 AM.Base.Reg = Op.getReg();
10831 AM.BaseType = X86AddressMode::FrameIndexBase;
10832 AM.Base.FrameIndex = Op.getIndex();
10834 Op = MI->getOperand(1);
10836 AM.Scale = Op.getImm();
10837 Op = MI->getOperand(2);
10839 AM.IndexReg = Op.getImm();
10840 Op = MI->getOperand(3);
10841 if (Op.isGlobal()) {
10842 AM.GV = Op.getGlobal();
10844 AM.Disp = Op.getImm();
10846 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10847 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10849 // Reload the original control word now.
10850 addFrameReference(BuildMI(*BB, MI, DL,
10851 TII->get(X86::FLDCW16m)), CWFrameIdx);
10853 MI->eraseFromParent(); // The pseudo instruction is gone now.
10856 // String/text processing lowering.
10857 case X86::PCMPISTRM128REG:
10858 case X86::VPCMPISTRM128REG:
10859 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10860 case X86::PCMPISTRM128MEM:
10861 case X86::VPCMPISTRM128MEM:
10862 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10863 case X86::PCMPESTRM128REG:
10864 case X86::VPCMPESTRM128REG:
10865 return EmitPCMP(MI, BB, 5, false /* in mem */);
10866 case X86::PCMPESTRM128MEM:
10867 case X86::VPCMPESTRM128MEM:
10868 return EmitPCMP(MI, BB, 5, true /* in mem */);
10870 // Thread synchronization.
10872 return EmitMonitor(MI, BB);
10874 return EmitMwait(MI, BB);
10876 // Atomic Lowering.
10877 case X86::ATOMAND32:
10878 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10879 X86::AND32ri, X86::MOV32rm,
10881 X86::NOT32r, X86::EAX,
10882 X86::GR32RegisterClass);
10883 case X86::ATOMOR32:
10884 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10885 X86::OR32ri, X86::MOV32rm,
10887 X86::NOT32r, X86::EAX,
10888 X86::GR32RegisterClass);
10889 case X86::ATOMXOR32:
10890 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10891 X86::XOR32ri, X86::MOV32rm,
10893 X86::NOT32r, X86::EAX,
10894 X86::GR32RegisterClass);
10895 case X86::ATOMNAND32:
10896 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10897 X86::AND32ri, X86::MOV32rm,
10899 X86::NOT32r, X86::EAX,
10900 X86::GR32RegisterClass, true);
10901 case X86::ATOMMIN32:
10902 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10903 case X86::ATOMMAX32:
10904 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10905 case X86::ATOMUMIN32:
10906 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10907 case X86::ATOMUMAX32:
10908 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10910 case X86::ATOMAND16:
10911 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10912 X86::AND16ri, X86::MOV16rm,
10914 X86::NOT16r, X86::AX,
10915 X86::GR16RegisterClass);
10916 case X86::ATOMOR16:
10917 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10918 X86::OR16ri, X86::MOV16rm,
10920 X86::NOT16r, X86::AX,
10921 X86::GR16RegisterClass);
10922 case X86::ATOMXOR16:
10923 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10924 X86::XOR16ri, X86::MOV16rm,
10926 X86::NOT16r, X86::AX,
10927 X86::GR16RegisterClass);
10928 case X86::ATOMNAND16:
10929 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10930 X86::AND16ri, X86::MOV16rm,
10932 X86::NOT16r, X86::AX,
10933 X86::GR16RegisterClass, true);
10934 case X86::ATOMMIN16:
10935 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10936 case X86::ATOMMAX16:
10937 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10938 case X86::ATOMUMIN16:
10939 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10940 case X86::ATOMUMAX16:
10941 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10943 case X86::ATOMAND8:
10944 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10945 X86::AND8ri, X86::MOV8rm,
10947 X86::NOT8r, X86::AL,
10948 X86::GR8RegisterClass);
10950 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10951 X86::OR8ri, X86::MOV8rm,
10953 X86::NOT8r, X86::AL,
10954 X86::GR8RegisterClass);
10955 case X86::ATOMXOR8:
10956 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10957 X86::XOR8ri, X86::MOV8rm,
10959 X86::NOT8r, X86::AL,
10960 X86::GR8RegisterClass);
10961 case X86::ATOMNAND8:
10962 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10963 X86::AND8ri, X86::MOV8rm,
10965 X86::NOT8r, X86::AL,
10966 X86::GR8RegisterClass, true);
10967 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10968 // This group is for 64-bit host.
10969 case X86::ATOMAND64:
10970 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10971 X86::AND64ri32, X86::MOV64rm,
10973 X86::NOT64r, X86::RAX,
10974 X86::GR64RegisterClass);
10975 case X86::ATOMOR64:
10976 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10977 X86::OR64ri32, X86::MOV64rm,
10979 X86::NOT64r, X86::RAX,
10980 X86::GR64RegisterClass);
10981 case X86::ATOMXOR64:
10982 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10983 X86::XOR64ri32, X86::MOV64rm,
10985 X86::NOT64r, X86::RAX,
10986 X86::GR64RegisterClass);
10987 case X86::ATOMNAND64:
10988 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10989 X86::AND64ri32, X86::MOV64rm,
10991 X86::NOT64r, X86::RAX,
10992 X86::GR64RegisterClass, true);
10993 case X86::ATOMMIN64:
10994 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10995 case X86::ATOMMAX64:
10996 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10997 case X86::ATOMUMIN64:
10998 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10999 case X86::ATOMUMAX64:
11000 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
11002 // This group does 64-bit operations on a 32-bit host.
11003 case X86::ATOMAND6432:
11004 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11005 X86::AND32rr, X86::AND32rr,
11006 X86::AND32ri, X86::AND32ri,
11008 case X86::ATOMOR6432:
11009 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11010 X86::OR32rr, X86::OR32rr,
11011 X86::OR32ri, X86::OR32ri,
11013 case X86::ATOMXOR6432:
11014 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11015 X86::XOR32rr, X86::XOR32rr,
11016 X86::XOR32ri, X86::XOR32ri,
11018 case X86::ATOMNAND6432:
11019 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11020 X86::AND32rr, X86::AND32rr,
11021 X86::AND32ri, X86::AND32ri,
11023 case X86::ATOMADD6432:
11024 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11025 X86::ADD32rr, X86::ADC32rr,
11026 X86::ADD32ri, X86::ADC32ri,
11028 case X86::ATOMSUB6432:
11029 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11030 X86::SUB32rr, X86::SBB32rr,
11031 X86::SUB32ri, X86::SBB32ri,
11033 case X86::ATOMSWAP6432:
11034 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11035 X86::MOV32rr, X86::MOV32rr,
11036 X86::MOV32ri, X86::MOV32ri,
11038 case X86::VASTART_SAVE_XMM_REGS:
11039 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
11041 case X86::VAARG_64:
11042 return EmitVAARG64WithCustomInserter(MI, BB);
11046 //===----------------------------------------------------------------------===//
11047 // X86 Optimization Hooks
11048 //===----------------------------------------------------------------------===//
11050 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
11054 const SelectionDAG &DAG,
11055 unsigned Depth) const {
11056 unsigned Opc = Op.getOpcode();
11057 assert((Opc >= ISD::BUILTIN_OP_END ||
11058 Opc == ISD::INTRINSIC_WO_CHAIN ||
11059 Opc == ISD::INTRINSIC_W_CHAIN ||
11060 Opc == ISD::INTRINSIC_VOID) &&
11061 "Should use MaskedValueIsZero if you don't know whether Op"
11062 " is a target node!");
11064 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
11078 // These nodes' second result is a boolean.
11079 if (Op.getResNo() == 0)
11082 case X86ISD::SETCC:
11083 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11084 Mask.getBitWidth() - 1);
11089 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11090 unsigned Depth) const {
11091 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11092 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11093 return Op.getValueType().getScalarType().getSizeInBits();
11099 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11100 /// node is a GlobalAddress + offset.
11101 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11102 const GlobalValue* &GA,
11103 int64_t &Offset) const {
11104 if (N->getOpcode() == X86ISD::Wrapper) {
11105 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11106 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11107 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11111 return TargetLowering::isGAPlusOffset(N, GA, Offset);
11114 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
11115 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
11116 /// if the load addresses are consecutive, non-overlapping, and in the right
11118 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11119 TargetLowering::DAGCombinerInfo &DCI) {
11120 DebugLoc dl = N->getDebugLoc();
11121 EVT VT = N->getValueType(0);
11123 if (VT.getSizeInBits() != 128)
11126 // Don't create instructions with illegal types after legalize types has run.
11127 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11128 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11131 SmallVector<SDValue, 16> Elts;
11132 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11133 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11135 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11138 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11139 /// generation and convert it from being a bunch of shuffles and extracts
11140 /// to a simple store and scalar loads to extract the elements.
11141 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11142 const TargetLowering &TLI) {
11143 SDValue InputVector = N->getOperand(0);
11145 // Only operate on vectors of 4 elements, where the alternative shuffling
11146 // gets to be more expensive.
11147 if (InputVector.getValueType() != MVT::v4i32)
11150 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11151 // single use which is a sign-extend or zero-extend, and all elements are
11153 SmallVector<SDNode *, 4> Uses;
11154 unsigned ExtractedElements = 0;
11155 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11156 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11157 if (UI.getUse().getResNo() != InputVector.getResNo())
11160 SDNode *Extract = *UI;
11161 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11164 if (Extract->getValueType(0) != MVT::i32)
11166 if (!Extract->hasOneUse())
11168 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11169 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11171 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11174 // Record which element was extracted.
11175 ExtractedElements |=
11176 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11178 Uses.push_back(Extract);
11181 // If not all the elements were used, this may not be worthwhile.
11182 if (ExtractedElements != 15)
11185 // Ok, we've now decided to do the transformation.
11186 DebugLoc dl = InputVector.getDebugLoc();
11188 // Store the value to a temporary stack slot.
11189 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11190 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11191 MachinePointerInfo(), false, false, 0);
11193 // Replace each use (extract) with a load of the appropriate element.
11194 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11195 UE = Uses.end(); UI != UE; ++UI) {
11196 SDNode *Extract = *UI;
11198 // cOMpute the element's address.
11199 SDValue Idx = Extract->getOperand(1);
11201 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11202 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11203 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11205 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11206 StackPtr, OffsetVal);
11208 // Load the scalar.
11209 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11210 ScalarAddr, MachinePointerInfo(),
11213 // Replace the exact with the load.
11214 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11217 // The replacement was made in place; don't return anything.
11221 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11222 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11223 const X86Subtarget *Subtarget) {
11224 DebugLoc DL = N->getDebugLoc();
11225 SDValue Cond = N->getOperand(0);
11226 // Get the LHS/RHS of the select.
11227 SDValue LHS = N->getOperand(1);
11228 SDValue RHS = N->getOperand(2);
11230 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11231 // instructions match the semantics of the common C idiom x<y?x:y but not
11232 // x<=y?x:y, because of how they handle negative zero (which can be
11233 // ignored in unsafe-math mode).
11234 if (Subtarget->hasSSE2() &&
11235 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11236 Cond.getOpcode() == ISD::SETCC) {
11237 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11239 unsigned Opcode = 0;
11240 // Check for x CC y ? x : y.
11241 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11242 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11246 // Converting this to a min would handle NaNs incorrectly, and swapping
11247 // the operands would cause it to handle comparisons between positive
11248 // and negative zero incorrectly.
11249 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11250 if (!UnsafeFPMath &&
11251 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11253 std::swap(LHS, RHS);
11255 Opcode = X86ISD::FMIN;
11258 // Converting this to a min would handle comparisons between positive
11259 // and negative zero incorrectly.
11260 if (!UnsafeFPMath &&
11261 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11263 Opcode = X86ISD::FMIN;
11266 // Converting this to a min would handle both negative zeros and NaNs
11267 // incorrectly, but we can swap the operands to fix both.
11268 std::swap(LHS, RHS);
11272 Opcode = X86ISD::FMIN;
11276 // Converting this to a max would handle comparisons between positive
11277 // and negative zero incorrectly.
11278 if (!UnsafeFPMath &&
11279 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11281 Opcode = X86ISD::FMAX;
11284 // Converting this to a max would handle NaNs incorrectly, and swapping
11285 // the operands would cause it to handle comparisons between positive
11286 // and negative zero incorrectly.
11287 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11288 if (!UnsafeFPMath &&
11289 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11291 std::swap(LHS, RHS);
11293 Opcode = X86ISD::FMAX;
11296 // Converting this to a max would handle both negative zeros and NaNs
11297 // incorrectly, but we can swap the operands to fix both.
11298 std::swap(LHS, RHS);
11302 Opcode = X86ISD::FMAX;
11305 // Check for x CC y ? y : x -- a min/max with reversed arms.
11306 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11307 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11311 // Converting this to a min would handle comparisons between positive
11312 // and negative zero incorrectly, and swapping the operands would
11313 // cause it to handle NaNs incorrectly.
11314 if (!UnsafeFPMath &&
11315 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11316 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11318 std::swap(LHS, RHS);
11320 Opcode = X86ISD::FMIN;
11323 // Converting this to a min would handle NaNs incorrectly.
11324 if (!UnsafeFPMath &&
11325 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11327 Opcode = X86ISD::FMIN;
11330 // Converting this to a min would handle both negative zeros and NaNs
11331 // incorrectly, but we can swap the operands to fix both.
11332 std::swap(LHS, RHS);
11336 Opcode = X86ISD::FMIN;
11340 // Converting this to a max would handle NaNs incorrectly.
11341 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11343 Opcode = X86ISD::FMAX;
11346 // Converting this to a max would handle comparisons between positive
11347 // and negative zero incorrectly, and swapping the operands would
11348 // cause it to handle NaNs incorrectly.
11349 if (!UnsafeFPMath &&
11350 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11351 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11353 std::swap(LHS, RHS);
11355 Opcode = X86ISD::FMAX;
11358 // Converting this to a max would handle both negative zeros and NaNs
11359 // incorrectly, but we can swap the operands to fix both.
11360 std::swap(LHS, RHS);
11364 Opcode = X86ISD::FMAX;
11370 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11373 // If this is a select between two integer constants, try to do some
11375 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11376 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11377 // Don't do this for crazy integer types.
11378 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11379 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11380 // so that TrueC (the true value) is larger than FalseC.
11381 bool NeedsCondInvert = false;
11383 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11384 // Efficiently invertible.
11385 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
11386 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
11387 isa<ConstantSDNode>(Cond.getOperand(1))))) {
11388 NeedsCondInvert = true;
11389 std::swap(TrueC, FalseC);
11392 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
11393 if (FalseC->getAPIntValue() == 0 &&
11394 TrueC->getAPIntValue().isPowerOf2()) {
11395 if (NeedsCondInvert) // Invert the condition if needed.
11396 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11397 DAG.getConstant(1, Cond.getValueType()));
11399 // Zero extend the condition if needed.
11400 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11402 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11403 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11404 DAG.getConstant(ShAmt, MVT::i8));
11407 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11408 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11409 if (NeedsCondInvert) // Invert the condition if needed.
11410 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11411 DAG.getConstant(1, Cond.getValueType()));
11413 // Zero extend the condition if needed.
11414 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11415 FalseC->getValueType(0), Cond);
11416 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11417 SDValue(FalseC, 0));
11420 // Optimize cases that will turn into an LEA instruction. This requires
11421 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11422 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11423 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11424 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11426 bool isFastMultiplier = false;
11428 switch ((unsigned char)Diff) {
11430 case 1: // result = add base, cond
11431 case 2: // result = lea base( , cond*2)
11432 case 3: // result = lea base(cond, cond*2)
11433 case 4: // result = lea base( , cond*4)
11434 case 5: // result = lea base(cond, cond*4)
11435 case 8: // result = lea base( , cond*8)
11436 case 9: // result = lea base(cond, cond*8)
11437 isFastMultiplier = true;
11442 if (isFastMultiplier) {
11443 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11444 if (NeedsCondInvert) // Invert the condition if needed.
11445 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11446 DAG.getConstant(1, Cond.getValueType()));
11448 // Zero extend the condition if needed.
11449 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11451 // Scale the condition by the difference.
11453 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11454 DAG.getConstant(Diff, Cond.getValueType()));
11456 // Add the base if non-zero.
11457 if (FalseC->getAPIntValue() != 0)
11458 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11459 SDValue(FalseC, 0));
11469 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11470 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11471 TargetLowering::DAGCombinerInfo &DCI) {
11472 DebugLoc DL = N->getDebugLoc();
11474 // If the flag operand isn't dead, don't touch this CMOV.
11475 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11478 SDValue FalseOp = N->getOperand(0);
11479 SDValue TrueOp = N->getOperand(1);
11480 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11481 SDValue Cond = N->getOperand(3);
11482 if (CC == X86::COND_E || CC == X86::COND_NE) {
11483 switch (Cond.getOpcode()) {
11487 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11488 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11489 return (CC == X86::COND_E) ? FalseOp : TrueOp;
11493 // If this is a select between two integer constants, try to do some
11494 // optimizations. Note that the operands are ordered the opposite of SELECT
11496 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11497 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11498 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11499 // larger than FalseC (the false value).
11500 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11501 CC = X86::GetOppositeBranchCondition(CC);
11502 std::swap(TrueC, FalseC);
11505 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
11506 // This is efficient for any integer data type (including i8/i16) and
11508 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11509 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11510 DAG.getConstant(CC, MVT::i8), Cond);
11512 // Zero extend the condition if needed.
11513 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11515 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11516 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11517 DAG.getConstant(ShAmt, MVT::i8));
11518 if (N->getNumValues() == 2) // Dead flag value?
11519 return DCI.CombineTo(N, Cond, SDValue());
11523 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
11524 // for any integer data type, including i8/i16.
11525 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11526 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11527 DAG.getConstant(CC, MVT::i8), Cond);
11529 // Zero extend the condition if needed.
11530 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11531 FalseC->getValueType(0), Cond);
11532 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11533 SDValue(FalseC, 0));
11535 if (N->getNumValues() == 2) // Dead flag value?
11536 return DCI.CombineTo(N, Cond, SDValue());
11540 // Optimize cases that will turn into an LEA instruction. This requires
11541 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11542 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11543 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11544 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11546 bool isFastMultiplier = false;
11548 switch ((unsigned char)Diff) {
11550 case 1: // result = add base, cond
11551 case 2: // result = lea base( , cond*2)
11552 case 3: // result = lea base(cond, cond*2)
11553 case 4: // result = lea base( , cond*4)
11554 case 5: // result = lea base(cond, cond*4)
11555 case 8: // result = lea base( , cond*8)
11556 case 9: // result = lea base(cond, cond*8)
11557 isFastMultiplier = true;
11562 if (isFastMultiplier) {
11563 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11564 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11565 DAG.getConstant(CC, MVT::i8), Cond);
11566 // Zero extend the condition if needed.
11567 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11569 // Scale the condition by the difference.
11571 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11572 DAG.getConstant(Diff, Cond.getValueType()));
11574 // Add the base if non-zero.
11575 if (FalseC->getAPIntValue() != 0)
11576 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11577 SDValue(FalseC, 0));
11578 if (N->getNumValues() == 2) // Dead flag value?
11579 return DCI.CombineTo(N, Cond, SDValue());
11589 /// PerformMulCombine - Optimize a single multiply with constant into two
11590 /// in order to implement it with two cheaper instructions, e.g.
11591 /// LEA + SHL, LEA + LEA.
11592 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11593 TargetLowering::DAGCombinerInfo &DCI) {
11594 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11597 EVT VT = N->getValueType(0);
11598 if (VT != MVT::i64)
11601 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11604 uint64_t MulAmt = C->getZExtValue();
11605 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11608 uint64_t MulAmt1 = 0;
11609 uint64_t MulAmt2 = 0;
11610 if ((MulAmt % 9) == 0) {
11612 MulAmt2 = MulAmt / 9;
11613 } else if ((MulAmt % 5) == 0) {
11615 MulAmt2 = MulAmt / 5;
11616 } else if ((MulAmt % 3) == 0) {
11618 MulAmt2 = MulAmt / 3;
11621 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11622 DebugLoc DL = N->getDebugLoc();
11624 if (isPowerOf2_64(MulAmt2) &&
11625 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11626 // If second multiplifer is pow2, issue it first. We want the multiply by
11627 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11629 std::swap(MulAmt1, MulAmt2);
11632 if (isPowerOf2_64(MulAmt1))
11633 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11634 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11636 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11637 DAG.getConstant(MulAmt1, VT));
11639 if (isPowerOf2_64(MulAmt2))
11640 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11641 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11643 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11644 DAG.getConstant(MulAmt2, VT));
11646 // Do not add new nodes to DAG combiner worklist.
11647 DCI.CombineTo(N, NewMul, false);
11652 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11653 SDValue N0 = N->getOperand(0);
11654 SDValue N1 = N->getOperand(1);
11655 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11656 EVT VT = N0.getValueType();
11658 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11659 // since the result of setcc_c is all zero's or all ones.
11660 if (N1C && N0.getOpcode() == ISD::AND &&
11661 N0.getOperand(1).getOpcode() == ISD::Constant) {
11662 SDValue N00 = N0.getOperand(0);
11663 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11664 ((N00.getOpcode() == ISD::ANY_EXTEND ||
11665 N00.getOpcode() == ISD::ZERO_EXTEND) &&
11666 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11667 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11668 APInt ShAmt = N1C->getAPIntValue();
11669 Mask = Mask.shl(ShAmt);
11671 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11672 N00, DAG.getConstant(Mask, VT));
11679 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11681 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11682 const X86Subtarget *Subtarget) {
11683 EVT VT = N->getValueType(0);
11684 if (!VT.isVector() && VT.isInteger() &&
11685 N->getOpcode() == ISD::SHL)
11686 return PerformSHLCombine(N, DAG);
11688 // On X86 with SSE2 support, we can transform this to a vector shift if
11689 // all elements are shifted by the same amount. We can't do this in legalize
11690 // because the a constant vector is typically transformed to a constant pool
11691 // so we have no knowledge of the shift amount.
11692 if (!Subtarget->hasSSE2())
11695 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11698 SDValue ShAmtOp = N->getOperand(1);
11699 EVT EltVT = VT.getVectorElementType();
11700 DebugLoc DL = N->getDebugLoc();
11701 SDValue BaseShAmt = SDValue();
11702 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11703 unsigned NumElts = VT.getVectorNumElements();
11705 for (; i != NumElts; ++i) {
11706 SDValue Arg = ShAmtOp.getOperand(i);
11707 if (Arg.getOpcode() == ISD::UNDEF) continue;
11711 for (; i != NumElts; ++i) {
11712 SDValue Arg = ShAmtOp.getOperand(i);
11713 if (Arg.getOpcode() == ISD::UNDEF) continue;
11714 if (Arg != BaseShAmt) {
11718 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11719 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11720 SDValue InVec = ShAmtOp.getOperand(0);
11721 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11722 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11724 for (; i != NumElts; ++i) {
11725 SDValue Arg = InVec.getOperand(i);
11726 if (Arg.getOpcode() == ISD::UNDEF) continue;
11730 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11731 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11732 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11733 if (C->getZExtValue() == SplatIdx)
11734 BaseShAmt = InVec.getOperand(1);
11737 if (BaseShAmt.getNode() == 0)
11738 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11739 DAG.getIntPtrConstant(0));
11743 // The shift amount is an i32.
11744 if (EltVT.bitsGT(MVT::i32))
11745 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11746 else if (EltVT.bitsLT(MVT::i32))
11747 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11749 // The shift amount is identical so we can do a vector shift.
11750 SDValue ValOp = N->getOperand(0);
11751 switch (N->getOpcode()) {
11753 llvm_unreachable("Unknown shift opcode!");
11756 if (VT == MVT::v2i64)
11757 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11758 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11760 if (VT == MVT::v4i32)
11761 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11762 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11764 if (VT == MVT::v8i16)
11765 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11766 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11770 if (VT == MVT::v4i32)
11771 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11772 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11774 if (VT == MVT::v8i16)
11775 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11776 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11780 if (VT == MVT::v2i64)
11781 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11782 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11784 if (VT == MVT::v4i32)
11785 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11786 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11788 if (VT == MVT::v8i16)
11789 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11790 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11798 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
11799 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
11800 // and friends. Likewise for OR -> CMPNEQSS.
11801 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
11802 TargetLowering::DAGCombinerInfo &DCI,
11803 const X86Subtarget *Subtarget) {
11806 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
11807 // we're requiring SSE2 for both.
11808 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
11809 SDValue N0 = N->getOperand(0);
11810 SDValue N1 = N->getOperand(1);
11811 SDValue CMP0 = N0->getOperand(1);
11812 SDValue CMP1 = N1->getOperand(1);
11813 DebugLoc DL = N->getDebugLoc();
11815 // The SETCCs should both refer to the same CMP.
11816 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
11819 SDValue CMP00 = CMP0->getOperand(0);
11820 SDValue CMP01 = CMP0->getOperand(1);
11821 EVT VT = CMP00.getValueType();
11823 if (VT == MVT::f32 || VT == MVT::f64) {
11824 bool ExpectingFlags = false;
11825 // Check for any users that want flags:
11826 for (SDNode::use_iterator UI = N->use_begin(),
11828 !ExpectingFlags && UI != UE; ++UI)
11829 switch (UI->getOpcode()) {
11834 ExpectingFlags = true;
11836 case ISD::CopyToReg:
11837 case ISD::SIGN_EXTEND:
11838 case ISD::ZERO_EXTEND:
11839 case ISD::ANY_EXTEND:
11843 if (!ExpectingFlags) {
11844 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
11845 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
11847 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
11848 X86::CondCode tmp = cc0;
11853 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
11854 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
11855 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
11856 X86ISD::NodeType NTOperator = is64BitFP ?
11857 X86ISD::FSETCCsd : X86ISD::FSETCCss;
11858 // FIXME: need symbolic constants for these magic numbers.
11859 // See X86ATTInstPrinter.cpp:printSSECC().
11860 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
11861 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
11862 DAG.getConstant(x86cc, MVT::i8));
11863 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
11865 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
11866 DAG.getConstant(1, MVT::i32));
11867 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
11868 return OneBitOfTruth;
11876 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11877 TargetLowering::DAGCombinerInfo &DCI,
11878 const X86Subtarget *Subtarget) {
11879 if (DCI.isBeforeLegalizeOps())
11882 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11886 // Want to form ANDNP nodes:
11887 // 1) In the hopes of then easily combining them with OR and AND nodes
11888 // to form PBLEND/PSIGN.
11889 // 2) To match ANDN packed intrinsics
11890 EVT VT = N->getValueType(0);
11891 if (VT != MVT::v2i64 && VT != MVT::v4i64)
11894 SDValue N0 = N->getOperand(0);
11895 SDValue N1 = N->getOperand(1);
11896 DebugLoc DL = N->getDebugLoc();
11898 // Check LHS for vnot
11899 if (N0.getOpcode() == ISD::XOR &&
11900 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11901 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
11903 // Check RHS for vnot
11904 if (N1.getOpcode() == ISD::XOR &&
11905 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11906 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
11911 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11912 TargetLowering::DAGCombinerInfo &DCI,
11913 const X86Subtarget *Subtarget) {
11914 if (DCI.isBeforeLegalizeOps())
11917 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11921 EVT VT = N->getValueType(0);
11922 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11925 SDValue N0 = N->getOperand(0);
11926 SDValue N1 = N->getOperand(1);
11928 // look for psign/blend
11929 if (Subtarget->hasSSSE3()) {
11930 if (VT == MVT::v2i64) {
11931 // Canonicalize pandn to RHS
11932 if (N0.getOpcode() == X86ISD::ANDNP)
11934 // or (and (m, x), (pandn m, y))
11935 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
11936 SDValue Mask = N1.getOperand(0);
11937 SDValue X = N1.getOperand(1);
11939 if (N0.getOperand(0) == Mask)
11940 Y = N0.getOperand(1);
11941 if (N0.getOperand(1) == Mask)
11942 Y = N0.getOperand(0);
11944 // Check to see if the mask appeared in both the AND and ANDNP and
11948 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11949 if (Mask.getOpcode() != ISD::BITCAST ||
11950 X.getOpcode() != ISD::BITCAST ||
11951 Y.getOpcode() != ISD::BITCAST)
11954 // Look through mask bitcast.
11955 Mask = Mask.getOperand(0);
11956 EVT MaskVT = Mask.getValueType();
11958 // Validate that the Mask operand is a vector sra node. The sra node
11959 // will be an intrinsic.
11960 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11963 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11964 // there is no psrai.b
11965 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11966 case Intrinsic::x86_sse2_psrai_w:
11967 case Intrinsic::x86_sse2_psrai_d:
11969 default: return SDValue();
11972 // Check that the SRA is all signbits.
11973 SDValue SraC = Mask.getOperand(2);
11974 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
11975 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11976 if ((SraAmt + 1) != EltBits)
11979 DebugLoc DL = N->getDebugLoc();
11981 // Now we know we at least have a plendvb with the mask val. See if
11982 // we can form a psignb/w/d.
11983 // psign = x.type == y.type == mask.type && y = sub(0, x);
11984 X = X.getOperand(0);
11985 Y = Y.getOperand(0);
11986 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11987 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11988 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11991 case 8: Opc = X86ISD::PSIGNB; break;
11992 case 16: Opc = X86ISD::PSIGNW; break;
11993 case 32: Opc = X86ISD::PSIGND; break;
11997 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11998 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
12001 // PBLENDVB only available on SSE 4.1
12002 if (!Subtarget->hasSSE41())
12005 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
12006 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
12007 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
12008 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
12009 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
12014 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
12015 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
12017 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
12019 if (!N0.hasOneUse() || !N1.hasOneUse())
12022 SDValue ShAmt0 = N0.getOperand(1);
12023 if (ShAmt0.getValueType() != MVT::i8)
12025 SDValue ShAmt1 = N1.getOperand(1);
12026 if (ShAmt1.getValueType() != MVT::i8)
12028 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
12029 ShAmt0 = ShAmt0.getOperand(0);
12030 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
12031 ShAmt1 = ShAmt1.getOperand(0);
12033 DebugLoc DL = N->getDebugLoc();
12034 unsigned Opc = X86ISD::SHLD;
12035 SDValue Op0 = N0.getOperand(0);
12036 SDValue Op1 = N1.getOperand(0);
12037 if (ShAmt0.getOpcode() == ISD::SUB) {
12038 Opc = X86ISD::SHRD;
12039 std::swap(Op0, Op1);
12040 std::swap(ShAmt0, ShAmt1);
12043 unsigned Bits = VT.getSizeInBits();
12044 if (ShAmt1.getOpcode() == ISD::SUB) {
12045 SDValue Sum = ShAmt1.getOperand(0);
12046 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
12047 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
12048 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
12049 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
12050 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
12051 return DAG.getNode(Opc, DL, VT,
12053 DAG.getNode(ISD::TRUNCATE, DL,
12056 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
12057 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
12059 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
12060 return DAG.getNode(Opc, DL, VT,
12061 N0.getOperand(0), N1.getOperand(0),
12062 DAG.getNode(ISD::TRUNCATE, DL,
12069 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
12070 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
12071 const X86Subtarget *Subtarget) {
12072 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
12073 // the FP state in cases where an emms may be missing.
12074 // A preferable solution to the general problem is to figure out the right
12075 // places to insert EMMS. This qualifies as a quick hack.
12077 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
12078 StoreSDNode *St = cast<StoreSDNode>(N);
12079 EVT VT = St->getValue().getValueType();
12080 if (VT.getSizeInBits() != 64)
12083 const Function *F = DAG.getMachineFunction().getFunction();
12084 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
12085 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
12086 && Subtarget->hasSSE2();
12087 if ((VT.isVector() ||
12088 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
12089 isa<LoadSDNode>(St->getValue()) &&
12090 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
12091 St->getChain().hasOneUse() && !St->isVolatile()) {
12092 SDNode* LdVal = St->getValue().getNode();
12093 LoadSDNode *Ld = 0;
12094 int TokenFactorIndex = -1;
12095 SmallVector<SDValue, 8> Ops;
12096 SDNode* ChainVal = St->getChain().getNode();
12097 // Must be a store of a load. We currently handle two cases: the load
12098 // is a direct child, and it's under an intervening TokenFactor. It is
12099 // possible to dig deeper under nested TokenFactors.
12100 if (ChainVal == LdVal)
12101 Ld = cast<LoadSDNode>(St->getChain());
12102 else if (St->getValue().hasOneUse() &&
12103 ChainVal->getOpcode() == ISD::TokenFactor) {
12104 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
12105 if (ChainVal->getOperand(i).getNode() == LdVal) {
12106 TokenFactorIndex = i;
12107 Ld = cast<LoadSDNode>(St->getValue());
12109 Ops.push_back(ChainVal->getOperand(i));
12113 if (!Ld || !ISD::isNormalLoad(Ld))
12116 // If this is not the MMX case, i.e. we are just turning i64 load/store
12117 // into f64 load/store, avoid the transformation if there are multiple
12118 // uses of the loaded value.
12119 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
12122 DebugLoc LdDL = Ld->getDebugLoc();
12123 DebugLoc StDL = N->getDebugLoc();
12124 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
12125 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
12127 if (Subtarget->is64Bit() || F64IsLegal) {
12128 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
12129 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
12130 Ld->getPointerInfo(), Ld->isVolatile(),
12131 Ld->isNonTemporal(), Ld->getAlignment());
12132 SDValue NewChain = NewLd.getValue(1);
12133 if (TokenFactorIndex != -1) {
12134 Ops.push_back(NewChain);
12135 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12138 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
12139 St->getPointerInfo(),
12140 St->isVolatile(), St->isNonTemporal(),
12141 St->getAlignment());
12144 // Otherwise, lower to two pairs of 32-bit loads / stores.
12145 SDValue LoAddr = Ld->getBasePtr();
12146 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
12147 DAG.getConstant(4, MVT::i32));
12149 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
12150 Ld->getPointerInfo(),
12151 Ld->isVolatile(), Ld->isNonTemporal(),
12152 Ld->getAlignment());
12153 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
12154 Ld->getPointerInfo().getWithOffset(4),
12155 Ld->isVolatile(), Ld->isNonTemporal(),
12156 MinAlign(Ld->getAlignment(), 4));
12158 SDValue NewChain = LoLd.getValue(1);
12159 if (TokenFactorIndex != -1) {
12160 Ops.push_back(LoLd);
12161 Ops.push_back(HiLd);
12162 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12166 LoAddr = St->getBasePtr();
12167 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
12168 DAG.getConstant(4, MVT::i32));
12170 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
12171 St->getPointerInfo(),
12172 St->isVolatile(), St->isNonTemporal(),
12173 St->getAlignment());
12174 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12175 St->getPointerInfo().getWithOffset(4),
12177 St->isNonTemporal(),
12178 MinAlign(St->getAlignment(), 4));
12179 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12184 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12185 /// X86ISD::FXOR nodes.
12186 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12187 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12188 // F[X]OR(0.0, x) -> x
12189 // F[X]OR(x, 0.0) -> x
12190 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12191 if (C->getValueAPF().isPosZero())
12192 return N->getOperand(1);
12193 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12194 if (C->getValueAPF().isPosZero())
12195 return N->getOperand(0);
12199 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12200 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12201 // FAND(0.0, x) -> 0.0
12202 // FAND(x, 0.0) -> 0.0
12203 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12204 if (C->getValueAPF().isPosZero())
12205 return N->getOperand(0);
12206 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12207 if (C->getValueAPF().isPosZero())
12208 return N->getOperand(1);
12212 static SDValue PerformBTCombine(SDNode *N,
12214 TargetLowering::DAGCombinerInfo &DCI) {
12215 // BT ignores high bits in the bit index operand.
12216 SDValue Op1 = N->getOperand(1);
12217 if (Op1.hasOneUse()) {
12218 unsigned BitWidth = Op1.getValueSizeInBits();
12219 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12220 APInt KnownZero, KnownOne;
12221 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12222 !DCI.isBeforeLegalizeOps());
12223 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12224 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12225 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12226 DCI.CommitTargetLoweringOpt(TLO);
12231 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12232 SDValue Op = N->getOperand(0);
12233 if (Op.getOpcode() == ISD::BITCAST)
12234 Op = Op.getOperand(0);
12235 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12236 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12237 VT.getVectorElementType().getSizeInBits() ==
12238 OpVT.getVectorElementType().getSizeInBits()) {
12239 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12244 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12245 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
12246 // (and (i32 x86isd::setcc_carry), 1)
12247 // This eliminates the zext. This transformation is necessary because
12248 // ISD::SETCC is always legalized to i8.
12249 DebugLoc dl = N->getDebugLoc();
12250 SDValue N0 = N->getOperand(0);
12251 EVT VT = N->getValueType(0);
12252 if (N0.getOpcode() == ISD::AND &&
12254 N0.getOperand(0).hasOneUse()) {
12255 SDValue N00 = N0.getOperand(0);
12256 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12258 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12259 if (!C || C->getZExtValue() != 1)
12261 return DAG.getNode(ISD::AND, dl, VT,
12262 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12263 N00.getOperand(0), N00.getOperand(1)),
12264 DAG.getConstant(1, VT));
12270 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12271 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12272 unsigned X86CC = N->getConstantOperandVal(0);
12273 SDValue EFLAG = N->getOperand(1);
12274 DebugLoc DL = N->getDebugLoc();
12276 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12277 // a zext and produces an all-ones bit which is more useful than 0/1 in some
12279 if (X86CC == X86::COND_B)
12280 return DAG.getNode(ISD::AND, DL, MVT::i8,
12281 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12282 DAG.getConstant(X86CC, MVT::i8), EFLAG),
12283 DAG.getConstant(1, MVT::i8));
12288 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
12289 const X86TargetLowering *XTLI) {
12290 SDValue Op0 = N->getOperand(0);
12291 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
12292 // a 32-bit target where SSE doesn't support i64->FP operations.
12293 if (Op0.getOpcode() == ISD::LOAD) {
12294 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
12295 EVT VT = Ld->getValueType(0);
12296 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
12297 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
12298 !XTLI->getSubtarget()->is64Bit() &&
12299 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12300 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
12301 Ld->getChain(), Op0, DAG);
12302 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
12309 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12310 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12311 X86TargetLowering::DAGCombinerInfo &DCI) {
12312 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12313 // the result is either zero or one (depending on the input carry bit).
12314 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12315 if (X86::isZeroNode(N->getOperand(0)) &&
12316 X86::isZeroNode(N->getOperand(1)) &&
12317 // We don't have a good way to replace an EFLAGS use, so only do this when
12319 SDValue(N, 1).use_empty()) {
12320 DebugLoc DL = N->getDebugLoc();
12321 EVT VT = N->getValueType(0);
12322 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12323 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12324 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12325 DAG.getConstant(X86::COND_B,MVT::i8),
12327 DAG.getConstant(1, VT));
12328 return DCI.CombineTo(N, Res1, CarryOut);
12334 // fold (add Y, (sete X, 0)) -> adc 0, Y
12335 // (add Y, (setne X, 0)) -> sbb -1, Y
12336 // (sub (sete X, 0), Y) -> sbb 0, Y
12337 // (sub (setne X, 0), Y) -> adc -1, Y
12338 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12339 DebugLoc DL = N->getDebugLoc();
12341 // Look through ZExts.
12342 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12343 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12346 SDValue SetCC = Ext.getOperand(0);
12347 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12350 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12351 if (CC != X86::COND_E && CC != X86::COND_NE)
12354 SDValue Cmp = SetCC.getOperand(1);
12355 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12356 !X86::isZeroNode(Cmp.getOperand(1)) ||
12357 !Cmp.getOperand(0).getValueType().isInteger())
12360 SDValue CmpOp0 = Cmp.getOperand(0);
12361 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12362 DAG.getConstant(1, CmpOp0.getValueType()));
12364 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12365 if (CC == X86::COND_NE)
12366 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12367 DL, OtherVal.getValueType(), OtherVal,
12368 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12369 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12370 DL, OtherVal.getValueType(), OtherVal,
12371 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12374 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12375 DAGCombinerInfo &DCI) const {
12376 SelectionDAG &DAG = DCI.DAG;
12377 switch (N->getOpcode()) {
12379 case ISD::EXTRACT_VECTOR_ELT:
12380 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12381 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
12382 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
12384 case ISD::SUB: return OptimizeConditonalInDecrement(N, DAG);
12385 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
12386 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
12389 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
12390 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
12391 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
12392 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
12393 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
12395 case X86ISD::FOR: return PerformFORCombine(N, DAG);
12396 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
12397 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
12398 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
12399 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
12400 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
12401 case X86ISD::SHUFPS: // Handle all target specific shuffles
12402 case X86ISD::SHUFPD:
12403 case X86ISD::PALIGN:
12404 case X86ISD::PUNPCKHBW:
12405 case X86ISD::PUNPCKHWD:
12406 case X86ISD::PUNPCKHDQ:
12407 case X86ISD::PUNPCKHQDQ:
12408 case X86ISD::UNPCKHPS:
12409 case X86ISD::UNPCKHPD:
12410 case X86ISD::PUNPCKLBW:
12411 case X86ISD::PUNPCKLWD:
12412 case X86ISD::PUNPCKLDQ:
12413 case X86ISD::PUNPCKLQDQ:
12414 case X86ISD::UNPCKLPS:
12415 case X86ISD::UNPCKLPD:
12416 case X86ISD::VUNPCKLPS:
12417 case X86ISD::VUNPCKLPD:
12418 case X86ISD::VUNPCKLPSY:
12419 case X86ISD::VUNPCKLPDY:
12420 case X86ISD::MOVHLPS:
12421 case X86ISD::MOVLHPS:
12422 case X86ISD::PSHUFD:
12423 case X86ISD::PSHUFHW:
12424 case X86ISD::PSHUFLW:
12425 case X86ISD::MOVSS:
12426 case X86ISD::MOVSD:
12427 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12433 /// isTypeDesirableForOp - Return true if the target has native support for
12434 /// the specified value type and it is 'desirable' to use the type for the
12435 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12436 /// instruction encodings are longer and some i16 instructions are slow.
12437 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12438 if (!isTypeLegal(VT))
12440 if (VT != MVT::i16)
12447 case ISD::SIGN_EXTEND:
12448 case ISD::ZERO_EXTEND:
12449 case ISD::ANY_EXTEND:
12462 /// IsDesirableToPromoteOp - This method query the target whether it is
12463 /// beneficial for dag combiner to promote the specified node. If true, it
12464 /// should return the desired promotion type by reference.
12465 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12466 EVT VT = Op.getValueType();
12467 if (VT != MVT::i16)
12470 bool Promote = false;
12471 bool Commute = false;
12472 switch (Op.getOpcode()) {
12475 LoadSDNode *LD = cast<LoadSDNode>(Op);
12476 // If the non-extending load has a single use and it's not live out, then it
12477 // might be folded.
12478 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12479 Op.hasOneUse()*/) {
12480 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12481 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12482 // The only case where we'd want to promote LOAD (rather then it being
12483 // promoted as an operand is when it's only use is liveout.
12484 if (UI->getOpcode() != ISD::CopyToReg)
12491 case ISD::SIGN_EXTEND:
12492 case ISD::ZERO_EXTEND:
12493 case ISD::ANY_EXTEND:
12498 SDValue N0 = Op.getOperand(0);
12499 // Look out for (store (shl (load), x)).
12500 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12513 SDValue N0 = Op.getOperand(0);
12514 SDValue N1 = Op.getOperand(1);
12515 if (!Commute && MayFoldLoad(N1))
12517 // Avoid disabling potential load folding opportunities.
12518 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12520 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12530 //===----------------------------------------------------------------------===//
12531 // X86 Inline Assembly Support
12532 //===----------------------------------------------------------------------===//
12534 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12535 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12537 std::string AsmStr = IA->getAsmString();
12539 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12540 SmallVector<StringRef, 4> AsmPieces;
12541 SplitString(AsmStr, AsmPieces, ";\n");
12543 switch (AsmPieces.size()) {
12544 default: return false;
12546 AsmStr = AsmPieces[0];
12548 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
12550 // FIXME: this should verify that we are targeting a 486 or better. If not,
12551 // we will turn this bswap into something that will be lowered to logical ops
12552 // instead of emitting the bswap asm. For now, we don't support 486 or lower
12553 // so don't worry about this.
12555 if (AsmPieces.size() == 2 &&
12556 (AsmPieces[0] == "bswap" ||
12557 AsmPieces[0] == "bswapq" ||
12558 AsmPieces[0] == "bswapl") &&
12559 (AsmPieces[1] == "$0" ||
12560 AsmPieces[1] == "${0:q}")) {
12561 // No need to check constraints, nothing other than the equivalent of
12562 // "=r,0" would be valid here.
12563 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12564 if (!Ty || Ty->getBitWidth() % 16 != 0)
12566 return IntrinsicLowering::LowerToByteSwap(CI);
12568 // rorw $$8, ${0:w} --> llvm.bswap.i16
12569 if (CI->getType()->isIntegerTy(16) &&
12570 AsmPieces.size() == 3 &&
12571 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12572 AsmPieces[1] == "$$8," &&
12573 AsmPieces[2] == "${0:w}" &&
12574 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12576 const std::string &ConstraintsStr = IA->getConstraintString();
12577 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12578 std::sort(AsmPieces.begin(), AsmPieces.end());
12579 if (AsmPieces.size() == 4 &&
12580 AsmPieces[0] == "~{cc}" &&
12581 AsmPieces[1] == "~{dirflag}" &&
12582 AsmPieces[2] == "~{flags}" &&
12583 AsmPieces[3] == "~{fpsr}") {
12584 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12585 if (!Ty || Ty->getBitWidth() % 16 != 0)
12587 return IntrinsicLowering::LowerToByteSwap(CI);
12592 if (CI->getType()->isIntegerTy(32) &&
12593 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12594 SmallVector<StringRef, 4> Words;
12595 SplitString(AsmPieces[0], Words, " \t,");
12596 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12597 Words[2] == "${0:w}") {
12599 SplitString(AsmPieces[1], Words, " \t,");
12600 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12601 Words[2] == "$0") {
12603 SplitString(AsmPieces[2], Words, " \t,");
12604 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12605 Words[2] == "${0:w}") {
12607 const std::string &ConstraintsStr = IA->getConstraintString();
12608 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12609 std::sort(AsmPieces.begin(), AsmPieces.end());
12610 if (AsmPieces.size() == 4 &&
12611 AsmPieces[0] == "~{cc}" &&
12612 AsmPieces[1] == "~{dirflag}" &&
12613 AsmPieces[2] == "~{flags}" &&
12614 AsmPieces[3] == "~{fpsr}") {
12615 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12616 if (!Ty || Ty->getBitWidth() % 16 != 0)
12618 return IntrinsicLowering::LowerToByteSwap(CI);
12625 if (CI->getType()->isIntegerTy(64)) {
12626 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12627 if (Constraints.size() >= 2 &&
12628 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12629 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12630 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
12631 SmallVector<StringRef, 4> Words;
12632 SplitString(AsmPieces[0], Words, " \t");
12633 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12635 SplitString(AsmPieces[1], Words, " \t");
12636 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12638 SplitString(AsmPieces[2], Words, " \t,");
12639 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12640 Words[2] == "%edx") {
12641 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12642 if (!Ty || Ty->getBitWidth() % 16 != 0)
12644 return IntrinsicLowering::LowerToByteSwap(CI);
12657 /// getConstraintType - Given a constraint letter, return the type of
12658 /// constraint it is for this target.
12659 X86TargetLowering::ConstraintType
12660 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12661 if (Constraint.size() == 1) {
12662 switch (Constraint[0]) {
12673 return C_RegisterClass;
12697 return TargetLowering::getConstraintType(Constraint);
12700 /// Examine constraint type and operand type and determine a weight value.
12701 /// This object must already have been set up with the operand type
12702 /// and the current alternative constraint selected.
12703 TargetLowering::ConstraintWeight
12704 X86TargetLowering::getSingleConstraintMatchWeight(
12705 AsmOperandInfo &info, const char *constraint) const {
12706 ConstraintWeight weight = CW_Invalid;
12707 Value *CallOperandVal = info.CallOperandVal;
12708 // If we don't have a value, we can't do a match,
12709 // but allow it at the lowest weight.
12710 if (CallOperandVal == NULL)
12712 const Type *type = CallOperandVal->getType();
12713 // Look at the constraint type.
12714 switch (*constraint) {
12716 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12727 if (CallOperandVal->getType()->isIntegerTy())
12728 weight = CW_SpecificReg;
12733 if (type->isFloatingPointTy())
12734 weight = CW_SpecificReg;
12737 if (type->isX86_MMXTy() && Subtarget->hasMMX())
12738 weight = CW_SpecificReg;
12742 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12743 weight = CW_Register;
12746 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12747 if (C->getZExtValue() <= 31)
12748 weight = CW_Constant;
12752 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12753 if (C->getZExtValue() <= 63)
12754 weight = CW_Constant;
12758 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12759 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12760 weight = CW_Constant;
12764 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12765 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12766 weight = CW_Constant;
12770 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12771 if (C->getZExtValue() <= 3)
12772 weight = CW_Constant;
12776 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12777 if (C->getZExtValue() <= 0xff)
12778 weight = CW_Constant;
12783 if (dyn_cast<ConstantFP>(CallOperandVal)) {
12784 weight = CW_Constant;
12788 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12789 if ((C->getSExtValue() >= -0x80000000LL) &&
12790 (C->getSExtValue() <= 0x7fffffffLL))
12791 weight = CW_Constant;
12795 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12796 if (C->getZExtValue() <= 0xffffffff)
12797 weight = CW_Constant;
12804 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12805 /// with another that has more specific requirements based on the type of the
12806 /// corresponding operand.
12807 const char *X86TargetLowering::
12808 LowerXConstraint(EVT ConstraintVT) const {
12809 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12810 // 'f' like normal targets.
12811 if (ConstraintVT.isFloatingPoint()) {
12812 if (Subtarget->hasXMMInt())
12814 if (Subtarget->hasXMM())
12818 return TargetLowering::LowerXConstraint(ConstraintVT);
12821 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12822 /// vector. If it is invalid, don't add anything to Ops.
12823 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12824 std::string &Constraint,
12825 std::vector<SDValue>&Ops,
12826 SelectionDAG &DAG) const {
12827 SDValue Result(0, 0);
12829 // Only support length 1 constraints for now.
12830 if (Constraint.length() > 1) return;
12832 char ConstraintLetter = Constraint[0];
12833 switch (ConstraintLetter) {
12836 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12837 if (C->getZExtValue() <= 31) {
12838 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12844 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12845 if (C->getZExtValue() <= 63) {
12846 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12852 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12853 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12854 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12860 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12861 if (C->getZExtValue() <= 255) {
12862 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12868 // 32-bit signed value
12869 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12870 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12871 C->getSExtValue())) {
12872 // Widen to 64 bits here to get it sign extended.
12873 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12876 // FIXME gcc accepts some relocatable values here too, but only in certain
12877 // memory models; it's complicated.
12882 // 32-bit unsigned value
12883 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12884 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12885 C->getZExtValue())) {
12886 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12890 // FIXME gcc accepts some relocatable values here too, but only in certain
12891 // memory models; it's complicated.
12895 // Literal immediates are always ok.
12896 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12897 // Widen to 64 bits here to get it sign extended.
12898 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12902 // In any sort of PIC mode addresses need to be computed at runtime by
12903 // adding in a register or some sort of table lookup. These can't
12904 // be used as immediates.
12905 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12908 // If we are in non-pic codegen mode, we allow the address of a global (with
12909 // an optional displacement) to be used with 'i'.
12910 GlobalAddressSDNode *GA = 0;
12911 int64_t Offset = 0;
12913 // Match either (GA), (GA+C), (GA+C1+C2), etc.
12915 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12916 Offset += GA->getOffset();
12918 } else if (Op.getOpcode() == ISD::ADD) {
12919 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12920 Offset += C->getZExtValue();
12921 Op = Op.getOperand(0);
12924 } else if (Op.getOpcode() == ISD::SUB) {
12925 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12926 Offset += -C->getZExtValue();
12927 Op = Op.getOperand(0);
12932 // Otherwise, this isn't something we can handle, reject it.
12936 const GlobalValue *GV = GA->getGlobal();
12937 // If we require an extra load to get this address, as in PIC mode, we
12938 // can't accept it.
12939 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12940 getTargetMachine())))
12943 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12944 GA->getValueType(0), Offset);
12949 if (Result.getNode()) {
12950 Ops.push_back(Result);
12953 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12956 std::pair<unsigned, const TargetRegisterClass*>
12957 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12959 // First, see if this is a constraint that directly corresponds to an LLVM
12961 if (Constraint.size() == 1) {
12962 // GCC Constraint Letters
12963 switch (Constraint[0]) {
12965 // TODO: Slight differences here in allocation order and leaving
12966 // RIP in the class. Do they matter any more here than they do
12967 // in the normal allocation?
12968 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12969 if (Subtarget->is64Bit()) {
12970 if (VT == MVT::i32 || VT == MVT::f32)
12971 return std::make_pair(0U, X86::GR32RegisterClass);
12972 else if (VT == MVT::i16)
12973 return std::make_pair(0U, X86::GR16RegisterClass);
12974 else if (VT == MVT::i8)
12975 return std::make_pair(0U, X86::GR8RegisterClass);
12976 else if (VT == MVT::i64 || VT == MVT::f64)
12977 return std::make_pair(0U, X86::GR64RegisterClass);
12980 // 32-bit fallthrough
12981 case 'Q': // Q_REGS
12982 if (VT == MVT::i32 || VT == MVT::f32)
12983 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
12984 else if (VT == MVT::i16)
12985 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
12986 else if (VT == MVT::i8)
12987 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
12988 else if (VT == MVT::i64)
12989 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
12991 case 'r': // GENERAL_REGS
12992 case 'l': // INDEX_REGS
12994 return std::make_pair(0U, X86::GR8RegisterClass);
12995 if (VT == MVT::i16)
12996 return std::make_pair(0U, X86::GR16RegisterClass);
12997 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
12998 return std::make_pair(0U, X86::GR32RegisterClass);
12999 return std::make_pair(0U, X86::GR64RegisterClass);
13000 case 'R': // LEGACY_REGS
13002 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
13003 if (VT == MVT::i16)
13004 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
13005 if (VT == MVT::i32 || !Subtarget->is64Bit())
13006 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
13007 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
13008 case 'f': // FP Stack registers.
13009 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
13010 // value to the correct fpstack register class.
13011 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
13012 return std::make_pair(0U, X86::RFP32RegisterClass);
13013 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
13014 return std::make_pair(0U, X86::RFP64RegisterClass);
13015 return std::make_pair(0U, X86::RFP80RegisterClass);
13016 case 'y': // MMX_REGS if MMX allowed.
13017 if (!Subtarget->hasMMX()) break;
13018 return std::make_pair(0U, X86::VR64RegisterClass);
13019 case 'Y': // SSE_REGS if SSE2 allowed
13020 if (!Subtarget->hasXMMInt()) break;
13022 case 'x': // SSE_REGS if SSE1 allowed
13023 if (!Subtarget->hasXMM()) break;
13025 switch (VT.getSimpleVT().SimpleTy) {
13027 // Scalar SSE types.
13030 return std::make_pair(0U, X86::FR32RegisterClass);
13033 return std::make_pair(0U, X86::FR64RegisterClass);
13041 return std::make_pair(0U, X86::VR128RegisterClass);
13047 // Use the default implementation in TargetLowering to convert the register
13048 // constraint into a member of a register class.
13049 std::pair<unsigned, const TargetRegisterClass*> Res;
13050 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
13052 // Not found as a standard register?
13053 if (Res.second == 0) {
13054 // Map st(0) -> st(7) -> ST0
13055 if (Constraint.size() == 7 && Constraint[0] == '{' &&
13056 tolower(Constraint[1]) == 's' &&
13057 tolower(Constraint[2]) == 't' &&
13058 Constraint[3] == '(' &&
13059 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
13060 Constraint[5] == ')' &&
13061 Constraint[6] == '}') {
13063 Res.first = X86::ST0+Constraint[4]-'0';
13064 Res.second = X86::RFP80RegisterClass;
13068 // GCC allows "st(0)" to be called just plain "st".
13069 if (StringRef("{st}").equals_lower(Constraint)) {
13070 Res.first = X86::ST0;
13071 Res.second = X86::RFP80RegisterClass;
13076 if (StringRef("{flags}").equals_lower(Constraint)) {
13077 Res.first = X86::EFLAGS;
13078 Res.second = X86::CCRRegisterClass;
13082 // 'A' means EAX + EDX.
13083 if (Constraint == "A") {
13084 Res.first = X86::EAX;
13085 Res.second = X86::GR32_ADRegisterClass;
13091 // Otherwise, check to see if this is a register class of the wrong value
13092 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
13093 // turn into {ax},{dx}.
13094 if (Res.second->hasType(VT))
13095 return Res; // Correct type already, nothing to do.
13097 // All of the single-register GCC register classes map their values onto
13098 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
13099 // really want an 8-bit or 32-bit register, map to the appropriate register
13100 // class and return the appropriate register.
13101 if (Res.second == X86::GR16RegisterClass) {
13102 if (VT == MVT::i8) {
13103 unsigned DestReg = 0;
13104 switch (Res.first) {
13106 case X86::AX: DestReg = X86::AL; break;
13107 case X86::DX: DestReg = X86::DL; break;
13108 case X86::CX: DestReg = X86::CL; break;
13109 case X86::BX: DestReg = X86::BL; break;
13112 Res.first = DestReg;
13113 Res.second = X86::GR8RegisterClass;
13115 } else if (VT == MVT::i32) {
13116 unsigned DestReg = 0;
13117 switch (Res.first) {
13119 case X86::AX: DestReg = X86::EAX; break;
13120 case X86::DX: DestReg = X86::EDX; break;
13121 case X86::CX: DestReg = X86::ECX; break;
13122 case X86::BX: DestReg = X86::EBX; break;
13123 case X86::SI: DestReg = X86::ESI; break;
13124 case X86::DI: DestReg = X86::EDI; break;
13125 case X86::BP: DestReg = X86::EBP; break;
13126 case X86::SP: DestReg = X86::ESP; break;
13129 Res.first = DestReg;
13130 Res.second = X86::GR32RegisterClass;
13132 } else if (VT == MVT::i64) {
13133 unsigned DestReg = 0;
13134 switch (Res.first) {
13136 case X86::AX: DestReg = X86::RAX; break;
13137 case X86::DX: DestReg = X86::RDX; break;
13138 case X86::CX: DestReg = X86::RCX; break;
13139 case X86::BX: DestReg = X86::RBX; break;
13140 case X86::SI: DestReg = X86::RSI; break;
13141 case X86::DI: DestReg = X86::RDI; break;
13142 case X86::BP: DestReg = X86::RBP; break;
13143 case X86::SP: DestReg = X86::RSP; break;
13146 Res.first = DestReg;
13147 Res.second = X86::GR64RegisterClass;
13150 } else if (Res.second == X86::FR32RegisterClass ||
13151 Res.second == X86::FR64RegisterClass ||
13152 Res.second == X86::VR128RegisterClass) {
13153 // Handle references to XMM physical registers that got mapped into the
13154 // wrong class. This can happen with constraints like {xmm0} where the
13155 // target independent register mapper will just pick the first match it can
13156 // find, ignoring the required type.
13157 if (VT == MVT::f32)
13158 Res.second = X86::FR32RegisterClass;
13159 else if (VT == MVT::f64)
13160 Res.second = X86::FR64RegisterClass;
13161 else if (X86::VR128RegisterClass->hasType(VT))
13162 Res.second = X86::VR128RegisterClass;