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);
1066 // We want to custom lower some of our intrinsics.
1067 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1070 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1071 // handle type legalization for these operations here.
1073 // FIXME: We really should do custom legalization for addition and
1074 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1075 // than generic legalization for 64-bit multiplication-with-overflow, though.
1076 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1077 // Add/Sub/Mul with overflow operations are custom lowered.
1079 setOperationAction(ISD::SADDO, VT, Custom);
1080 setOperationAction(ISD::UADDO, VT, Custom);
1081 setOperationAction(ISD::SSUBO, VT, Custom);
1082 setOperationAction(ISD::USUBO, VT, Custom);
1083 setOperationAction(ISD::SMULO, VT, Custom);
1084 setOperationAction(ISD::UMULO, VT, Custom);
1087 // There are no 8-bit 3-address imul/mul instructions
1088 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1089 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1091 if (!Subtarget->is64Bit()) {
1092 // These libcalls are not available in 32-bit.
1093 setLibcallName(RTLIB::SHL_I128, 0);
1094 setLibcallName(RTLIB::SRL_I128, 0);
1095 setLibcallName(RTLIB::SRA_I128, 0);
1098 // We have target-specific dag combine patterns for the following nodes:
1099 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1100 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1101 setTargetDAGCombine(ISD::BUILD_VECTOR);
1102 setTargetDAGCombine(ISD::SELECT);
1103 setTargetDAGCombine(ISD::SHL);
1104 setTargetDAGCombine(ISD::SRA);
1105 setTargetDAGCombine(ISD::SRL);
1106 setTargetDAGCombine(ISD::OR);
1107 setTargetDAGCombine(ISD::AND);
1108 setTargetDAGCombine(ISD::ADD);
1109 setTargetDAGCombine(ISD::SUB);
1110 setTargetDAGCombine(ISD::STORE);
1111 setTargetDAGCombine(ISD::ZERO_EXTEND);
1112 setTargetDAGCombine(ISD::SINT_TO_FP);
1113 if (Subtarget->is64Bit())
1114 setTargetDAGCombine(ISD::MUL);
1116 computeRegisterProperties();
1118 // On Darwin, -Os means optimize for size without hurting performance,
1119 // do not reduce the limit.
1120 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1121 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1122 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1123 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1124 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1125 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1126 setPrefLoopAlignment(16);
1127 benefitFromCodePlacementOpt = true;
1129 setPrefFunctionAlignment(4);
1133 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1138 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1139 /// the desired ByVal argument alignment.
1140 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1143 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1144 if (VTy->getBitWidth() == 128)
1146 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1147 unsigned EltAlign = 0;
1148 getMaxByValAlign(ATy->getElementType(), EltAlign);
1149 if (EltAlign > MaxAlign)
1150 MaxAlign = EltAlign;
1151 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1152 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1153 unsigned EltAlign = 0;
1154 getMaxByValAlign(STy->getElementType(i), EltAlign);
1155 if (EltAlign > MaxAlign)
1156 MaxAlign = EltAlign;
1164 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1165 /// function arguments in the caller parameter area. For X86, aggregates
1166 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1167 /// are at 4-byte boundaries.
1168 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1169 if (Subtarget->is64Bit()) {
1170 // Max of 8 and alignment of type.
1171 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1178 if (Subtarget->hasXMM())
1179 getMaxByValAlign(Ty, Align);
1183 /// getOptimalMemOpType - Returns the target specific optimal type for load
1184 /// and store operations as a result of memset, memcpy, and memmove
1185 /// lowering. If DstAlign is zero that means it's safe to destination
1186 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1187 /// means there isn't a need to check it against alignment requirement,
1188 /// probably because the source does not need to be loaded. If
1189 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1190 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1191 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1192 /// constant so it does not need to be loaded.
1193 /// It returns EVT::Other if the type should be determined using generic
1194 /// target-independent logic.
1196 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1197 unsigned DstAlign, unsigned SrcAlign,
1198 bool NonScalarIntSafe,
1200 MachineFunction &MF) const {
1201 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1202 // linux. This is because the stack realignment code can't handle certain
1203 // cases like PR2962. This should be removed when PR2962 is fixed.
1204 const Function *F = MF.getFunction();
1205 if (NonScalarIntSafe &&
1206 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1208 (Subtarget->isUnalignedMemAccessFast() ||
1209 ((DstAlign == 0 || DstAlign >= 16) &&
1210 (SrcAlign == 0 || SrcAlign >= 16))) &&
1211 Subtarget->getStackAlignment() >= 16) {
1212 if (Subtarget->hasSSE2())
1214 if (Subtarget->hasSSE1())
1216 } else if (!MemcpyStrSrc && Size >= 8 &&
1217 !Subtarget->is64Bit() &&
1218 Subtarget->getStackAlignment() >= 8 &&
1219 Subtarget->hasXMMInt()) {
1220 // Do not use f64 to lower memcpy if source is string constant. It's
1221 // better to use i32 to avoid the loads.
1225 if (Subtarget->is64Bit() && Size >= 8)
1230 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1231 /// current function. The returned value is a member of the
1232 /// MachineJumpTableInfo::JTEntryKind enum.
1233 unsigned X86TargetLowering::getJumpTableEncoding() const {
1234 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1236 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1237 Subtarget->isPICStyleGOT())
1238 return MachineJumpTableInfo::EK_Custom32;
1240 // Otherwise, use the normal jump table encoding heuristics.
1241 return TargetLowering::getJumpTableEncoding();
1245 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1246 const MachineBasicBlock *MBB,
1247 unsigned uid,MCContext &Ctx) const{
1248 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1249 Subtarget->isPICStyleGOT());
1250 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1252 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1253 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1256 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1258 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1259 SelectionDAG &DAG) const {
1260 if (!Subtarget->is64Bit())
1261 // This doesn't have DebugLoc associated with it, but is not really the
1262 // same as a Register.
1263 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1267 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1268 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1270 const MCExpr *X86TargetLowering::
1271 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1272 MCContext &Ctx) const {
1273 // X86-64 uses RIP relative addressing based on the jump table label.
1274 if (Subtarget->isPICStyleRIPRel())
1275 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1277 // Otherwise, the reference is relative to the PIC base.
1278 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1281 // FIXME: Why this routine is here? Move to RegInfo!
1282 std::pair<const TargetRegisterClass*, uint8_t>
1283 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1284 const TargetRegisterClass *RRC = 0;
1286 switch (VT.getSimpleVT().SimpleTy) {
1288 return TargetLowering::findRepresentativeClass(VT);
1289 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1290 RRC = (Subtarget->is64Bit()
1291 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1294 RRC = X86::VR64RegisterClass;
1296 case MVT::f32: case MVT::f64:
1297 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1298 case MVT::v4f32: case MVT::v2f64:
1299 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1301 RRC = X86::VR128RegisterClass;
1304 return std::make_pair(RRC, Cost);
1307 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1308 unsigned &Offset) const {
1309 if (!Subtarget->isTargetLinux())
1312 if (Subtarget->is64Bit()) {
1313 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1315 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1328 //===----------------------------------------------------------------------===//
1329 // Return Value Calling Convention Implementation
1330 //===----------------------------------------------------------------------===//
1332 #include "X86GenCallingConv.inc"
1335 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1336 MachineFunction &MF, bool isVarArg,
1337 const SmallVectorImpl<ISD::OutputArg> &Outs,
1338 LLVMContext &Context) const {
1339 SmallVector<CCValAssign, 16> RVLocs;
1340 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1342 return CCInfo.CheckReturn(Outs, RetCC_X86);
1346 X86TargetLowering::LowerReturn(SDValue Chain,
1347 CallingConv::ID CallConv, bool isVarArg,
1348 const SmallVectorImpl<ISD::OutputArg> &Outs,
1349 const SmallVectorImpl<SDValue> &OutVals,
1350 DebugLoc dl, SelectionDAG &DAG) const {
1351 MachineFunction &MF = DAG.getMachineFunction();
1352 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1354 SmallVector<CCValAssign, 16> RVLocs;
1355 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1356 RVLocs, *DAG.getContext());
1357 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1359 // Add the regs to the liveout set for the function.
1360 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1361 for (unsigned i = 0; i != RVLocs.size(); ++i)
1362 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1363 MRI.addLiveOut(RVLocs[i].getLocReg());
1367 SmallVector<SDValue, 6> RetOps;
1368 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1369 // Operand #1 = Bytes To Pop
1370 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1373 // Copy the result values into the output registers.
1374 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1375 CCValAssign &VA = RVLocs[i];
1376 assert(VA.isRegLoc() && "Can only return in registers!");
1377 SDValue ValToCopy = OutVals[i];
1378 EVT ValVT = ValToCopy.getValueType();
1380 // If this is x86-64, and we disabled SSE, we can't return FP values,
1381 // or SSE or MMX vectors.
1382 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1383 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1384 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1385 report_fatal_error("SSE register return with SSE disabled");
1387 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1388 // llvm-gcc has never done it right and no one has noticed, so this
1389 // should be OK for now.
1390 if (ValVT == MVT::f64 &&
1391 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1392 report_fatal_error("SSE2 register return with SSE2 disabled");
1394 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1395 // the RET instruction and handled by the FP Stackifier.
1396 if (VA.getLocReg() == X86::ST0 ||
1397 VA.getLocReg() == X86::ST1) {
1398 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1399 // change the value to the FP stack register class.
1400 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1401 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1402 RetOps.push_back(ValToCopy);
1403 // Don't emit a copytoreg.
1407 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1408 // which is returned in RAX / RDX.
1409 if (Subtarget->is64Bit()) {
1410 if (ValVT == MVT::x86mmx) {
1411 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1412 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1413 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1415 // If we don't have SSE2 available, convert to v4f32 so the generated
1416 // register is legal.
1417 if (!Subtarget->hasSSE2())
1418 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1423 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1424 Flag = Chain.getValue(1);
1427 // The x86-64 ABI for returning structs by value requires that we copy
1428 // the sret argument into %rax for the return. We saved the argument into
1429 // a virtual register in the entry block, so now we copy the value out
1431 if (Subtarget->is64Bit() &&
1432 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1433 MachineFunction &MF = DAG.getMachineFunction();
1434 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1435 unsigned Reg = FuncInfo->getSRetReturnReg();
1437 "SRetReturnReg should have been set in LowerFormalArguments().");
1438 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1440 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1441 Flag = Chain.getValue(1);
1443 // RAX now acts like a return value.
1444 MRI.addLiveOut(X86::RAX);
1447 RetOps[0] = Chain; // Update chain.
1449 // Add the flag if we have it.
1451 RetOps.push_back(Flag);
1453 return DAG.getNode(X86ISD::RET_FLAG, dl,
1454 MVT::Other, &RetOps[0], RetOps.size());
1457 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1458 if (N->getNumValues() != 1)
1460 if (!N->hasNUsesOfValue(1, 0))
1463 SDNode *Copy = *N->use_begin();
1464 if (Copy->getOpcode() != ISD::CopyToReg &&
1465 Copy->getOpcode() != ISD::FP_EXTEND)
1468 bool HasRet = false;
1469 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1471 if (UI->getOpcode() != X86ISD::RET_FLAG)
1480 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1481 ISD::NodeType ExtendKind) const {
1483 // TODO: Is this also valid on 32-bit?
1484 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1485 ReturnMVT = MVT::i8;
1487 ReturnMVT = MVT::i32;
1489 EVT MinVT = getRegisterType(Context, ReturnMVT);
1490 return VT.bitsLT(MinVT) ? MinVT : VT;
1493 /// LowerCallResult - Lower the result values of a call into the
1494 /// appropriate copies out of appropriate physical registers.
1497 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1498 CallingConv::ID CallConv, bool isVarArg,
1499 const SmallVectorImpl<ISD::InputArg> &Ins,
1500 DebugLoc dl, SelectionDAG &DAG,
1501 SmallVectorImpl<SDValue> &InVals) const {
1503 // Assign locations to each value returned by this call.
1504 SmallVector<CCValAssign, 16> RVLocs;
1505 bool Is64Bit = Subtarget->is64Bit();
1506 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1507 getTargetMachine(), RVLocs, *DAG.getContext());
1508 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1510 // Copy all of the result registers out of their specified physreg.
1511 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1512 CCValAssign &VA = RVLocs[i];
1513 EVT CopyVT = VA.getValVT();
1515 // If this is x86-64, and we disabled SSE, we can't return FP values
1516 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1517 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1518 report_fatal_error("SSE register return with SSE disabled");
1523 // If this is a call to a function that returns an fp value on the floating
1524 // point stack, we must guarantee the the value is popped from the stack, so
1525 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1526 // if the return value is not used. We use the FpPOP_RETVAL instruction
1528 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1529 // If we prefer to use the value in xmm registers, copy it out as f80 and
1530 // use a truncate to move it from fp stack reg to xmm reg.
1531 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1532 SDValue Ops[] = { Chain, InFlag };
1533 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1534 MVT::Other, MVT::Glue, Ops, 2), 1);
1535 Val = Chain.getValue(0);
1537 // Round the f80 to the right size, which also moves it to the appropriate
1539 if (CopyVT != VA.getValVT())
1540 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1541 // This truncation won't change the value.
1542 DAG.getIntPtrConstant(1));
1544 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1545 CopyVT, InFlag).getValue(1);
1546 Val = Chain.getValue(0);
1548 InFlag = Chain.getValue(2);
1549 InVals.push_back(Val);
1556 //===----------------------------------------------------------------------===//
1557 // C & StdCall & Fast Calling Convention implementation
1558 //===----------------------------------------------------------------------===//
1559 // StdCall calling convention seems to be standard for many Windows' API
1560 // routines and around. It differs from C calling convention just a little:
1561 // callee should clean up the stack, not caller. Symbols should be also
1562 // decorated in some fancy way :) It doesn't support any vector arguments.
1563 // For info on fast calling convention see Fast Calling Convention (tail call)
1564 // implementation LowerX86_32FastCCCallTo.
1566 /// CallIsStructReturn - Determines whether a call uses struct return
1568 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1572 return Outs[0].Flags.isSRet();
1575 /// ArgsAreStructReturn - Determines whether a function uses struct
1576 /// return semantics.
1578 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1582 return Ins[0].Flags.isSRet();
1585 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1586 /// by "Src" to address "Dst" with size and alignment information specified by
1587 /// the specific parameter attribute. The copy will be passed as a byval
1588 /// function parameter.
1590 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1591 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1593 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1595 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1596 /*isVolatile*/false, /*AlwaysInline=*/true,
1597 MachinePointerInfo(), MachinePointerInfo());
1600 /// IsTailCallConvention - Return true if the calling convention is one that
1601 /// supports tail call optimization.
1602 static bool IsTailCallConvention(CallingConv::ID CC) {
1603 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1606 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1607 if (!CI->isTailCall())
1611 CallingConv::ID CalleeCC = CS.getCallingConv();
1612 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1618 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1619 /// a tailcall target by changing its ABI.
1620 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1621 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1625 X86TargetLowering::LowerMemArgument(SDValue Chain,
1626 CallingConv::ID CallConv,
1627 const SmallVectorImpl<ISD::InputArg> &Ins,
1628 DebugLoc dl, SelectionDAG &DAG,
1629 const CCValAssign &VA,
1630 MachineFrameInfo *MFI,
1632 // Create the nodes corresponding to a load from this parameter slot.
1633 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1634 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1635 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1638 // If value is passed by pointer we have address passed instead of the value
1640 if (VA.getLocInfo() == CCValAssign::Indirect)
1641 ValVT = VA.getLocVT();
1643 ValVT = VA.getValVT();
1645 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1646 // changed with more analysis.
1647 // In case of tail call optimization mark all arguments mutable. Since they
1648 // could be overwritten by lowering of arguments in case of a tail call.
1649 if (Flags.isByVal()) {
1650 unsigned Bytes = Flags.getByValSize();
1651 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1652 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1653 return DAG.getFrameIndex(FI, getPointerTy());
1655 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1656 VA.getLocMemOffset(), isImmutable);
1657 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1658 return DAG.getLoad(ValVT, dl, Chain, FIN,
1659 MachinePointerInfo::getFixedStack(FI),
1665 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1666 CallingConv::ID CallConv,
1668 const SmallVectorImpl<ISD::InputArg> &Ins,
1671 SmallVectorImpl<SDValue> &InVals)
1673 MachineFunction &MF = DAG.getMachineFunction();
1674 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1676 const Function* Fn = MF.getFunction();
1677 if (Fn->hasExternalLinkage() &&
1678 Subtarget->isTargetCygMing() &&
1679 Fn->getName() == "main")
1680 FuncInfo->setForceFramePointer(true);
1682 MachineFrameInfo *MFI = MF.getFrameInfo();
1683 bool Is64Bit = Subtarget->is64Bit();
1684 bool IsWin64 = Subtarget->isTargetWin64();
1686 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1687 "Var args not supported with calling convention fastcc or ghc");
1689 // Assign locations to all of the incoming arguments.
1690 SmallVector<CCValAssign, 16> ArgLocs;
1691 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1692 ArgLocs, *DAG.getContext());
1694 // Allocate shadow area for Win64
1696 CCInfo.AllocateStack(32, 8);
1699 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1701 unsigned LastVal = ~0U;
1703 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1704 CCValAssign &VA = ArgLocs[i];
1705 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1707 assert(VA.getValNo() != LastVal &&
1708 "Don't support value assigned to multiple locs yet");
1709 LastVal = VA.getValNo();
1711 if (VA.isRegLoc()) {
1712 EVT RegVT = VA.getLocVT();
1713 TargetRegisterClass *RC = NULL;
1714 if (RegVT == MVT::i32)
1715 RC = X86::GR32RegisterClass;
1716 else if (Is64Bit && RegVT == MVT::i64)
1717 RC = X86::GR64RegisterClass;
1718 else if (RegVT == MVT::f32)
1719 RC = X86::FR32RegisterClass;
1720 else if (RegVT == MVT::f64)
1721 RC = X86::FR64RegisterClass;
1722 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1723 RC = X86::VR256RegisterClass;
1724 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1725 RC = X86::VR128RegisterClass;
1726 else if (RegVT == MVT::x86mmx)
1727 RC = X86::VR64RegisterClass;
1729 llvm_unreachable("Unknown argument type!");
1731 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1732 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1734 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1735 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1737 if (VA.getLocInfo() == CCValAssign::SExt)
1738 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1739 DAG.getValueType(VA.getValVT()));
1740 else if (VA.getLocInfo() == CCValAssign::ZExt)
1741 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1742 DAG.getValueType(VA.getValVT()));
1743 else if (VA.getLocInfo() == CCValAssign::BCvt)
1744 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1746 if (VA.isExtInLoc()) {
1747 // Handle MMX values passed in XMM regs.
1748 if (RegVT.isVector()) {
1749 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1752 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1755 assert(VA.isMemLoc());
1756 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1759 // If value is passed via pointer - do a load.
1760 if (VA.getLocInfo() == CCValAssign::Indirect)
1761 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1762 MachinePointerInfo(), false, false, 0);
1764 InVals.push_back(ArgValue);
1767 // The x86-64 ABI for returning structs by value requires that we copy
1768 // the sret argument into %rax for the return. Save the argument into
1769 // a virtual register so that we can access it from the return points.
1770 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1771 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1772 unsigned Reg = FuncInfo->getSRetReturnReg();
1774 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1775 FuncInfo->setSRetReturnReg(Reg);
1777 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1778 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1781 unsigned StackSize = CCInfo.getNextStackOffset();
1782 // Align stack specially for tail calls.
1783 if (FuncIsMadeTailCallSafe(CallConv))
1784 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1786 // If the function takes variable number of arguments, make a frame index for
1787 // the start of the first vararg value... for expansion of llvm.va_start.
1789 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1790 CallConv != CallingConv::X86_ThisCall)) {
1791 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1794 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1796 // FIXME: We should really autogenerate these arrays
1797 static const unsigned GPR64ArgRegsWin64[] = {
1798 X86::RCX, X86::RDX, X86::R8, X86::R9
1800 static const unsigned GPR64ArgRegs64Bit[] = {
1801 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1803 static const unsigned XMMArgRegs64Bit[] = {
1804 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1805 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1807 const unsigned *GPR64ArgRegs;
1808 unsigned NumXMMRegs = 0;
1811 // The XMM registers which might contain var arg parameters are shadowed
1812 // in their paired GPR. So we only need to save the GPR to their home
1814 TotalNumIntRegs = 4;
1815 GPR64ArgRegs = GPR64ArgRegsWin64;
1817 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1818 GPR64ArgRegs = GPR64ArgRegs64Bit;
1820 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1822 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1825 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1826 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1827 "SSE register cannot be used when SSE is disabled!");
1828 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1829 "SSE register cannot be used when SSE is disabled!");
1830 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1831 // Kernel mode asks for SSE to be disabled, so don't push them
1833 TotalNumXMMRegs = 0;
1836 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1837 // Get to the caller-allocated home save location. Add 8 to account
1838 // for the return address.
1839 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1840 FuncInfo->setRegSaveFrameIndex(
1841 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1842 // Fixup to set vararg frame on shadow area (4 x i64).
1844 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1846 // For X86-64, if there are vararg parameters that are passed via
1847 // registers, then we must store them to their spots on the stack so they
1848 // may be loaded by deferencing the result of va_next.
1849 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1850 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1851 FuncInfo->setRegSaveFrameIndex(
1852 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1856 // Store the integer parameter registers.
1857 SmallVector<SDValue, 8> MemOps;
1858 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1860 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1861 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1862 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1863 DAG.getIntPtrConstant(Offset));
1864 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1865 X86::GR64RegisterClass);
1866 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1868 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1869 MachinePointerInfo::getFixedStack(
1870 FuncInfo->getRegSaveFrameIndex(), Offset),
1872 MemOps.push_back(Store);
1876 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1877 // Now store the XMM (fp + vector) parameter registers.
1878 SmallVector<SDValue, 11> SaveXMMOps;
1879 SaveXMMOps.push_back(Chain);
1881 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1882 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1883 SaveXMMOps.push_back(ALVal);
1885 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1886 FuncInfo->getRegSaveFrameIndex()));
1887 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1888 FuncInfo->getVarArgsFPOffset()));
1890 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1891 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1892 X86::VR128RegisterClass);
1893 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1894 SaveXMMOps.push_back(Val);
1896 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1898 &SaveXMMOps[0], SaveXMMOps.size()));
1901 if (!MemOps.empty())
1902 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1903 &MemOps[0], MemOps.size());
1907 // Some CCs need callee pop.
1908 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1909 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1911 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1912 // If this is an sret function, the return should pop the hidden pointer.
1913 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1914 FuncInfo->setBytesToPopOnReturn(4);
1918 // RegSaveFrameIndex is X86-64 only.
1919 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1920 if (CallConv == CallingConv::X86_FastCall ||
1921 CallConv == CallingConv::X86_ThisCall)
1922 // fastcc functions can't have varargs.
1923 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1930 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1931 SDValue StackPtr, SDValue Arg,
1932 DebugLoc dl, SelectionDAG &DAG,
1933 const CCValAssign &VA,
1934 ISD::ArgFlagsTy Flags) const {
1935 unsigned LocMemOffset = VA.getLocMemOffset();
1936 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1937 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1938 if (Flags.isByVal())
1939 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1941 return DAG.getStore(Chain, dl, Arg, PtrOff,
1942 MachinePointerInfo::getStack(LocMemOffset),
1946 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1947 /// optimization is performed and it is required.
1949 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1950 SDValue &OutRetAddr, SDValue Chain,
1951 bool IsTailCall, bool Is64Bit,
1952 int FPDiff, DebugLoc dl) const {
1953 // Adjust the Return address stack slot.
1954 EVT VT = getPointerTy();
1955 OutRetAddr = getReturnAddressFrameIndex(DAG);
1957 // Load the "old" Return address.
1958 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1960 return SDValue(OutRetAddr.getNode(), 1);
1963 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1964 /// optimization is performed and it is required (FPDiff!=0).
1966 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1967 SDValue Chain, SDValue RetAddrFrIdx,
1968 bool Is64Bit, int FPDiff, DebugLoc dl) {
1969 // Store the return address to the appropriate stack slot.
1970 if (!FPDiff) return Chain;
1971 // Calculate the new stack slot for the return address.
1972 int SlotSize = Is64Bit ? 8 : 4;
1973 int NewReturnAddrFI =
1974 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1975 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1976 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1977 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1978 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1984 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1985 CallingConv::ID CallConv, bool isVarArg,
1987 const SmallVectorImpl<ISD::OutputArg> &Outs,
1988 const SmallVectorImpl<SDValue> &OutVals,
1989 const SmallVectorImpl<ISD::InputArg> &Ins,
1990 DebugLoc dl, SelectionDAG &DAG,
1991 SmallVectorImpl<SDValue> &InVals) const {
1992 MachineFunction &MF = DAG.getMachineFunction();
1993 bool Is64Bit = Subtarget->is64Bit();
1994 bool IsWin64 = Subtarget->isTargetWin64();
1995 bool IsStructRet = CallIsStructReturn(Outs);
1996 bool IsSibcall = false;
1999 // Check if it's really possible to do a tail call.
2000 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2001 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2002 Outs, OutVals, Ins, DAG);
2004 // Sibcalls are automatically detected tailcalls which do not require
2006 if (!GuaranteedTailCallOpt && isTailCall)
2013 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2014 "Var args not supported with calling convention fastcc or ghc");
2016 // Analyze operands of the call, assigning locations to each operand.
2017 SmallVector<CCValAssign, 16> ArgLocs;
2018 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2019 ArgLocs, *DAG.getContext());
2021 // Allocate shadow area for Win64
2023 CCInfo.AllocateStack(32, 8);
2026 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2028 // Get a count of how many bytes are to be pushed on the stack.
2029 unsigned NumBytes = CCInfo.getNextStackOffset();
2031 // This is a sibcall. The memory operands are available in caller's
2032 // own caller's stack.
2034 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2035 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2038 if (isTailCall && !IsSibcall) {
2039 // Lower arguments at fp - stackoffset + fpdiff.
2040 unsigned NumBytesCallerPushed =
2041 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2042 FPDiff = NumBytesCallerPushed - NumBytes;
2044 // Set the delta of movement of the returnaddr stackslot.
2045 // But only set if delta is greater than previous delta.
2046 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2047 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2051 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2053 SDValue RetAddrFrIdx;
2054 // Load return address for tail calls.
2055 if (isTailCall && FPDiff)
2056 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2057 Is64Bit, FPDiff, dl);
2059 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2060 SmallVector<SDValue, 8> MemOpChains;
2063 // Walk the register/memloc assignments, inserting copies/loads. In the case
2064 // of tail call optimization arguments are handle later.
2065 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2066 CCValAssign &VA = ArgLocs[i];
2067 EVT RegVT = VA.getLocVT();
2068 SDValue Arg = OutVals[i];
2069 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2070 bool isByVal = Flags.isByVal();
2072 // Promote the value if needed.
2073 switch (VA.getLocInfo()) {
2074 default: llvm_unreachable("Unknown loc info!");
2075 case CCValAssign::Full: break;
2076 case CCValAssign::SExt:
2077 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2079 case CCValAssign::ZExt:
2080 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2082 case CCValAssign::AExt:
2083 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2084 // Special case: passing MMX values in XMM registers.
2085 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2086 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2087 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2089 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2091 case CCValAssign::BCvt:
2092 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2094 case CCValAssign::Indirect: {
2095 // Store the argument.
2096 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2097 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2098 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2099 MachinePointerInfo::getFixedStack(FI),
2106 if (VA.isRegLoc()) {
2107 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2108 if (isVarArg && IsWin64) {
2109 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2110 // shadow reg if callee is a varargs function.
2111 unsigned ShadowReg = 0;
2112 switch (VA.getLocReg()) {
2113 case X86::XMM0: ShadowReg = X86::RCX; break;
2114 case X86::XMM1: ShadowReg = X86::RDX; break;
2115 case X86::XMM2: ShadowReg = X86::R8; break;
2116 case X86::XMM3: ShadowReg = X86::R9; break;
2119 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2121 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2122 assert(VA.isMemLoc());
2123 if (StackPtr.getNode() == 0)
2124 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2125 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2126 dl, DAG, VA, Flags));
2130 if (!MemOpChains.empty())
2131 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2132 &MemOpChains[0], MemOpChains.size());
2134 // Build a sequence of copy-to-reg nodes chained together with token chain
2135 // and flag operands which copy the outgoing args into registers.
2137 // Tail call byval lowering might overwrite argument registers so in case of
2138 // tail call optimization the copies to registers are lowered later.
2140 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2141 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2142 RegsToPass[i].second, InFlag);
2143 InFlag = Chain.getValue(1);
2146 if (Subtarget->isPICStyleGOT()) {
2147 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2150 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2151 DAG.getNode(X86ISD::GlobalBaseReg,
2152 DebugLoc(), getPointerTy()),
2154 InFlag = Chain.getValue(1);
2156 // If we are tail calling and generating PIC/GOT style code load the
2157 // address of the callee into ECX. The value in ecx is used as target of
2158 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2159 // for tail calls on PIC/GOT architectures. Normally we would just put the
2160 // address of GOT into ebx and then call target@PLT. But for tail calls
2161 // ebx would be restored (since ebx is callee saved) before jumping to the
2164 // Note: The actual moving to ECX is done further down.
2165 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2166 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2167 !G->getGlobal()->hasProtectedVisibility())
2168 Callee = LowerGlobalAddress(Callee, DAG);
2169 else if (isa<ExternalSymbolSDNode>(Callee))
2170 Callee = LowerExternalSymbol(Callee, DAG);
2174 if (Is64Bit && isVarArg && !IsWin64) {
2175 // From AMD64 ABI document:
2176 // For calls that may call functions that use varargs or stdargs
2177 // (prototype-less calls or calls to functions containing ellipsis (...) in
2178 // the declaration) %al is used as hidden argument to specify the number
2179 // of SSE registers used. The contents of %al do not need to match exactly
2180 // the number of registers, but must be an ubound on the number of SSE
2181 // registers used and is in the range 0 - 8 inclusive.
2183 // Count the number of XMM registers allocated.
2184 static const unsigned XMMArgRegs[] = {
2185 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2186 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2188 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2189 assert((Subtarget->hasXMM() || !NumXMMRegs)
2190 && "SSE registers cannot be used when SSE is disabled");
2192 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2193 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2194 InFlag = Chain.getValue(1);
2198 // For tail calls lower the arguments to the 'real' stack slot.
2200 // Force all the incoming stack arguments to be loaded from the stack
2201 // before any new outgoing arguments are stored to the stack, because the
2202 // outgoing stack slots may alias the incoming argument stack slots, and
2203 // the alias isn't otherwise explicit. This is slightly more conservative
2204 // than necessary, because it means that each store effectively depends
2205 // on every argument instead of just those arguments it would clobber.
2206 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2208 SmallVector<SDValue, 8> MemOpChains2;
2211 // Do not flag preceding copytoreg stuff together with the following stuff.
2213 if (GuaranteedTailCallOpt) {
2214 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2215 CCValAssign &VA = ArgLocs[i];
2218 assert(VA.isMemLoc());
2219 SDValue Arg = OutVals[i];
2220 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2221 // Create frame index.
2222 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2223 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2224 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2225 FIN = DAG.getFrameIndex(FI, getPointerTy());
2227 if (Flags.isByVal()) {
2228 // Copy relative to framepointer.
2229 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2230 if (StackPtr.getNode() == 0)
2231 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2233 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2235 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2239 // Store relative to framepointer.
2240 MemOpChains2.push_back(
2241 DAG.getStore(ArgChain, dl, Arg, FIN,
2242 MachinePointerInfo::getFixedStack(FI),
2248 if (!MemOpChains2.empty())
2249 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2250 &MemOpChains2[0], MemOpChains2.size());
2252 // Copy arguments to their registers.
2253 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2254 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2255 RegsToPass[i].second, InFlag);
2256 InFlag = Chain.getValue(1);
2260 // Store the return address to the appropriate stack slot.
2261 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2265 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2266 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2267 // In the 64-bit large code model, we have to make all calls
2268 // through a register, since the call instruction's 32-bit
2269 // pc-relative offset may not be large enough to hold the whole
2271 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2272 // If the callee is a GlobalAddress node (quite common, every direct call
2273 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2276 // We should use extra load for direct calls to dllimported functions in
2278 const GlobalValue *GV = G->getGlobal();
2279 if (!GV->hasDLLImportLinkage()) {
2280 unsigned char OpFlags = 0;
2281 bool ExtraLoad = false;
2282 unsigned WrapperKind = ISD::DELETED_NODE;
2284 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2285 // external symbols most go through the PLT in PIC mode. If the symbol
2286 // has hidden or protected visibility, or if it is static or local, then
2287 // we don't need to use the PLT - we can directly call it.
2288 if (Subtarget->isTargetELF() &&
2289 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2290 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2291 OpFlags = X86II::MO_PLT;
2292 } else if (Subtarget->isPICStyleStubAny() &&
2293 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2294 (!Subtarget->getTargetTriple().isMacOSX() ||
2295 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2296 // PC-relative references to external symbols should go through $stub,
2297 // unless we're building with the leopard linker or later, which
2298 // automatically synthesizes these stubs.
2299 OpFlags = X86II::MO_DARWIN_STUB;
2300 } else if (Subtarget->isPICStyleRIPRel() &&
2301 isa<Function>(GV) &&
2302 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2303 // If the function is marked as non-lazy, generate an indirect call
2304 // which loads from the GOT directly. This avoids runtime overhead
2305 // at the cost of eager binding (and one extra byte of encoding).
2306 OpFlags = X86II::MO_GOTPCREL;
2307 WrapperKind = X86ISD::WrapperRIP;
2311 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2312 G->getOffset(), OpFlags);
2314 // Add a wrapper if needed.
2315 if (WrapperKind != ISD::DELETED_NODE)
2316 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2317 // Add extra indirection if needed.
2319 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2320 MachinePointerInfo::getGOT(),
2323 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2324 unsigned char OpFlags = 0;
2326 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2327 // external symbols should go through the PLT.
2328 if (Subtarget->isTargetELF() &&
2329 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2330 OpFlags = X86II::MO_PLT;
2331 } else if (Subtarget->isPICStyleStubAny() &&
2332 (!Subtarget->getTargetTriple().isMacOSX() ||
2333 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2334 // PC-relative references to external symbols should go through $stub,
2335 // unless we're building with the leopard linker or later, which
2336 // automatically synthesizes these stubs.
2337 OpFlags = X86II::MO_DARWIN_STUB;
2340 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2344 // Returns a chain & a flag for retval copy to use.
2345 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2346 SmallVector<SDValue, 8> Ops;
2348 if (!IsSibcall && isTailCall) {
2349 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2350 DAG.getIntPtrConstant(0, true), InFlag);
2351 InFlag = Chain.getValue(1);
2354 Ops.push_back(Chain);
2355 Ops.push_back(Callee);
2358 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2360 // Add argument registers to the end of the list so that they are known live
2362 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2363 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2364 RegsToPass[i].second.getValueType()));
2366 // Add an implicit use GOT pointer in EBX.
2367 if (!isTailCall && Subtarget->isPICStyleGOT())
2368 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2370 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2371 if (Is64Bit && isVarArg && !IsWin64)
2372 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2374 if (InFlag.getNode())
2375 Ops.push_back(InFlag);
2379 //// If this is the first return lowered for this function, add the regs
2380 //// to the liveout set for the function.
2381 // This isn't right, although it's probably harmless on x86; liveouts
2382 // should be computed from returns not tail calls. Consider a void
2383 // function making a tail call to a function returning int.
2384 return DAG.getNode(X86ISD::TC_RETURN, dl,
2385 NodeTys, &Ops[0], Ops.size());
2388 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2389 InFlag = Chain.getValue(1);
2391 // Create the CALLSEQ_END node.
2392 unsigned NumBytesForCalleeToPush;
2393 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2394 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2395 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2396 // If this is a call to a struct-return function, the callee
2397 // pops the hidden struct pointer, so we have to push it back.
2398 // This is common for Darwin/X86, Linux & Mingw32 targets.
2399 NumBytesForCalleeToPush = 4;
2401 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2403 // Returns a flag for retval copy to use.
2405 Chain = DAG.getCALLSEQ_END(Chain,
2406 DAG.getIntPtrConstant(NumBytes, true),
2407 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2410 InFlag = Chain.getValue(1);
2413 // Handle result values, copying them out of physregs into vregs that we
2415 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2416 Ins, dl, DAG, InVals);
2420 //===----------------------------------------------------------------------===//
2421 // Fast Calling Convention (tail call) implementation
2422 //===----------------------------------------------------------------------===//
2424 // Like std call, callee cleans arguments, convention except that ECX is
2425 // reserved for storing the tail called function address. Only 2 registers are
2426 // free for argument passing (inreg). Tail call optimization is performed
2428 // * tailcallopt is enabled
2429 // * caller/callee are fastcc
2430 // On X86_64 architecture with GOT-style position independent code only local
2431 // (within module) calls are supported at the moment.
2432 // To keep the stack aligned according to platform abi the function
2433 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2434 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2435 // If a tail called function callee has more arguments than the caller the
2436 // caller needs to make sure that there is room to move the RETADDR to. This is
2437 // achieved by reserving an area the size of the argument delta right after the
2438 // original REtADDR, but before the saved framepointer or the spilled registers
2439 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2451 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2452 /// for a 16 byte align requirement.
2454 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2455 SelectionDAG& DAG) const {
2456 MachineFunction &MF = DAG.getMachineFunction();
2457 const TargetMachine &TM = MF.getTarget();
2458 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2459 unsigned StackAlignment = TFI.getStackAlignment();
2460 uint64_t AlignMask = StackAlignment - 1;
2461 int64_t Offset = StackSize;
2462 uint64_t SlotSize = TD->getPointerSize();
2463 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2464 // Number smaller than 12 so just add the difference.
2465 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2467 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2468 Offset = ((~AlignMask) & Offset) + StackAlignment +
2469 (StackAlignment-SlotSize);
2474 /// MatchingStackOffset - Return true if the given stack call argument is
2475 /// already available in the same position (relatively) of the caller's
2476 /// incoming argument stack.
2478 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2479 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2480 const X86InstrInfo *TII) {
2481 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2483 if (Arg.getOpcode() == ISD::CopyFromReg) {
2484 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2485 if (!TargetRegisterInfo::isVirtualRegister(VR))
2487 MachineInstr *Def = MRI->getVRegDef(VR);
2490 if (!Flags.isByVal()) {
2491 if (!TII->isLoadFromStackSlot(Def, FI))
2494 unsigned Opcode = Def->getOpcode();
2495 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2496 Def->getOperand(1).isFI()) {
2497 FI = Def->getOperand(1).getIndex();
2498 Bytes = Flags.getByValSize();
2502 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2503 if (Flags.isByVal())
2504 // ByVal argument is passed in as a pointer but it's now being
2505 // dereferenced. e.g.
2506 // define @foo(%struct.X* %A) {
2507 // tail call @bar(%struct.X* byval %A)
2510 SDValue Ptr = Ld->getBasePtr();
2511 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2514 FI = FINode->getIndex();
2515 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2516 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2517 FI = FINode->getIndex();
2518 Bytes = Flags.getByValSize();
2522 assert(FI != INT_MAX);
2523 if (!MFI->isFixedObjectIndex(FI))
2525 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2528 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2529 /// for tail call optimization. Targets which want to do tail call
2530 /// optimization should implement this function.
2532 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2533 CallingConv::ID CalleeCC,
2535 bool isCalleeStructRet,
2536 bool isCallerStructRet,
2537 const SmallVectorImpl<ISD::OutputArg> &Outs,
2538 const SmallVectorImpl<SDValue> &OutVals,
2539 const SmallVectorImpl<ISD::InputArg> &Ins,
2540 SelectionDAG& DAG) const {
2541 if (!IsTailCallConvention(CalleeCC) &&
2542 CalleeCC != CallingConv::C)
2545 // If -tailcallopt is specified, make fastcc functions tail-callable.
2546 const MachineFunction &MF = DAG.getMachineFunction();
2547 const Function *CallerF = DAG.getMachineFunction().getFunction();
2548 CallingConv::ID CallerCC = CallerF->getCallingConv();
2549 bool CCMatch = CallerCC == CalleeCC;
2551 if (GuaranteedTailCallOpt) {
2552 if (IsTailCallConvention(CalleeCC) && CCMatch)
2557 // Look for obvious safe cases to perform tail call optimization that do not
2558 // require ABI changes. This is what gcc calls sibcall.
2560 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2561 // emit a special epilogue.
2562 if (RegInfo->needsStackRealignment(MF))
2565 // Also avoid sibcall optimization if either caller or callee uses struct
2566 // return semantics.
2567 if (isCalleeStructRet || isCallerStructRet)
2570 // An stdcall caller is expected to clean up its arguments; the callee
2571 // isn't going to do that.
2572 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2575 // Do not sibcall optimize vararg calls unless all arguments are passed via
2577 if (isVarArg && !Outs.empty()) {
2579 // Optimizing for varargs on Win64 is unlikely to be safe without
2580 // additional testing.
2581 if (Subtarget->isTargetWin64())
2584 SmallVector<CCValAssign, 16> ArgLocs;
2585 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2586 getTargetMachine(), ArgLocs, *DAG.getContext());
2588 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2589 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2590 if (!ArgLocs[i].isRegLoc())
2594 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2595 // Therefore if it's not used by the call it is not safe to optimize this into
2597 bool Unused = false;
2598 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2605 SmallVector<CCValAssign, 16> RVLocs;
2606 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2607 getTargetMachine(), RVLocs, *DAG.getContext());
2608 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2609 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2610 CCValAssign &VA = RVLocs[i];
2611 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2616 // If the calling conventions do not match, then we'd better make sure the
2617 // results are returned in the same way as what the caller expects.
2619 SmallVector<CCValAssign, 16> RVLocs1;
2620 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2621 getTargetMachine(), RVLocs1, *DAG.getContext());
2622 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2624 SmallVector<CCValAssign, 16> RVLocs2;
2625 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2626 getTargetMachine(), RVLocs2, *DAG.getContext());
2627 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2629 if (RVLocs1.size() != RVLocs2.size())
2631 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2632 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2634 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2636 if (RVLocs1[i].isRegLoc()) {
2637 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2640 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2646 // If the callee takes no arguments then go on to check the results of the
2648 if (!Outs.empty()) {
2649 // Check if stack adjustment is needed. For now, do not do this if any
2650 // argument is passed on the stack.
2651 SmallVector<CCValAssign, 16> ArgLocs;
2652 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2653 getTargetMachine(), ArgLocs, *DAG.getContext());
2655 // Allocate shadow area for Win64
2656 if (Subtarget->isTargetWin64()) {
2657 CCInfo.AllocateStack(32, 8);
2660 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2661 if (CCInfo.getNextStackOffset()) {
2662 MachineFunction &MF = DAG.getMachineFunction();
2663 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2666 // Check if the arguments are already laid out in the right way as
2667 // the caller's fixed stack objects.
2668 MachineFrameInfo *MFI = MF.getFrameInfo();
2669 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2670 const X86InstrInfo *TII =
2671 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2672 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2673 CCValAssign &VA = ArgLocs[i];
2674 SDValue Arg = OutVals[i];
2675 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2676 if (VA.getLocInfo() == CCValAssign::Indirect)
2678 if (!VA.isRegLoc()) {
2679 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2686 // If the tailcall address may be in a register, then make sure it's
2687 // possible to register allocate for it. In 32-bit, the call address can
2688 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2689 // callee-saved registers are restored. These happen to be the same
2690 // registers used to pass 'inreg' arguments so watch out for those.
2691 if (!Subtarget->is64Bit() &&
2692 !isa<GlobalAddressSDNode>(Callee) &&
2693 !isa<ExternalSymbolSDNode>(Callee)) {
2694 unsigned NumInRegs = 0;
2695 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2696 CCValAssign &VA = ArgLocs[i];
2699 unsigned Reg = VA.getLocReg();
2702 case X86::EAX: case X86::EDX: case X86::ECX:
2703 if (++NumInRegs == 3)
2715 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2716 return X86::createFastISel(funcInfo);
2720 //===----------------------------------------------------------------------===//
2721 // Other Lowering Hooks
2722 //===----------------------------------------------------------------------===//
2724 static bool MayFoldLoad(SDValue Op) {
2725 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2728 static bool MayFoldIntoStore(SDValue Op) {
2729 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2732 static bool isTargetShuffle(unsigned Opcode) {
2734 default: return false;
2735 case X86ISD::PSHUFD:
2736 case X86ISD::PSHUFHW:
2737 case X86ISD::PSHUFLW:
2738 case X86ISD::SHUFPD:
2739 case X86ISD::PALIGN:
2740 case X86ISD::SHUFPS:
2741 case X86ISD::MOVLHPS:
2742 case X86ISD::MOVLHPD:
2743 case X86ISD::MOVHLPS:
2744 case X86ISD::MOVLPS:
2745 case X86ISD::MOVLPD:
2746 case X86ISD::MOVSHDUP:
2747 case X86ISD::MOVSLDUP:
2748 case X86ISD::MOVDDUP:
2751 case X86ISD::UNPCKLPS:
2752 case X86ISD::UNPCKLPD:
2753 case X86ISD::VUNPCKLPS:
2754 case X86ISD::VUNPCKLPD:
2755 case X86ISD::VUNPCKLPSY:
2756 case X86ISD::VUNPCKLPDY:
2757 case X86ISD::PUNPCKLWD:
2758 case X86ISD::PUNPCKLBW:
2759 case X86ISD::PUNPCKLDQ:
2760 case X86ISD::PUNPCKLQDQ:
2761 case X86ISD::UNPCKHPS:
2762 case X86ISD::UNPCKHPD:
2763 case X86ISD::PUNPCKHWD:
2764 case X86ISD::PUNPCKHBW:
2765 case X86ISD::PUNPCKHDQ:
2766 case X86ISD::PUNPCKHQDQ:
2772 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2773 SDValue V1, SelectionDAG &DAG) {
2775 default: llvm_unreachable("Unknown x86 shuffle node");
2776 case X86ISD::MOVSHDUP:
2777 case X86ISD::MOVSLDUP:
2778 case X86ISD::MOVDDUP:
2779 return DAG.getNode(Opc, dl, VT, V1);
2785 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2786 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2788 default: llvm_unreachable("Unknown x86 shuffle node");
2789 case X86ISD::PSHUFD:
2790 case X86ISD::PSHUFHW:
2791 case X86ISD::PSHUFLW:
2792 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2798 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2799 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2801 default: llvm_unreachable("Unknown x86 shuffle node");
2802 case X86ISD::PALIGN:
2803 case X86ISD::SHUFPD:
2804 case X86ISD::SHUFPS:
2805 return DAG.getNode(Opc, dl, VT, V1, V2,
2806 DAG.getConstant(TargetMask, MVT::i8));
2811 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2812 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2814 default: llvm_unreachable("Unknown x86 shuffle node");
2815 case X86ISD::MOVLHPS:
2816 case X86ISD::MOVLHPD:
2817 case X86ISD::MOVHLPS:
2818 case X86ISD::MOVLPS:
2819 case X86ISD::MOVLPD:
2822 case X86ISD::UNPCKLPS:
2823 case X86ISD::UNPCKLPD:
2824 case X86ISD::VUNPCKLPS:
2825 case X86ISD::VUNPCKLPD:
2826 case X86ISD::VUNPCKLPSY:
2827 case X86ISD::VUNPCKLPDY:
2828 case X86ISD::PUNPCKLWD:
2829 case X86ISD::PUNPCKLBW:
2830 case X86ISD::PUNPCKLDQ:
2831 case X86ISD::PUNPCKLQDQ:
2832 case X86ISD::UNPCKHPS:
2833 case X86ISD::UNPCKHPD:
2834 case X86ISD::PUNPCKHWD:
2835 case X86ISD::PUNPCKHBW:
2836 case X86ISD::PUNPCKHDQ:
2837 case X86ISD::PUNPCKHQDQ:
2838 return DAG.getNode(Opc, dl, VT, V1, V2);
2843 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2844 MachineFunction &MF = DAG.getMachineFunction();
2845 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2846 int ReturnAddrIndex = FuncInfo->getRAIndex();
2848 if (ReturnAddrIndex == 0) {
2849 // Set up a frame object for the return address.
2850 uint64_t SlotSize = TD->getPointerSize();
2851 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2853 FuncInfo->setRAIndex(ReturnAddrIndex);
2856 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2860 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2861 bool hasSymbolicDisplacement) {
2862 // Offset should fit into 32 bit immediate field.
2863 if (!isInt<32>(Offset))
2866 // If we don't have a symbolic displacement - we don't have any extra
2868 if (!hasSymbolicDisplacement)
2871 // FIXME: Some tweaks might be needed for medium code model.
2872 if (M != CodeModel::Small && M != CodeModel::Kernel)
2875 // For small code model we assume that latest object is 16MB before end of 31
2876 // bits boundary. We may also accept pretty large negative constants knowing
2877 // that all objects are in the positive half of address space.
2878 if (M == CodeModel::Small && Offset < 16*1024*1024)
2881 // For kernel code model we know that all object resist in the negative half
2882 // of 32bits address space. We may not accept negative offsets, since they may
2883 // be just off and we may accept pretty large positive ones.
2884 if (M == CodeModel::Kernel && Offset > 0)
2890 /// isCalleePop - Determines whether the callee is required to pop its
2891 /// own arguments. Callee pop is necessary to support tail calls.
2892 bool X86::isCalleePop(CallingConv::ID CallingConv,
2893 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2897 switch (CallingConv) {
2900 case CallingConv::X86_StdCall:
2902 case CallingConv::X86_FastCall:
2904 case CallingConv::X86_ThisCall:
2906 case CallingConv::Fast:
2908 case CallingConv::GHC:
2913 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2914 /// specific condition code, returning the condition code and the LHS/RHS of the
2915 /// comparison to make.
2916 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2917 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2919 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2920 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2921 // X > -1 -> X == 0, jump !sign.
2922 RHS = DAG.getConstant(0, RHS.getValueType());
2923 return X86::COND_NS;
2924 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2925 // X < 0 -> X == 0, jump on sign.
2927 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2929 RHS = DAG.getConstant(0, RHS.getValueType());
2930 return X86::COND_LE;
2934 switch (SetCCOpcode) {
2935 default: llvm_unreachable("Invalid integer condition!");
2936 case ISD::SETEQ: return X86::COND_E;
2937 case ISD::SETGT: return X86::COND_G;
2938 case ISD::SETGE: return X86::COND_GE;
2939 case ISD::SETLT: return X86::COND_L;
2940 case ISD::SETLE: return X86::COND_LE;
2941 case ISD::SETNE: return X86::COND_NE;
2942 case ISD::SETULT: return X86::COND_B;
2943 case ISD::SETUGT: return X86::COND_A;
2944 case ISD::SETULE: return X86::COND_BE;
2945 case ISD::SETUGE: return X86::COND_AE;
2949 // First determine if it is required or is profitable to flip the operands.
2951 // If LHS is a foldable load, but RHS is not, flip the condition.
2952 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2953 !ISD::isNON_EXTLoad(RHS.getNode())) {
2954 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2955 std::swap(LHS, RHS);
2958 switch (SetCCOpcode) {
2964 std::swap(LHS, RHS);
2968 // On a floating point condition, the flags are set as follows:
2970 // 0 | 0 | 0 | X > Y
2971 // 0 | 0 | 1 | X < Y
2972 // 1 | 0 | 0 | X == Y
2973 // 1 | 1 | 1 | unordered
2974 switch (SetCCOpcode) {
2975 default: llvm_unreachable("Condcode should be pre-legalized away");
2977 case ISD::SETEQ: return X86::COND_E;
2978 case ISD::SETOLT: // flipped
2980 case ISD::SETGT: return X86::COND_A;
2981 case ISD::SETOLE: // flipped
2983 case ISD::SETGE: return X86::COND_AE;
2984 case ISD::SETUGT: // flipped
2986 case ISD::SETLT: return X86::COND_B;
2987 case ISD::SETUGE: // flipped
2989 case ISD::SETLE: return X86::COND_BE;
2991 case ISD::SETNE: return X86::COND_NE;
2992 case ISD::SETUO: return X86::COND_P;
2993 case ISD::SETO: return X86::COND_NP;
2995 case ISD::SETUNE: return X86::COND_INVALID;
2999 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3000 /// code. Current x86 isa includes the following FP cmov instructions:
3001 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3002 static bool hasFPCMov(unsigned X86CC) {
3018 /// isFPImmLegal - Returns true if the target can instruction select the
3019 /// specified FP immediate natively. If false, the legalizer will
3020 /// materialize the FP immediate as a load from a constant pool.
3021 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3022 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3023 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3029 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3030 /// the specified range (L, H].
3031 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3032 return (Val < 0) || (Val >= Low && Val < Hi);
3035 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3036 /// specified value.
3037 static bool isUndefOrEqual(int Val, int CmpVal) {
3038 if (Val < 0 || Val == CmpVal)
3043 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3044 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3045 /// the second operand.
3046 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3047 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3048 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3049 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3050 return (Mask[0] < 2 && Mask[1] < 2);
3054 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3055 SmallVector<int, 8> M;
3057 return ::isPSHUFDMask(M, N->getValueType(0));
3060 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3061 /// is suitable for input to PSHUFHW.
3062 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3063 if (VT != MVT::v8i16)
3066 // Lower quadword copied in order or undef.
3067 for (int i = 0; i != 4; ++i)
3068 if (Mask[i] >= 0 && Mask[i] != i)
3071 // Upper quadword shuffled.
3072 for (int i = 4; i != 8; ++i)
3073 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3079 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3080 SmallVector<int, 8> M;
3082 return ::isPSHUFHWMask(M, N->getValueType(0));
3085 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3086 /// is suitable for input to PSHUFLW.
3087 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3088 if (VT != MVT::v8i16)
3091 // Upper quadword copied in order.
3092 for (int i = 4; i != 8; ++i)
3093 if (Mask[i] >= 0 && Mask[i] != i)
3096 // Lower quadword shuffled.
3097 for (int i = 0; i != 4; ++i)
3104 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3105 SmallVector<int, 8> M;
3107 return ::isPSHUFLWMask(M, N->getValueType(0));
3110 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3111 /// is suitable for input to PALIGNR.
3112 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3114 int i, e = VT.getVectorNumElements();
3116 // Do not handle v2i64 / v2f64 shuffles with palignr.
3117 if (e < 4 || !hasSSSE3)
3120 for (i = 0; i != e; ++i)
3124 // All undef, not a palignr.
3128 // Determine if it's ok to perform a palignr with only the LHS, since we
3129 // don't have access to the actual shuffle elements to see if RHS is undef.
3130 bool Unary = Mask[i] < (int)e;
3131 bool NeedsUnary = false;
3133 int s = Mask[i] - i;
3135 // Check the rest of the elements to see if they are consecutive.
3136 for (++i; i != e; ++i) {
3141 Unary = Unary && (m < (int)e);
3142 NeedsUnary = NeedsUnary || (m < s);
3144 if (NeedsUnary && !Unary)
3146 if (Unary && m != ((s+i) & (e-1)))
3148 if (!Unary && m != (s+i))
3154 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3155 SmallVector<int, 8> M;
3157 return ::isPALIGNRMask(M, N->getValueType(0), true);
3160 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3161 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3162 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3163 int NumElems = VT.getVectorNumElements();
3164 if (NumElems != 2 && NumElems != 4)
3167 int Half = NumElems / 2;
3168 for (int i = 0; i < Half; ++i)
3169 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3171 for (int i = Half; i < NumElems; ++i)
3172 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3178 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3179 SmallVector<int, 8> M;
3181 return ::isSHUFPMask(M, N->getValueType(0));
3184 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3185 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3186 /// half elements to come from vector 1 (which would equal the dest.) and
3187 /// the upper half to come from vector 2.
3188 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3189 int NumElems = VT.getVectorNumElements();
3191 if (NumElems != 2 && NumElems != 4)
3194 int Half = NumElems / 2;
3195 for (int i = 0; i < Half; ++i)
3196 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3198 for (int i = Half; i < NumElems; ++i)
3199 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3204 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3205 SmallVector<int, 8> M;
3207 return isCommutedSHUFPMask(M, N->getValueType(0));
3210 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3211 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3212 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3213 if (N->getValueType(0).getVectorNumElements() != 4)
3216 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3217 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3218 isUndefOrEqual(N->getMaskElt(1), 7) &&
3219 isUndefOrEqual(N->getMaskElt(2), 2) &&
3220 isUndefOrEqual(N->getMaskElt(3), 3);
3223 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3224 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3226 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3227 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3232 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3233 isUndefOrEqual(N->getMaskElt(1), 3) &&
3234 isUndefOrEqual(N->getMaskElt(2), 2) &&
3235 isUndefOrEqual(N->getMaskElt(3), 3);
3238 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3239 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3240 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3241 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3243 if (NumElems != 2 && NumElems != 4)
3246 for (unsigned i = 0; i < NumElems/2; ++i)
3247 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3250 for (unsigned i = NumElems/2; i < NumElems; ++i)
3251 if (!isUndefOrEqual(N->getMaskElt(i), i))
3257 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3258 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3259 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3260 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3262 if ((NumElems != 2 && NumElems != 4)
3263 || N->getValueType(0).getSizeInBits() > 128)
3266 for (unsigned i = 0; i < NumElems/2; ++i)
3267 if (!isUndefOrEqual(N->getMaskElt(i), i))
3270 for (unsigned i = 0; i < NumElems/2; ++i)
3271 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3277 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3278 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3279 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3280 bool V2IsSplat = false) {
3281 int NumElts = VT.getVectorNumElements();
3282 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3285 // Handle vector lengths > 128 bits. Define a "section" as a set of
3286 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3288 unsigned NumSections = VT.getSizeInBits() / 128;
3289 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3290 unsigned NumSectionElts = NumElts / NumSections;
3293 unsigned End = NumSectionElts;
3294 for (unsigned s = 0; s < NumSections; ++s) {
3295 for (unsigned i = Start, j = s * NumSectionElts;
3299 int BitI1 = Mask[i+1];
3300 if (!isUndefOrEqual(BitI, j))
3303 if (!isUndefOrEqual(BitI1, NumElts))
3306 if (!isUndefOrEqual(BitI1, j + NumElts))
3310 // Process the next 128 bits.
3311 Start += NumSectionElts;
3312 End += NumSectionElts;
3318 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3319 SmallVector<int, 8> M;
3321 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3324 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3325 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3326 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3327 bool V2IsSplat = false) {
3328 int NumElts = VT.getVectorNumElements();
3329 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3332 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3334 int BitI1 = Mask[i+1];
3335 if (!isUndefOrEqual(BitI, j + NumElts/2))
3338 if (isUndefOrEqual(BitI1, NumElts))
3341 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3348 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3349 SmallVector<int, 8> M;
3351 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3354 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3355 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3357 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3358 int NumElems = VT.getVectorNumElements();
3359 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3362 // Handle vector lengths > 128 bits. Define a "section" as a set of
3363 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3365 unsigned NumSections = VT.getSizeInBits() / 128;
3366 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3367 unsigned NumSectionElts = NumElems / NumSections;
3369 for (unsigned s = 0; s < NumSections; ++s) {
3370 for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3371 i != NumSectionElts * (s + 1);
3374 int BitI1 = Mask[i+1];
3376 if (!isUndefOrEqual(BitI, j))
3378 if (!isUndefOrEqual(BitI1, j))
3386 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3387 SmallVector<int, 8> M;
3389 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3392 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3393 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3395 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3396 int NumElems = VT.getVectorNumElements();
3397 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3400 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3402 int BitI1 = Mask[i+1];
3403 if (!isUndefOrEqual(BitI, j))
3405 if (!isUndefOrEqual(BitI1, j))
3411 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3412 SmallVector<int, 8> M;
3414 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3417 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3418 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3419 /// MOVSD, and MOVD, i.e. setting the lowest element.
3420 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3421 if (VT.getVectorElementType().getSizeInBits() < 32)
3424 int NumElts = VT.getVectorNumElements();
3426 if (!isUndefOrEqual(Mask[0], NumElts))
3429 for (int i = 1; i < NumElts; ++i)
3430 if (!isUndefOrEqual(Mask[i], i))
3436 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3437 SmallVector<int, 8> M;
3439 return ::isMOVLMask(M, N->getValueType(0));
3442 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3443 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3444 /// element of vector 2 and the other elements to come from vector 1 in order.
3445 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3446 bool V2IsSplat = false, bool V2IsUndef = false) {
3447 int NumOps = VT.getVectorNumElements();
3448 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3451 if (!isUndefOrEqual(Mask[0], 0))
3454 for (int i = 1; i < NumOps; ++i)
3455 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3456 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3457 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3463 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3464 bool V2IsUndef = false) {
3465 SmallVector<int, 8> M;
3467 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3470 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3471 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3472 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3473 if (N->getValueType(0).getVectorNumElements() != 4)
3476 // Expect 1, 1, 3, 3
3477 for (unsigned i = 0; i < 2; ++i) {
3478 int Elt = N->getMaskElt(i);
3479 if (Elt >= 0 && Elt != 1)
3484 for (unsigned i = 2; i < 4; ++i) {
3485 int Elt = N->getMaskElt(i);
3486 if (Elt >= 0 && Elt != 3)
3491 // Don't use movshdup if it can be done with a shufps.
3492 // FIXME: verify that matching u, u, 3, 3 is what we want.
3496 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3497 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3498 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3499 if (N->getValueType(0).getVectorNumElements() != 4)
3502 // Expect 0, 0, 2, 2
3503 for (unsigned i = 0; i < 2; ++i)
3504 if (N->getMaskElt(i) > 0)
3508 for (unsigned i = 2; i < 4; ++i) {
3509 int Elt = N->getMaskElt(i);
3510 if (Elt >= 0 && Elt != 2)
3515 // Don't use movsldup if it can be done with a shufps.
3519 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3520 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3521 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3522 int e = N->getValueType(0).getVectorNumElements() / 2;
3524 for (int i = 0; i < e; ++i)
3525 if (!isUndefOrEqual(N->getMaskElt(i), i))
3527 for (int i = 0; i < e; ++i)
3528 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3533 /// isVEXTRACTF128Index - Return true if the specified
3534 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3535 /// suitable for input to VEXTRACTF128.
3536 bool X86::isVEXTRACTF128Index(SDNode *N) {
3537 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3540 // The index should be aligned on a 128-bit boundary.
3542 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3544 unsigned VL = N->getValueType(0).getVectorNumElements();
3545 unsigned VBits = N->getValueType(0).getSizeInBits();
3546 unsigned ElSize = VBits / VL;
3547 bool Result = (Index * ElSize) % 128 == 0;
3552 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3553 /// operand specifies a subvector insert that is suitable for input to
3555 bool X86::isVINSERTF128Index(SDNode *N) {
3556 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3559 // The index should be aligned on a 128-bit boundary.
3561 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3563 unsigned VL = N->getValueType(0).getVectorNumElements();
3564 unsigned VBits = N->getValueType(0).getSizeInBits();
3565 unsigned ElSize = VBits / VL;
3566 bool Result = (Index * ElSize) % 128 == 0;
3571 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3572 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3573 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3574 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3575 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3577 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3579 for (int i = 0; i < NumOperands; ++i) {
3580 int Val = SVOp->getMaskElt(NumOperands-i-1);
3581 if (Val < 0) Val = 0;
3582 if (Val >= NumOperands) Val -= NumOperands;
3584 if (i != NumOperands - 1)
3590 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3591 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3592 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3593 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3595 // 8 nodes, but we only care about the last 4.
3596 for (unsigned i = 7; i >= 4; --i) {
3597 int Val = SVOp->getMaskElt(i);
3606 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3607 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3608 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3609 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3611 // 8 nodes, but we only care about the first 4.
3612 for (int i = 3; i >= 0; --i) {
3613 int Val = SVOp->getMaskElt(i);
3622 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3623 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3624 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3625 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3626 EVT VVT = N->getValueType(0);
3627 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3631 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3632 Val = SVOp->getMaskElt(i);
3636 return (Val - i) * EltSize;
3639 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3640 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3642 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3643 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3644 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3647 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3649 EVT VecVT = N->getOperand(0).getValueType();
3650 EVT ElVT = VecVT.getVectorElementType();
3652 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3654 return Index / NumElemsPerChunk;
3657 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3658 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3660 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3661 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3662 llvm_unreachable("Illegal insert subvector for VINSERTF128");
3665 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3667 EVT VecVT = N->getValueType(0);
3668 EVT ElVT = VecVT.getVectorElementType();
3670 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3672 return Index / NumElemsPerChunk;
3675 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3677 bool X86::isZeroNode(SDValue Elt) {
3678 return ((isa<ConstantSDNode>(Elt) &&
3679 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3680 (isa<ConstantFPSDNode>(Elt) &&
3681 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3684 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3685 /// their permute mask.
3686 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3687 SelectionDAG &DAG) {
3688 EVT VT = SVOp->getValueType(0);
3689 unsigned NumElems = VT.getVectorNumElements();
3690 SmallVector<int, 8> MaskVec;
3692 for (unsigned i = 0; i != NumElems; ++i) {
3693 int idx = SVOp->getMaskElt(i);
3695 MaskVec.push_back(idx);
3696 else if (idx < (int)NumElems)
3697 MaskVec.push_back(idx + NumElems);
3699 MaskVec.push_back(idx - NumElems);
3701 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3702 SVOp->getOperand(0), &MaskVec[0]);
3705 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3706 /// the two vector operands have swapped position.
3707 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3708 unsigned NumElems = VT.getVectorNumElements();
3709 for (unsigned i = 0; i != NumElems; ++i) {
3713 else if (idx < (int)NumElems)
3714 Mask[i] = idx + NumElems;
3716 Mask[i] = idx - NumElems;
3720 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3721 /// match movhlps. The lower half elements should come from upper half of
3722 /// V1 (and in order), and the upper half elements should come from the upper
3723 /// half of V2 (and in order).
3724 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3725 if (Op->getValueType(0).getVectorNumElements() != 4)
3727 for (unsigned i = 0, e = 2; i != e; ++i)
3728 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3730 for (unsigned i = 2; i != 4; ++i)
3731 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3736 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3737 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3739 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3740 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3742 N = N->getOperand(0).getNode();
3743 if (!ISD::isNON_EXTLoad(N))
3746 *LD = cast<LoadSDNode>(N);
3750 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3751 /// match movlp{s|d}. The lower half elements should come from lower half of
3752 /// V1 (and in order), and the upper half elements should come from the upper
3753 /// half of V2 (and in order). And since V1 will become the source of the
3754 /// MOVLP, it must be either a vector load or a scalar load to vector.
3755 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3756 ShuffleVectorSDNode *Op) {
3757 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3759 // Is V2 is a vector load, don't do this transformation. We will try to use
3760 // load folding shufps op.
3761 if (ISD::isNON_EXTLoad(V2))
3764 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3766 if (NumElems != 2 && NumElems != 4)
3768 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3769 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3771 for (unsigned i = NumElems/2; i != NumElems; ++i)
3772 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3777 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3779 static bool isSplatVector(SDNode *N) {
3780 if (N->getOpcode() != ISD::BUILD_VECTOR)
3783 SDValue SplatValue = N->getOperand(0);
3784 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3785 if (N->getOperand(i) != SplatValue)
3790 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3791 /// to an zero vector.
3792 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3793 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3794 SDValue V1 = N->getOperand(0);
3795 SDValue V2 = N->getOperand(1);
3796 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3797 for (unsigned i = 0; i != NumElems; ++i) {
3798 int Idx = N->getMaskElt(i);
3799 if (Idx >= (int)NumElems) {
3800 unsigned Opc = V2.getOpcode();
3801 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3803 if (Opc != ISD::BUILD_VECTOR ||
3804 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3806 } else if (Idx >= 0) {
3807 unsigned Opc = V1.getOpcode();
3808 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3810 if (Opc != ISD::BUILD_VECTOR ||
3811 !X86::isZeroNode(V1.getOperand(Idx)))
3818 /// getZeroVector - Returns a vector of specified type with all zero elements.
3820 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3822 assert(VT.isVector() && "Expected a vector type");
3824 // Always build SSE zero vectors as <4 x i32> bitcasted
3825 // to their dest type. This ensures they get CSE'd.
3827 if (VT.getSizeInBits() == 128) { // SSE
3828 if (HasSSE2) { // SSE2
3829 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3830 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3832 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3833 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3835 } else if (VT.getSizeInBits() == 256) { // AVX
3836 // 256-bit logic and arithmetic instructions in AVX are
3837 // all floating-point, no support for integer ops. Default
3838 // to emitting fp zeroed vectors then.
3839 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3840 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3841 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3843 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3846 /// getOnesVector - Returns a vector of specified type with all bits set.
3848 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3849 assert(VT.isVector() && "Expected a vector type");
3851 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3852 // type. This ensures they get CSE'd.
3853 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3855 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3856 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3860 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3861 /// that point to V2 points to its first element.
3862 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3863 EVT VT = SVOp->getValueType(0);
3864 unsigned NumElems = VT.getVectorNumElements();
3866 bool Changed = false;
3867 SmallVector<int, 8> MaskVec;
3868 SVOp->getMask(MaskVec);
3870 for (unsigned i = 0; i != NumElems; ++i) {
3871 if (MaskVec[i] > (int)NumElems) {
3872 MaskVec[i] = NumElems;
3877 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3878 SVOp->getOperand(1), &MaskVec[0]);
3879 return SDValue(SVOp, 0);
3882 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3883 /// operation of specified width.
3884 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3886 unsigned NumElems = VT.getVectorNumElements();
3887 SmallVector<int, 8> Mask;
3888 Mask.push_back(NumElems);
3889 for (unsigned i = 1; i != NumElems; ++i)
3891 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3894 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3895 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3897 unsigned NumElems = VT.getVectorNumElements();
3898 SmallVector<int, 8> Mask;
3899 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3901 Mask.push_back(i + NumElems);
3903 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3906 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3907 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3909 unsigned NumElems = VT.getVectorNumElements();
3910 unsigned Half = NumElems/2;
3911 SmallVector<int, 8> Mask;
3912 for (unsigned i = 0; i != Half; ++i) {
3913 Mask.push_back(i + Half);
3914 Mask.push_back(i + NumElems + Half);
3916 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3919 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3920 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3921 EVT PVT = MVT::v4f32;
3922 EVT VT = SV->getValueType(0);
3923 DebugLoc dl = SV->getDebugLoc();
3924 SDValue V1 = SV->getOperand(0);
3925 int NumElems = VT.getVectorNumElements();
3926 int EltNo = SV->getSplatIndex();
3928 // unpack elements to the correct location
3929 while (NumElems > 4) {
3930 if (EltNo < NumElems/2) {
3931 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3933 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3934 EltNo -= NumElems/2;
3939 // Perform the splat.
3940 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3941 V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3942 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3943 return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3946 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3947 /// vector of zero or undef vector. This produces a shuffle where the low
3948 /// element of V2 is swizzled into the zero/undef vector, landing at element
3949 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3950 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3951 bool isZero, bool HasSSE2,
3952 SelectionDAG &DAG) {
3953 EVT VT = V2.getValueType();
3955 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3956 unsigned NumElems = VT.getVectorNumElements();
3957 SmallVector<int, 16> MaskVec;
3958 for (unsigned i = 0; i != NumElems; ++i)
3959 // If this is the insertion idx, put the low elt of V2 here.
3960 MaskVec.push_back(i == Idx ? NumElems : i);
3961 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3964 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3965 /// element of the result of the vector shuffle.
3966 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3969 return SDValue(); // Limit search depth.
3971 SDValue V = SDValue(N, 0);
3972 EVT VT = V.getValueType();
3973 unsigned Opcode = V.getOpcode();
3975 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3976 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3977 Index = SV->getMaskElt(Index);
3980 return DAG.getUNDEF(VT.getVectorElementType());
3982 int NumElems = VT.getVectorNumElements();
3983 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3984 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3987 // Recurse into target specific vector shuffles to find scalars.
3988 if (isTargetShuffle(Opcode)) {
3989 int NumElems = VT.getVectorNumElements();
3990 SmallVector<unsigned, 16> ShuffleMask;
3994 case X86ISD::SHUFPS:
3995 case X86ISD::SHUFPD:
3996 ImmN = N->getOperand(N->getNumOperands()-1);
3997 DecodeSHUFPSMask(NumElems,
3998 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4001 case X86ISD::PUNPCKHBW:
4002 case X86ISD::PUNPCKHWD:
4003 case X86ISD::PUNPCKHDQ:
4004 case X86ISD::PUNPCKHQDQ:
4005 DecodePUNPCKHMask(NumElems, ShuffleMask);
4007 case X86ISD::UNPCKHPS:
4008 case X86ISD::UNPCKHPD:
4009 DecodeUNPCKHPMask(NumElems, ShuffleMask);
4011 case X86ISD::PUNPCKLBW:
4012 case X86ISD::PUNPCKLWD:
4013 case X86ISD::PUNPCKLDQ:
4014 case X86ISD::PUNPCKLQDQ:
4015 DecodePUNPCKLMask(VT, ShuffleMask);
4017 case X86ISD::UNPCKLPS:
4018 case X86ISD::UNPCKLPD:
4019 case X86ISD::VUNPCKLPS:
4020 case X86ISD::VUNPCKLPD:
4021 case X86ISD::VUNPCKLPSY:
4022 case X86ISD::VUNPCKLPDY:
4023 DecodeUNPCKLPMask(VT, ShuffleMask);
4025 case X86ISD::MOVHLPS:
4026 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4028 case X86ISD::MOVLHPS:
4029 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4031 case X86ISD::PSHUFD:
4032 ImmN = N->getOperand(N->getNumOperands()-1);
4033 DecodePSHUFMask(NumElems,
4034 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4037 case X86ISD::PSHUFHW:
4038 ImmN = N->getOperand(N->getNumOperands()-1);
4039 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4042 case X86ISD::PSHUFLW:
4043 ImmN = N->getOperand(N->getNumOperands()-1);
4044 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4048 case X86ISD::MOVSD: {
4049 // The index 0 always comes from the first element of the second source,
4050 // this is why MOVSS and MOVSD are used in the first place. The other
4051 // elements come from the other positions of the first source vector.
4052 unsigned OpNum = (Index == 0) ? 1 : 0;
4053 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4057 assert("not implemented for target shuffle node");
4061 Index = ShuffleMask[Index];
4063 return DAG.getUNDEF(VT.getVectorElementType());
4065 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4066 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4070 // Actual nodes that may contain scalar elements
4071 if (Opcode == ISD::BITCAST) {
4072 V = V.getOperand(0);
4073 EVT SrcVT = V.getValueType();
4074 unsigned NumElems = VT.getVectorNumElements();
4076 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4080 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4081 return (Index == 0) ? V.getOperand(0)
4082 : DAG.getUNDEF(VT.getVectorElementType());
4084 if (V.getOpcode() == ISD::BUILD_VECTOR)
4085 return V.getOperand(Index);
4090 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4091 /// shuffle operation which come from a consecutively from a zero. The
4092 /// search can start in two different directions, from left or right.
4094 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4095 bool ZerosFromLeft, SelectionDAG &DAG) {
4098 while (i < NumElems) {
4099 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4100 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4101 if (!(Elt.getNode() &&
4102 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4110 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4111 /// MaskE correspond consecutively to elements from one of the vector operands,
4112 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4114 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4115 int OpIdx, int NumElems, unsigned &OpNum) {
4116 bool SeenV1 = false;
4117 bool SeenV2 = false;
4119 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4120 int Idx = SVOp->getMaskElt(i);
4121 // Ignore undef indicies
4130 // Only accept consecutive elements from the same vector
4131 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4135 OpNum = SeenV1 ? 0 : 1;
4139 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4140 /// logical left shift of a vector.
4141 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4142 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4143 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4144 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4145 false /* check zeros from right */, DAG);
4151 // Considering the elements in the mask that are not consecutive zeros,
4152 // check if they consecutively come from only one of the source vectors.
4154 // V1 = {X, A, B, C} 0
4156 // vector_shuffle V1, V2 <1, 2, 3, X>
4158 if (!isShuffleMaskConsecutive(SVOp,
4159 0, // Mask Start Index
4160 NumElems-NumZeros-1, // Mask End Index
4161 NumZeros, // Where to start looking in the src vector
4162 NumElems, // Number of elements in vector
4163 OpSrc)) // Which source operand ?
4168 ShVal = SVOp->getOperand(OpSrc);
4172 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4173 /// logical left shift of a vector.
4174 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4175 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4176 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4177 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4178 true /* check zeros from left */, DAG);
4184 // Considering the elements in the mask that are not consecutive zeros,
4185 // check if they consecutively come from only one of the source vectors.
4187 // 0 { A, B, X, X } = V2
4189 // vector_shuffle V1, V2 <X, X, 4, 5>
4191 if (!isShuffleMaskConsecutive(SVOp,
4192 NumZeros, // Mask Start Index
4193 NumElems-1, // Mask End Index
4194 0, // Where to start looking in the src vector
4195 NumElems, // Number of elements in vector
4196 OpSrc)) // Which source operand ?
4201 ShVal = SVOp->getOperand(OpSrc);
4205 /// isVectorShift - Returns true if the shuffle can be implemented as a
4206 /// logical left or right shift of a vector.
4207 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4208 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4209 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4210 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4216 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4218 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4219 unsigned NumNonZero, unsigned NumZero,
4221 const TargetLowering &TLI) {
4225 DebugLoc dl = Op.getDebugLoc();
4228 for (unsigned i = 0; i < 16; ++i) {
4229 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4230 if (ThisIsNonZero && First) {
4232 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4234 V = DAG.getUNDEF(MVT::v8i16);
4239 SDValue ThisElt(0, 0), LastElt(0, 0);
4240 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4241 if (LastIsNonZero) {
4242 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4243 MVT::i16, Op.getOperand(i-1));
4245 if (ThisIsNonZero) {
4246 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4247 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4248 ThisElt, DAG.getConstant(8, MVT::i8));
4250 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4254 if (ThisElt.getNode())
4255 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4256 DAG.getIntPtrConstant(i/2));
4260 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4263 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4265 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4266 unsigned NumNonZero, unsigned NumZero,
4268 const TargetLowering &TLI) {
4272 DebugLoc dl = Op.getDebugLoc();
4275 for (unsigned i = 0; i < 8; ++i) {
4276 bool isNonZero = (NonZeros & (1 << i)) != 0;
4280 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4282 V = DAG.getUNDEF(MVT::v8i16);
4285 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4286 MVT::v8i16, V, Op.getOperand(i),
4287 DAG.getIntPtrConstant(i));
4294 /// getVShift - Return a vector logical shift node.
4296 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4297 unsigned NumBits, SelectionDAG &DAG,
4298 const TargetLowering &TLI, DebugLoc dl) {
4299 EVT ShVT = MVT::v2i64;
4300 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4301 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4302 return DAG.getNode(ISD::BITCAST, dl, VT,
4303 DAG.getNode(Opc, dl, ShVT, SrcOp,
4304 DAG.getConstant(NumBits,
4305 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4309 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4310 SelectionDAG &DAG) const {
4312 // Check if the scalar load can be widened into a vector load. And if
4313 // the address is "base + cst" see if the cst can be "absorbed" into
4314 // the shuffle mask.
4315 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4316 SDValue Ptr = LD->getBasePtr();
4317 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4319 EVT PVT = LD->getValueType(0);
4320 if (PVT != MVT::i32 && PVT != MVT::f32)
4325 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4326 FI = FINode->getIndex();
4328 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4329 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4330 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4331 Offset = Ptr.getConstantOperandVal(1);
4332 Ptr = Ptr.getOperand(0);
4337 SDValue Chain = LD->getChain();
4338 // Make sure the stack object alignment is at least 16.
4339 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4340 if (DAG.InferPtrAlignment(Ptr) < 16) {
4341 if (MFI->isFixedObjectIndex(FI)) {
4342 // Can't change the alignment. FIXME: It's possible to compute
4343 // the exact stack offset and reference FI + adjust offset instead.
4344 // If someone *really* cares about this. That's the way to implement it.
4347 MFI->setObjectAlignment(FI, 16);
4351 // (Offset % 16) must be multiple of 4. Then address is then
4352 // Ptr + (Offset & ~15).
4355 if ((Offset % 16) & 3)
4357 int64_t StartOffset = Offset & ~15;
4359 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4360 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4362 int EltNo = (Offset - StartOffset) >> 2;
4363 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4364 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4365 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4366 LD->getPointerInfo().getWithOffset(StartOffset),
4368 // Canonicalize it to a v4i32 shuffle.
4369 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4370 return DAG.getNode(ISD::BITCAST, dl, VT,
4371 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4372 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4378 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4379 /// vector of type 'VT', see if the elements can be replaced by a single large
4380 /// load which has the same value as a build_vector whose operands are 'elts'.
4382 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4384 /// FIXME: we'd also like to handle the case where the last elements are zero
4385 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4386 /// There's even a handy isZeroNode for that purpose.
4387 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4388 DebugLoc &DL, SelectionDAG &DAG) {
4389 EVT EltVT = VT.getVectorElementType();
4390 unsigned NumElems = Elts.size();
4392 LoadSDNode *LDBase = NULL;
4393 unsigned LastLoadedElt = -1U;
4395 // For each element in the initializer, see if we've found a load or an undef.
4396 // If we don't find an initial load element, or later load elements are
4397 // non-consecutive, bail out.
4398 for (unsigned i = 0; i < NumElems; ++i) {
4399 SDValue Elt = Elts[i];
4401 if (!Elt.getNode() ||
4402 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4405 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4407 LDBase = cast<LoadSDNode>(Elt.getNode());
4411 if (Elt.getOpcode() == ISD::UNDEF)
4414 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4415 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4420 // If we have found an entire vector of loads and undefs, then return a large
4421 // load of the entire vector width starting at the base pointer. If we found
4422 // consecutive loads for the low half, generate a vzext_load node.
4423 if (LastLoadedElt == NumElems - 1) {
4424 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4425 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4426 LDBase->getPointerInfo(),
4427 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4428 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4429 LDBase->getPointerInfo(),
4430 LDBase->isVolatile(), LDBase->isNonTemporal(),
4431 LDBase->getAlignment());
4432 } else if (NumElems == 4 && LastLoadedElt == 1) {
4433 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4434 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4435 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4437 LDBase->getMemOperand());
4438 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4444 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4445 DebugLoc dl = Op.getDebugLoc();
4447 EVT VT = Op.getValueType();
4448 EVT ExtVT = VT.getVectorElementType();
4450 unsigned NumElems = Op.getNumOperands();
4452 // For AVX-length vectors, build the individual 128-bit pieces and
4453 // use shuffles to put them in place.
4454 if (VT.getSizeInBits() > 256 &&
4455 Subtarget->hasAVX() &&
4456 !ISD::isBuildVectorAllZeros(Op.getNode())) {
4457 SmallVector<SDValue, 8> V;
4459 for (unsigned i = 0; i < NumElems; ++i) {
4460 V[i] = Op.getOperand(i);
4463 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4465 // Build the lower subvector.
4466 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4467 // Build the upper subvector.
4468 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4471 return ConcatVectors(Lower, Upper, DAG);
4474 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4475 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4476 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4477 // is present, so AllOnes is ignored.
4478 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4479 (Op.getValueType().getSizeInBits() != 256 &&
4480 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4481 // Canonicalize this to <4 x i32> (SSE) to
4482 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4483 // eliminated on x86-32 hosts.
4484 if (Op.getValueType() == MVT::v4i32)
4487 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4488 return getOnesVector(Op.getValueType(), DAG, dl);
4489 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4492 unsigned EVTBits = ExtVT.getSizeInBits();
4494 unsigned NumZero = 0;
4495 unsigned NumNonZero = 0;
4496 unsigned NonZeros = 0;
4497 bool IsAllConstants = true;
4498 SmallSet<SDValue, 8> Values;
4499 for (unsigned i = 0; i < NumElems; ++i) {
4500 SDValue Elt = Op.getOperand(i);
4501 if (Elt.getOpcode() == ISD::UNDEF)
4504 if (Elt.getOpcode() != ISD::Constant &&
4505 Elt.getOpcode() != ISD::ConstantFP)
4506 IsAllConstants = false;
4507 if (X86::isZeroNode(Elt))
4510 NonZeros |= (1 << i);
4515 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4516 if (NumNonZero == 0)
4517 return DAG.getUNDEF(VT);
4519 // Special case for single non-zero, non-undef, element.
4520 if (NumNonZero == 1) {
4521 unsigned Idx = CountTrailingZeros_32(NonZeros);
4522 SDValue Item = Op.getOperand(Idx);
4524 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4525 // the value are obviously zero, truncate the value to i32 and do the
4526 // insertion that way. Only do this if the value is non-constant or if the
4527 // value is a constant being inserted into element 0. It is cheaper to do
4528 // a constant pool load than it is to do a movd + shuffle.
4529 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4530 (!IsAllConstants || Idx == 0)) {
4531 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4533 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4534 EVT VecVT = MVT::v4i32;
4535 unsigned VecElts = 4;
4537 // Truncate the value (which may itself be a constant) to i32, and
4538 // convert it to a vector with movd (S2V+shuffle to zero extend).
4539 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4540 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4541 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4542 Subtarget->hasSSE2(), DAG);
4544 // Now we have our 32-bit value zero extended in the low element of
4545 // a vector. If Idx != 0, swizzle it into place.
4547 SmallVector<int, 4> Mask;
4548 Mask.push_back(Idx);
4549 for (unsigned i = 1; i != VecElts; ++i)
4551 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4552 DAG.getUNDEF(Item.getValueType()),
4555 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4559 // If we have a constant or non-constant insertion into the low element of
4560 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4561 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4562 // depending on what the source datatype is.
4565 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4566 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4567 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4568 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4569 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4570 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4572 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4573 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4574 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4575 EVT MiddleVT = MVT::v4i32;
4576 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4577 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4578 Subtarget->hasSSE2(), DAG);
4579 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4583 // Is it a vector logical left shift?
4584 if (NumElems == 2 && Idx == 1 &&
4585 X86::isZeroNode(Op.getOperand(0)) &&
4586 !X86::isZeroNode(Op.getOperand(1))) {
4587 unsigned NumBits = VT.getSizeInBits();
4588 return getVShift(true, VT,
4589 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4590 VT, Op.getOperand(1)),
4591 NumBits/2, DAG, *this, dl);
4594 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4597 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4598 // is a non-constant being inserted into an element other than the low one,
4599 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4600 // movd/movss) to move this into the low element, then shuffle it into
4602 if (EVTBits == 32) {
4603 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4605 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4606 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4607 Subtarget->hasSSE2(), DAG);
4608 SmallVector<int, 8> MaskVec;
4609 for (unsigned i = 0; i < NumElems; i++)
4610 MaskVec.push_back(i == Idx ? 0 : 1);
4611 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4615 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4616 if (Values.size() == 1) {
4617 if (EVTBits == 32) {
4618 // Instead of a shuffle like this:
4619 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4620 // Check if it's possible to issue this instead.
4621 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4622 unsigned Idx = CountTrailingZeros_32(NonZeros);
4623 SDValue Item = Op.getOperand(Idx);
4624 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4625 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4630 // A vector full of immediates; various special cases are already
4631 // handled, so this is best done with a single constant-pool load.
4635 // Let legalizer expand 2-wide build_vectors.
4636 if (EVTBits == 64) {
4637 if (NumNonZero == 1) {
4638 // One half is zero or undef.
4639 unsigned Idx = CountTrailingZeros_32(NonZeros);
4640 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4641 Op.getOperand(Idx));
4642 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4643 Subtarget->hasSSE2(), DAG);
4648 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4649 if (EVTBits == 8 && NumElems == 16) {
4650 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4652 if (V.getNode()) return V;
4655 if (EVTBits == 16 && NumElems == 8) {
4656 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4658 if (V.getNode()) return V;
4661 // If element VT is == 32 bits, turn it into a number of shuffles.
4662 SmallVector<SDValue, 8> V;
4664 if (NumElems == 4 && NumZero > 0) {
4665 for (unsigned i = 0; i < 4; ++i) {
4666 bool isZero = !(NonZeros & (1 << i));
4668 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4670 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4673 for (unsigned i = 0; i < 2; ++i) {
4674 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4677 V[i] = V[i*2]; // Must be a zero vector.
4680 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4683 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4686 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4691 SmallVector<int, 8> MaskVec;
4692 bool Reverse = (NonZeros & 0x3) == 2;
4693 for (unsigned i = 0; i < 2; ++i)
4694 MaskVec.push_back(Reverse ? 1-i : i);
4695 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4696 for (unsigned i = 0; i < 2; ++i)
4697 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4698 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4701 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4702 // Check for a build vector of consecutive loads.
4703 for (unsigned i = 0; i < NumElems; ++i)
4704 V[i] = Op.getOperand(i);
4706 // Check for elements which are consecutive loads.
4707 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4711 // For SSE 4.1, use insertps to put the high elements into the low element.
4712 if (getSubtarget()->hasSSE41()) {
4714 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4715 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4717 Result = DAG.getUNDEF(VT);
4719 for (unsigned i = 1; i < NumElems; ++i) {
4720 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4721 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4722 Op.getOperand(i), DAG.getIntPtrConstant(i));
4727 // Otherwise, expand into a number of unpckl*, start by extending each of
4728 // our (non-undef) elements to the full vector width with the element in the
4729 // bottom slot of the vector (which generates no code for SSE).
4730 for (unsigned i = 0; i < NumElems; ++i) {
4731 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4732 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4734 V[i] = DAG.getUNDEF(VT);
4737 // Next, we iteratively mix elements, e.g. for v4f32:
4738 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4739 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4740 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4741 unsigned EltStride = NumElems >> 1;
4742 while (EltStride != 0) {
4743 for (unsigned i = 0; i < EltStride; ++i) {
4744 // If V[i+EltStride] is undef and this is the first round of mixing,
4745 // then it is safe to just drop this shuffle: V[i] is already in the
4746 // right place, the one element (since it's the first round) being
4747 // inserted as undef can be dropped. This isn't safe for successive
4748 // rounds because they will permute elements within both vectors.
4749 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4750 EltStride == NumElems/2)
4753 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4763 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4764 // We support concatenate two MMX registers and place them in a MMX
4765 // register. This is better than doing a stack convert.
4766 DebugLoc dl = Op.getDebugLoc();
4767 EVT ResVT = Op.getValueType();
4768 assert(Op.getNumOperands() == 2);
4769 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4770 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4772 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4773 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4774 InVec = Op.getOperand(1);
4775 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4776 unsigned NumElts = ResVT.getVectorNumElements();
4777 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4778 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4779 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4781 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4782 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4783 Mask[0] = 0; Mask[1] = 2;
4784 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4786 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4789 // v8i16 shuffles - Prefer shuffles in the following order:
4790 // 1. [all] pshuflw, pshufhw, optional move
4791 // 2. [ssse3] 1 x pshufb
4792 // 3. [ssse3] 2 x pshufb + 1 x por
4793 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4795 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4796 SelectionDAG &DAG) const {
4797 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4798 SDValue V1 = SVOp->getOperand(0);
4799 SDValue V2 = SVOp->getOperand(1);
4800 DebugLoc dl = SVOp->getDebugLoc();
4801 SmallVector<int, 8> MaskVals;
4803 // Determine if more than 1 of the words in each of the low and high quadwords
4804 // of the result come from the same quadword of one of the two inputs. Undef
4805 // mask values count as coming from any quadword, for better codegen.
4806 SmallVector<unsigned, 4> LoQuad(4);
4807 SmallVector<unsigned, 4> HiQuad(4);
4808 BitVector InputQuads(4);
4809 for (unsigned i = 0; i < 8; ++i) {
4810 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4811 int EltIdx = SVOp->getMaskElt(i);
4812 MaskVals.push_back(EltIdx);
4821 InputQuads.set(EltIdx / 4);
4824 int BestLoQuad = -1;
4825 unsigned MaxQuad = 1;
4826 for (unsigned i = 0; i < 4; ++i) {
4827 if (LoQuad[i] > MaxQuad) {
4829 MaxQuad = LoQuad[i];
4833 int BestHiQuad = -1;
4835 for (unsigned i = 0; i < 4; ++i) {
4836 if (HiQuad[i] > MaxQuad) {
4838 MaxQuad = HiQuad[i];
4842 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4843 // of the two input vectors, shuffle them into one input vector so only a
4844 // single pshufb instruction is necessary. If There are more than 2 input
4845 // quads, disable the next transformation since it does not help SSSE3.
4846 bool V1Used = InputQuads[0] || InputQuads[1];
4847 bool V2Used = InputQuads[2] || InputQuads[3];
4848 if (Subtarget->hasSSSE3()) {
4849 if (InputQuads.count() == 2 && V1Used && V2Used) {
4850 BestLoQuad = InputQuads.find_first();
4851 BestHiQuad = InputQuads.find_next(BestLoQuad);
4853 if (InputQuads.count() > 2) {
4859 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4860 // the shuffle mask. If a quad is scored as -1, that means that it contains
4861 // words from all 4 input quadwords.
4863 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4864 SmallVector<int, 8> MaskV;
4865 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4866 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4867 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4868 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4869 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4870 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4872 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4873 // source words for the shuffle, to aid later transformations.
4874 bool AllWordsInNewV = true;
4875 bool InOrder[2] = { true, true };
4876 for (unsigned i = 0; i != 8; ++i) {
4877 int idx = MaskVals[i];
4879 InOrder[i/4] = false;
4880 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4882 AllWordsInNewV = false;
4886 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4887 if (AllWordsInNewV) {
4888 for (int i = 0; i != 8; ++i) {
4889 int idx = MaskVals[i];
4892 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4893 if ((idx != i) && idx < 4)
4895 if ((idx != i) && idx > 3)
4904 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4905 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4906 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4907 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4908 unsigned TargetMask = 0;
4909 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4910 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4911 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4912 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4913 V1 = NewV.getOperand(0);
4914 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4918 // If we have SSSE3, and all words of the result are from 1 input vector,
4919 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4920 // is present, fall back to case 4.
4921 if (Subtarget->hasSSSE3()) {
4922 SmallVector<SDValue,16> pshufbMask;
4924 // If we have elements from both input vectors, set the high bit of the
4925 // shuffle mask element to zero out elements that come from V2 in the V1
4926 // mask, and elements that come from V1 in the V2 mask, so that the two
4927 // results can be OR'd together.
4928 bool TwoInputs = V1Used && V2Used;
4929 for (unsigned i = 0; i != 8; ++i) {
4930 int EltIdx = MaskVals[i] * 2;
4931 if (TwoInputs && (EltIdx >= 16)) {
4932 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4933 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4936 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4937 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4939 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4940 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4941 DAG.getNode(ISD::BUILD_VECTOR, dl,
4942 MVT::v16i8, &pshufbMask[0], 16));
4944 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4946 // Calculate the shuffle mask for the second input, shuffle it, and
4947 // OR it with the first shuffled input.
4949 for (unsigned i = 0; i != 8; ++i) {
4950 int EltIdx = MaskVals[i] * 2;
4952 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4953 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4956 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4957 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4959 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4960 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4961 DAG.getNode(ISD::BUILD_VECTOR, dl,
4962 MVT::v16i8, &pshufbMask[0], 16));
4963 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4964 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4967 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4968 // and update MaskVals with new element order.
4969 BitVector InOrder(8);
4970 if (BestLoQuad >= 0) {
4971 SmallVector<int, 8> MaskV;
4972 for (int i = 0; i != 4; ++i) {
4973 int idx = MaskVals[i];
4975 MaskV.push_back(-1);
4977 } else if ((idx / 4) == BestLoQuad) {
4978 MaskV.push_back(idx & 3);
4981 MaskV.push_back(-1);
4984 for (unsigned i = 4; i != 8; ++i)
4986 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4989 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4990 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4992 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4996 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4997 // and update MaskVals with the new element order.
4998 if (BestHiQuad >= 0) {
4999 SmallVector<int, 8> MaskV;
5000 for (unsigned i = 0; i != 4; ++i)
5002 for (unsigned i = 4; i != 8; ++i) {
5003 int idx = MaskVals[i];
5005 MaskV.push_back(-1);
5007 } else if ((idx / 4) == BestHiQuad) {
5008 MaskV.push_back((idx & 3) + 4);
5011 MaskV.push_back(-1);
5014 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5017 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5018 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5020 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5024 // In case BestHi & BestLo were both -1, which means each quadword has a word
5025 // from each of the four input quadwords, calculate the InOrder bitvector now
5026 // before falling through to the insert/extract cleanup.
5027 if (BestLoQuad == -1 && BestHiQuad == -1) {
5029 for (int i = 0; i != 8; ++i)
5030 if (MaskVals[i] < 0 || MaskVals[i] == i)
5034 // The other elements are put in the right place using pextrw and pinsrw.
5035 for (unsigned i = 0; i != 8; ++i) {
5038 int EltIdx = MaskVals[i];
5041 SDValue ExtOp = (EltIdx < 8)
5042 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5043 DAG.getIntPtrConstant(EltIdx))
5044 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5045 DAG.getIntPtrConstant(EltIdx - 8));
5046 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5047 DAG.getIntPtrConstant(i));
5052 // v16i8 shuffles - Prefer shuffles in the following order:
5053 // 1. [ssse3] 1 x pshufb
5054 // 2. [ssse3] 2 x pshufb + 1 x por
5055 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5057 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5059 const X86TargetLowering &TLI) {
5060 SDValue V1 = SVOp->getOperand(0);
5061 SDValue V2 = SVOp->getOperand(1);
5062 DebugLoc dl = SVOp->getDebugLoc();
5063 SmallVector<int, 16> MaskVals;
5064 SVOp->getMask(MaskVals);
5066 // If we have SSSE3, case 1 is generated when all result bytes come from
5067 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5068 // present, fall back to case 3.
5069 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5072 for (unsigned i = 0; i < 16; ++i) {
5073 int EltIdx = MaskVals[i];
5082 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5083 if (TLI.getSubtarget()->hasSSSE3()) {
5084 SmallVector<SDValue,16> pshufbMask;
5086 // If all result elements are from one input vector, then only translate
5087 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5089 // Otherwise, we have elements from both input vectors, and must zero out
5090 // elements that come from V2 in the first mask, and V1 in the second mask
5091 // so that we can OR them together.
5092 bool TwoInputs = !(V1Only || V2Only);
5093 for (unsigned i = 0; i != 16; ++i) {
5094 int EltIdx = MaskVals[i];
5095 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5096 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5099 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5101 // If all the elements are from V2, assign it to V1 and return after
5102 // building the first pshufb.
5105 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5106 DAG.getNode(ISD::BUILD_VECTOR, dl,
5107 MVT::v16i8, &pshufbMask[0], 16));
5111 // Calculate the shuffle mask for the second input, shuffle it, and
5112 // OR it with the first shuffled input.
5114 for (unsigned i = 0; i != 16; ++i) {
5115 int EltIdx = MaskVals[i];
5117 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5120 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5122 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5123 DAG.getNode(ISD::BUILD_VECTOR, dl,
5124 MVT::v16i8, &pshufbMask[0], 16));
5125 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5128 // No SSSE3 - Calculate in place words and then fix all out of place words
5129 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5130 // the 16 different words that comprise the two doublequadword input vectors.
5131 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5132 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5133 SDValue NewV = V2Only ? V2 : V1;
5134 for (int i = 0; i != 8; ++i) {
5135 int Elt0 = MaskVals[i*2];
5136 int Elt1 = MaskVals[i*2+1];
5138 // This word of the result is all undef, skip it.
5139 if (Elt0 < 0 && Elt1 < 0)
5142 // This word of the result is already in the correct place, skip it.
5143 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5145 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5148 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5149 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5152 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5153 // using a single extract together, load it and store it.
5154 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5155 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5156 DAG.getIntPtrConstant(Elt1 / 2));
5157 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5158 DAG.getIntPtrConstant(i));
5162 // If Elt1 is defined, extract it from the appropriate source. If the
5163 // source byte is not also odd, shift the extracted word left 8 bits
5164 // otherwise clear the bottom 8 bits if we need to do an or.
5166 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5167 DAG.getIntPtrConstant(Elt1 / 2));
5168 if ((Elt1 & 1) == 0)
5169 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5171 TLI.getShiftAmountTy(InsElt.getValueType())));
5173 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5174 DAG.getConstant(0xFF00, MVT::i16));
5176 // If Elt0 is defined, extract it from the appropriate source. If the
5177 // source byte is not also even, shift the extracted word right 8 bits. If
5178 // Elt1 was also defined, OR the extracted values together before
5179 // inserting them in the result.
5181 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5182 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5183 if ((Elt0 & 1) != 0)
5184 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5186 TLI.getShiftAmountTy(InsElt0.getValueType())));
5188 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5189 DAG.getConstant(0x00FF, MVT::i16));
5190 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5193 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5194 DAG.getIntPtrConstant(i));
5196 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5199 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5200 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5201 /// done when every pair / quad of shuffle mask elements point to elements in
5202 /// the right sequence. e.g.
5203 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5205 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5206 SelectionDAG &DAG, DebugLoc dl) {
5207 EVT VT = SVOp->getValueType(0);
5208 SDValue V1 = SVOp->getOperand(0);
5209 SDValue V2 = SVOp->getOperand(1);
5210 unsigned NumElems = VT.getVectorNumElements();
5211 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5213 switch (VT.getSimpleVT().SimpleTy) {
5214 default: assert(false && "Unexpected!");
5215 case MVT::v4f32: NewVT = MVT::v2f64; break;
5216 case MVT::v4i32: NewVT = MVT::v2i64; break;
5217 case MVT::v8i16: NewVT = MVT::v4i32; break;
5218 case MVT::v16i8: NewVT = MVT::v4i32; break;
5221 int Scale = NumElems / NewWidth;
5222 SmallVector<int, 8> MaskVec;
5223 for (unsigned i = 0; i < NumElems; i += Scale) {
5225 for (int j = 0; j < Scale; ++j) {
5226 int EltIdx = SVOp->getMaskElt(i+j);
5230 StartIdx = EltIdx - (EltIdx % Scale);
5231 if (EltIdx != StartIdx + j)
5235 MaskVec.push_back(-1);
5237 MaskVec.push_back(StartIdx / Scale);
5240 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5241 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5242 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5245 /// getVZextMovL - Return a zero-extending vector move low node.
5247 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5248 SDValue SrcOp, SelectionDAG &DAG,
5249 const X86Subtarget *Subtarget, DebugLoc dl) {
5250 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5251 LoadSDNode *LD = NULL;
5252 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5253 LD = dyn_cast<LoadSDNode>(SrcOp);
5255 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5257 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5258 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5259 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5260 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5261 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5263 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5264 return DAG.getNode(ISD::BITCAST, dl, VT,
5265 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5266 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5274 return DAG.getNode(ISD::BITCAST, dl, VT,
5275 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5276 DAG.getNode(ISD::BITCAST, dl,
5280 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5283 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5284 SDValue V1 = SVOp->getOperand(0);
5285 SDValue V2 = SVOp->getOperand(1);
5286 DebugLoc dl = SVOp->getDebugLoc();
5287 EVT VT = SVOp->getValueType(0);
5289 SmallVector<std::pair<int, int>, 8> Locs;
5291 SmallVector<int, 8> Mask1(4U, -1);
5292 SmallVector<int, 8> PermMask;
5293 SVOp->getMask(PermMask);
5297 for (unsigned i = 0; i != 4; ++i) {
5298 int Idx = PermMask[i];
5300 Locs[i] = std::make_pair(-1, -1);
5302 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5304 Locs[i] = std::make_pair(0, NumLo);
5308 Locs[i] = std::make_pair(1, NumHi);
5310 Mask1[2+NumHi] = Idx;
5316 if (NumLo <= 2 && NumHi <= 2) {
5317 // If no more than two elements come from either vector. This can be
5318 // implemented with two shuffles. First shuffle gather the elements.
5319 // The second shuffle, which takes the first shuffle as both of its
5320 // vector operands, put the elements into the right order.
5321 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5323 SmallVector<int, 8> Mask2(4U, -1);
5325 for (unsigned i = 0; i != 4; ++i) {
5326 if (Locs[i].first == -1)
5329 unsigned Idx = (i < 2) ? 0 : 4;
5330 Idx += Locs[i].first * 2 + Locs[i].second;
5335 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5336 } else if (NumLo == 3 || NumHi == 3) {
5337 // Otherwise, we must have three elements from one vector, call it X, and
5338 // one element from the other, call it Y. First, use a shufps to build an
5339 // intermediate vector with the one element from Y and the element from X
5340 // that will be in the same half in the final destination (the indexes don't
5341 // matter). Then, use a shufps to build the final vector, taking the half
5342 // containing the element from Y from the intermediate, and the other half
5345 // Normalize it so the 3 elements come from V1.
5346 CommuteVectorShuffleMask(PermMask, VT);
5350 // Find the element from V2.
5352 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5353 int Val = PermMask[HiIndex];
5360 Mask1[0] = PermMask[HiIndex];
5362 Mask1[2] = PermMask[HiIndex^1];
5364 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5367 Mask1[0] = PermMask[0];
5368 Mask1[1] = PermMask[1];
5369 Mask1[2] = HiIndex & 1 ? 6 : 4;
5370 Mask1[3] = HiIndex & 1 ? 4 : 6;
5371 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5373 Mask1[0] = HiIndex & 1 ? 2 : 0;
5374 Mask1[1] = HiIndex & 1 ? 0 : 2;
5375 Mask1[2] = PermMask[2];
5376 Mask1[3] = PermMask[3];
5381 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5385 // Break it into (shuffle shuffle_hi, shuffle_lo).
5388 SmallVector<int,8> LoMask(4U, -1);
5389 SmallVector<int,8> HiMask(4U, -1);
5391 SmallVector<int,8> *MaskPtr = &LoMask;
5392 unsigned MaskIdx = 0;
5395 for (unsigned i = 0; i != 4; ++i) {
5402 int Idx = PermMask[i];
5404 Locs[i] = std::make_pair(-1, -1);
5405 } else if (Idx < 4) {
5406 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5407 (*MaskPtr)[LoIdx] = Idx;
5410 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5411 (*MaskPtr)[HiIdx] = Idx;
5416 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5417 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5418 SmallVector<int, 8> MaskOps;
5419 for (unsigned i = 0; i != 4; ++i) {
5420 if (Locs[i].first == -1) {
5421 MaskOps.push_back(-1);
5423 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5424 MaskOps.push_back(Idx);
5427 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5430 static bool MayFoldVectorLoad(SDValue V) {
5431 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5432 V = V.getOperand(0);
5433 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5434 V = V.getOperand(0);
5440 // FIXME: the version above should always be used. Since there's
5441 // a bug where several vector shuffles can't be folded because the
5442 // DAG is not updated during lowering and a node claims to have two
5443 // uses while it only has one, use this version, and let isel match
5444 // another instruction if the load really happens to have more than
5445 // one use. Remove this version after this bug get fixed.
5446 // rdar://8434668, PR8156
5447 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5448 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5449 V = V.getOperand(0);
5450 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5451 V = V.getOperand(0);
5452 if (ISD::isNormalLoad(V.getNode()))
5457 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5458 /// a vector extract, and if both can be later optimized into a single load.
5459 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5460 /// here because otherwise a target specific shuffle node is going to be
5461 /// emitted for this shuffle, and the optimization not done.
5462 /// FIXME: This is probably not the best approach, but fix the problem
5463 /// until the right path is decided.
5465 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5466 const TargetLowering &TLI) {
5467 EVT VT = V.getValueType();
5468 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5470 // Be sure that the vector shuffle is present in a pattern like this:
5471 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5475 SDNode *N = *V.getNode()->use_begin();
5476 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5479 SDValue EltNo = N->getOperand(1);
5480 if (!isa<ConstantSDNode>(EltNo))
5483 // If the bit convert changed the number of elements, it is unsafe
5484 // to examine the mask.
5485 bool HasShuffleIntoBitcast = false;
5486 if (V.getOpcode() == ISD::BITCAST) {
5487 EVT SrcVT = V.getOperand(0).getValueType();
5488 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5490 V = V.getOperand(0);
5491 HasShuffleIntoBitcast = true;
5494 // Select the input vector, guarding against out of range extract vector.
5495 unsigned NumElems = VT.getVectorNumElements();
5496 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5497 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5498 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5500 // Skip one more bit_convert if necessary
5501 if (V.getOpcode() == ISD::BITCAST)
5502 V = V.getOperand(0);
5504 if (ISD::isNormalLoad(V.getNode())) {
5505 // Is the original load suitable?
5506 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5508 // FIXME: avoid the multi-use bug that is preventing lots of
5509 // of foldings to be detected, this is still wrong of course, but
5510 // give the temporary desired behavior, and if it happens that
5511 // the load has real more uses, during isel it will not fold, and
5512 // will generate poor code.
5513 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5516 if (!HasShuffleIntoBitcast)
5519 // If there's a bitcast before the shuffle, check if the load type and
5520 // alignment is valid.
5521 unsigned Align = LN0->getAlignment();
5523 TLI.getTargetData()->getABITypeAlignment(
5524 VT.getTypeForEVT(*DAG.getContext()));
5526 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5534 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5535 EVT VT = Op.getValueType();
5537 // Canonizalize to v2f64.
5538 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5539 return DAG.getNode(ISD::BITCAST, dl, VT,
5540 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5545 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5547 SDValue V1 = Op.getOperand(0);
5548 SDValue V2 = Op.getOperand(1);
5549 EVT VT = Op.getValueType();
5551 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5553 if (HasSSE2 && VT == MVT::v2f64)
5554 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5557 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5561 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5562 SDValue V1 = Op.getOperand(0);
5563 SDValue V2 = Op.getOperand(1);
5564 EVT VT = Op.getValueType();
5566 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5567 "unsupported shuffle type");
5569 if (V2.getOpcode() == ISD::UNDEF)
5573 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5577 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5578 SDValue V1 = Op.getOperand(0);
5579 SDValue V2 = Op.getOperand(1);
5580 EVT VT = Op.getValueType();
5581 unsigned NumElems = VT.getVectorNumElements();
5583 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5584 // operand of these instructions is only memory, so check if there's a
5585 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5587 bool CanFoldLoad = false;
5589 // Trivial case, when V2 comes from a load.
5590 if (MayFoldVectorLoad(V2))
5593 // When V1 is a load, it can be folded later into a store in isel, example:
5594 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5596 // (MOVLPSmr addr:$src1, VR128:$src2)
5597 // So, recognize this potential and also use MOVLPS or MOVLPD
5598 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5601 // Both of them can't be memory operations though.
5602 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5603 CanFoldLoad = false;
5606 if (HasSSE2 && NumElems == 2)
5607 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5610 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5613 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5614 // movl and movlp will both match v2i64, but v2i64 is never matched by
5615 // movl earlier because we make it strict to avoid messing with the movlp load
5616 // folding logic (see the code above getMOVLP call). Match it here then,
5617 // this is horrible, but will stay like this until we move all shuffle
5618 // matching to x86 specific nodes. Note that for the 1st condition all
5619 // types are matched with movsd.
5620 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5621 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5623 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5626 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5628 // Invert the operand order and use SHUFPS to match it.
5629 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5630 X86::getShuffleSHUFImmediate(SVOp), DAG);
5633 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5634 switch(VT.getSimpleVT().SimpleTy) {
5635 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5636 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5638 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5640 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5641 case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5642 case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5643 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5644 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5646 llvm_unreachable("Unknown type for unpckl");
5651 static inline unsigned getUNPCKHOpcode(EVT VT) {
5652 switch(VT.getSimpleVT().SimpleTy) {
5653 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5654 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5655 case MVT::v4f32: return X86ISD::UNPCKHPS;
5656 case MVT::v2f64: return X86ISD::UNPCKHPD;
5657 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5658 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5660 llvm_unreachable("Unknown type for unpckh");
5666 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5667 const TargetLowering &TLI,
5668 const X86Subtarget *Subtarget) {
5669 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5670 EVT VT = Op.getValueType();
5671 DebugLoc dl = Op.getDebugLoc();
5672 SDValue V1 = Op.getOperand(0);
5673 SDValue V2 = Op.getOperand(1);
5675 if (isZeroShuffle(SVOp))
5676 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5678 // Handle splat operations
5679 if (SVOp->isSplat()) {
5680 // Special case, this is the only place now where it's
5681 // allowed to return a vector_shuffle operation without
5682 // using a target specific node, because *hopefully* it
5683 // will be optimized away by the dag combiner.
5684 if (VT.getVectorNumElements() <= 4 &&
5685 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5688 // Handle splats by matching through known masks
5689 if (VT.getVectorNumElements() <= 4)
5692 // Canonicalize all of the remaining to v4f32.
5693 return PromoteSplat(SVOp, DAG);
5696 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5698 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5699 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5700 if (NewOp.getNode())
5701 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5702 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5703 // FIXME: Figure out a cleaner way to do this.
5704 // Try to make use of movq to zero out the top part.
5705 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5706 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5707 if (NewOp.getNode()) {
5708 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5709 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5710 DAG, Subtarget, dl);
5712 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5713 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5714 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5715 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5716 DAG, Subtarget, dl);
5723 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5724 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5725 SDValue V1 = Op.getOperand(0);
5726 SDValue V2 = Op.getOperand(1);
5727 EVT VT = Op.getValueType();
5728 DebugLoc dl = Op.getDebugLoc();
5729 unsigned NumElems = VT.getVectorNumElements();
5730 bool isMMX = VT.getSizeInBits() == 64;
5731 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5732 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5733 bool V1IsSplat = false;
5734 bool V2IsSplat = false;
5735 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5736 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5737 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5738 MachineFunction &MF = DAG.getMachineFunction();
5739 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5741 // Shuffle operations on MMX not supported.
5745 // Vector shuffle lowering takes 3 steps:
5747 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5748 // narrowing and commutation of operands should be handled.
5749 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5751 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5752 // so the shuffle can be broken into other shuffles and the legalizer can
5753 // try the lowering again.
5755 // The general ideia is that no vector_shuffle operation should be left to
5756 // be matched during isel, all of them must be converted to a target specific
5759 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5760 // narrowing and commutation of operands should be handled. The actual code
5761 // doesn't include all of those, work in progress...
5762 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5763 if (NewOp.getNode())
5766 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5767 // unpckh_undef). Only use pshufd if speed is more important than size.
5768 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5769 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5770 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5771 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5772 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5773 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5775 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5776 RelaxedMayFoldVectorLoad(V1))
5777 return getMOVDDup(Op, dl, V1, DAG);
5779 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5780 return getMOVHighToLow(Op, dl, DAG);
5782 // Use to match splats
5783 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5784 (VT == MVT::v2f64 || VT == MVT::v2i64))
5785 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5787 if (X86::isPSHUFDMask(SVOp)) {
5788 // The actual implementation will match the mask in the if above and then
5789 // during isel it can match several different instructions, not only pshufd
5790 // as its name says, sad but true, emulate the behavior for now...
5791 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5792 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5794 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5796 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5797 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5799 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5800 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5803 if (VT == MVT::v4f32)
5804 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5808 // Check if this can be converted into a logical shift.
5809 bool isLeft = false;
5812 bool isShift = getSubtarget()->hasSSE2() &&
5813 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5814 if (isShift && ShVal.hasOneUse()) {
5815 // If the shifted value has multiple uses, it may be cheaper to use
5816 // v_set0 + movlhps or movhlps, etc.
5817 EVT EltVT = VT.getVectorElementType();
5818 ShAmt *= EltVT.getSizeInBits();
5819 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5822 if (X86::isMOVLMask(SVOp)) {
5825 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5826 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5827 if (!X86::isMOVLPMask(SVOp)) {
5828 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5829 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5831 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5832 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5836 // FIXME: fold these into legal mask.
5837 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5838 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5840 if (X86::isMOVHLPSMask(SVOp))
5841 return getMOVHighToLow(Op, dl, DAG);
5843 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5844 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5846 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5847 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5849 if (X86::isMOVLPMask(SVOp))
5850 return getMOVLP(Op, dl, DAG, HasSSE2);
5852 if (ShouldXformToMOVHLPS(SVOp) ||
5853 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5854 return CommuteVectorShuffle(SVOp, DAG);
5857 // No better options. Use a vshl / vsrl.
5858 EVT EltVT = VT.getVectorElementType();
5859 ShAmt *= EltVT.getSizeInBits();
5860 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5863 bool Commuted = false;
5864 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5865 // 1,1,1,1 -> v8i16 though.
5866 V1IsSplat = isSplatVector(V1.getNode());
5867 V2IsSplat = isSplatVector(V2.getNode());
5869 // Canonicalize the splat or undef, if present, to be on the RHS.
5870 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5871 Op = CommuteVectorShuffle(SVOp, DAG);
5872 SVOp = cast<ShuffleVectorSDNode>(Op);
5873 V1 = SVOp->getOperand(0);
5874 V2 = SVOp->getOperand(1);
5875 std::swap(V1IsSplat, V2IsSplat);
5876 std::swap(V1IsUndef, V2IsUndef);
5880 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5881 // Shuffling low element of v1 into undef, just return v1.
5884 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5885 // the instruction selector will not match, so get a canonical MOVL with
5886 // swapped operands to undo the commute.
5887 return getMOVL(DAG, dl, VT, V2, V1);
5890 if (X86::isUNPCKLMask(SVOp))
5891 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5892 dl, VT, V1, V2, DAG);
5894 if (X86::isUNPCKHMask(SVOp))
5895 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5898 // Normalize mask so all entries that point to V2 points to its first
5899 // element then try to match unpck{h|l} again. If match, return a
5900 // new vector_shuffle with the corrected mask.
5901 SDValue NewMask = NormalizeMask(SVOp, DAG);
5902 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5903 if (NSVOp != SVOp) {
5904 if (X86::isUNPCKLMask(NSVOp, true)) {
5906 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5913 // Commute is back and try unpck* again.
5914 // FIXME: this seems wrong.
5915 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5916 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5918 if (X86::isUNPCKLMask(NewSVOp))
5919 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5920 dl, VT, V2, V1, DAG);
5922 if (X86::isUNPCKHMask(NewSVOp))
5923 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5926 // Normalize the node to match x86 shuffle ops if needed
5927 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5928 return CommuteVectorShuffle(SVOp, DAG);
5930 // The checks below are all present in isShuffleMaskLegal, but they are
5931 // inlined here right now to enable us to directly emit target specific
5932 // nodes, and remove one by one until they don't return Op anymore.
5933 SmallVector<int, 16> M;
5936 if (isPALIGNRMask(M, VT, HasSSSE3))
5937 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5938 X86::getShufflePALIGNRImmediate(SVOp),
5941 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5942 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5943 if (VT == MVT::v2f64) {
5944 X86ISD::NodeType Opcode =
5945 getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5946 return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5948 if (VT == MVT::v2i64)
5949 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5952 if (isPSHUFHWMask(M, VT))
5953 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5954 X86::getShufflePSHUFHWImmediate(SVOp),
5957 if (isPSHUFLWMask(M, VT))
5958 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5959 X86::getShufflePSHUFLWImmediate(SVOp),
5962 if (isSHUFPMask(M, VT)) {
5963 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5964 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5965 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5967 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5968 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5972 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5973 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5974 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5975 dl, VT, V1, V1, DAG);
5976 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5977 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5978 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5980 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5981 if (VT == MVT::v8i16) {
5982 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5983 if (NewOp.getNode())
5987 if (VT == MVT::v16i8) {
5988 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5989 if (NewOp.getNode())
5993 // Handle all 4 wide cases with a number of shuffles.
5995 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
6001 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6002 SelectionDAG &DAG) const {
6003 EVT VT = Op.getValueType();
6004 DebugLoc dl = Op.getDebugLoc();
6005 if (VT.getSizeInBits() == 8) {
6006 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6007 Op.getOperand(0), Op.getOperand(1));
6008 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6009 DAG.getValueType(VT));
6010 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6011 } else if (VT.getSizeInBits() == 16) {
6012 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6013 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6015 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6016 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6017 DAG.getNode(ISD::BITCAST, dl,
6021 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6022 Op.getOperand(0), Op.getOperand(1));
6023 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6024 DAG.getValueType(VT));
6025 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6026 } else if (VT == MVT::f32) {
6027 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6028 // the result back to FR32 register. It's only worth matching if the
6029 // result has a single use which is a store or a bitcast to i32. And in
6030 // the case of a store, it's not worth it if the index is a constant 0,
6031 // because a MOVSSmr can be used instead, which is smaller and faster.
6032 if (!Op.hasOneUse())
6034 SDNode *User = *Op.getNode()->use_begin();
6035 if ((User->getOpcode() != ISD::STORE ||
6036 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6037 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6038 (User->getOpcode() != ISD::BITCAST ||
6039 User->getValueType(0) != MVT::i32))
6041 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6042 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6045 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6046 } else if (VT == MVT::i32) {
6047 // ExtractPS works with constant index.
6048 if (isa<ConstantSDNode>(Op.getOperand(1)))
6056 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6057 SelectionDAG &DAG) const {
6058 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6061 SDValue Vec = Op.getOperand(0);
6062 EVT VecVT = Vec.getValueType();
6064 // If this is a 256-bit vector result, first extract the 128-bit
6065 // vector and then extract from the 128-bit vector.
6066 if (VecVT.getSizeInBits() > 128) {
6067 DebugLoc dl = Op.getNode()->getDebugLoc();
6068 unsigned NumElems = VecVT.getVectorNumElements();
6069 SDValue Idx = Op.getOperand(1);
6071 if (!isa<ConstantSDNode>(Idx))
6074 unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6075 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6077 // Get the 128-bit vector.
6078 bool Upper = IdxVal >= ExtractNumElems;
6079 Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6082 SDValue ScaledIdx = Idx;
6084 ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6085 DAG.getConstant(ExtractNumElems,
6086 Idx.getValueType()));
6087 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6091 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6093 if (Subtarget->hasSSE41()) {
6094 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6099 EVT VT = Op.getValueType();
6100 DebugLoc dl = Op.getDebugLoc();
6101 // TODO: handle v16i8.
6102 if (VT.getSizeInBits() == 16) {
6103 SDValue Vec = Op.getOperand(0);
6104 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6106 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6107 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6108 DAG.getNode(ISD::BITCAST, dl,
6111 // Transform it so it match pextrw which produces a 32-bit result.
6112 EVT EltVT = MVT::i32;
6113 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6114 Op.getOperand(0), Op.getOperand(1));
6115 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6116 DAG.getValueType(VT));
6117 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6118 } else if (VT.getSizeInBits() == 32) {
6119 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6123 // SHUFPS the element to the lowest double word, then movss.
6124 int Mask[4] = { Idx, -1, -1, -1 };
6125 EVT VVT = Op.getOperand(0).getValueType();
6126 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6127 DAG.getUNDEF(VVT), Mask);
6128 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6129 DAG.getIntPtrConstant(0));
6130 } else if (VT.getSizeInBits() == 64) {
6131 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6132 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6133 // to match extract_elt for f64.
6134 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6138 // UNPCKHPD the element to the lowest double word, then movsd.
6139 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6140 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6141 int Mask[2] = { 1, -1 };
6142 EVT VVT = Op.getOperand(0).getValueType();
6143 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6144 DAG.getUNDEF(VVT), Mask);
6145 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6146 DAG.getIntPtrConstant(0));
6153 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6154 SelectionDAG &DAG) const {
6155 EVT VT = Op.getValueType();
6156 EVT EltVT = VT.getVectorElementType();
6157 DebugLoc dl = Op.getDebugLoc();
6159 SDValue N0 = Op.getOperand(0);
6160 SDValue N1 = Op.getOperand(1);
6161 SDValue N2 = Op.getOperand(2);
6163 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6164 isa<ConstantSDNode>(N2)) {
6166 if (VT == MVT::v8i16)
6167 Opc = X86ISD::PINSRW;
6168 else if (VT == MVT::v16i8)
6169 Opc = X86ISD::PINSRB;
6171 Opc = X86ISD::PINSRB;
6173 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6175 if (N1.getValueType() != MVT::i32)
6176 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6177 if (N2.getValueType() != MVT::i32)
6178 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6179 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6180 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6181 // Bits [7:6] of the constant are the source select. This will always be
6182 // zero here. The DAG Combiner may combine an extract_elt index into these
6183 // bits. For example (insert (extract, 3), 2) could be matched by putting
6184 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6185 // Bits [5:4] of the constant are the destination select. This is the
6186 // value of the incoming immediate.
6187 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6188 // combine either bitwise AND or insert of float 0.0 to set these bits.
6189 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6190 // Create this as a scalar to vector..
6191 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6192 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6193 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6194 // PINSR* works with constant index.
6201 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6202 EVT VT = Op.getValueType();
6203 EVT EltVT = VT.getVectorElementType();
6205 DebugLoc dl = Op.getDebugLoc();
6206 SDValue N0 = Op.getOperand(0);
6207 SDValue N1 = Op.getOperand(1);
6208 SDValue N2 = Op.getOperand(2);
6210 // If this is a 256-bit vector result, first insert into a 128-bit
6211 // vector and then insert into the 256-bit vector.
6212 if (VT.getSizeInBits() > 128) {
6213 if (!isa<ConstantSDNode>(N2))
6216 // Get the 128-bit vector.
6217 unsigned NumElems = VT.getVectorNumElements();
6218 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6219 bool Upper = IdxVal >= NumElems / 2;
6221 SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6224 SDValue ScaledN2 = N2;
6226 ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6227 DAG.getConstant(NumElems /
6228 (VT.getSizeInBits() / 128),
6229 N2.getValueType()));
6230 Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6233 // Insert the 128-bit vector
6234 // FIXME: Why UNDEF?
6235 return Insert128BitVector(N0, Op, N2, DAG, dl);
6238 if (Subtarget->hasSSE41())
6239 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6241 if (EltVT == MVT::i8)
6244 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6245 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6246 // as its second argument.
6247 if (N1.getValueType() != MVT::i32)
6248 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6249 if (N2.getValueType() != MVT::i32)
6250 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6251 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6257 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6258 LLVMContext *Context = DAG.getContext();
6259 DebugLoc dl = Op.getDebugLoc();
6260 EVT OpVT = Op.getValueType();
6262 // If this is a 256-bit vector result, first insert into a 128-bit
6263 // vector and then insert into the 256-bit vector.
6264 if (OpVT.getSizeInBits() > 128) {
6265 // Insert into a 128-bit vector.
6266 EVT VT128 = EVT::getVectorVT(*Context,
6267 OpVT.getVectorElementType(),
6268 OpVT.getVectorNumElements() / 2);
6270 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6272 // Insert the 128-bit vector.
6273 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6274 DAG.getConstant(0, MVT::i32),
6278 if (Op.getValueType() == MVT::v1i64 &&
6279 Op.getOperand(0).getValueType() == MVT::i64)
6280 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6282 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6283 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6284 "Expected an SSE type!");
6285 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6286 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6289 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
6290 // a simple subregister reference or explicit instructions to grab
6291 // upper bits of a vector.
6293 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6294 if (Subtarget->hasAVX()) {
6295 DebugLoc dl = Op.getNode()->getDebugLoc();
6296 SDValue Vec = Op.getNode()->getOperand(0);
6297 SDValue Idx = Op.getNode()->getOperand(1);
6299 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6300 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6301 return Extract128BitVector(Vec, Idx, DAG, dl);
6307 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
6308 // simple superregister reference or explicit instructions to insert
6309 // the upper bits of a vector.
6311 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6312 if (Subtarget->hasAVX()) {
6313 DebugLoc dl = Op.getNode()->getDebugLoc();
6314 SDValue Vec = Op.getNode()->getOperand(0);
6315 SDValue SubVec = Op.getNode()->getOperand(1);
6316 SDValue Idx = Op.getNode()->getOperand(2);
6318 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6319 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6320 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6326 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6327 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6328 // one of the above mentioned nodes. It has to be wrapped because otherwise
6329 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6330 // be used to form addressing mode. These wrapped nodes will be selected
6333 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6334 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6336 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6338 unsigned char OpFlag = 0;
6339 unsigned WrapperKind = X86ISD::Wrapper;
6340 CodeModel::Model M = getTargetMachine().getCodeModel();
6342 if (Subtarget->isPICStyleRIPRel() &&
6343 (M == CodeModel::Small || M == CodeModel::Kernel))
6344 WrapperKind = X86ISD::WrapperRIP;
6345 else if (Subtarget->isPICStyleGOT())
6346 OpFlag = X86II::MO_GOTOFF;
6347 else if (Subtarget->isPICStyleStubPIC())
6348 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6350 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6352 CP->getOffset(), OpFlag);
6353 DebugLoc DL = CP->getDebugLoc();
6354 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6355 // With PIC, the address is actually $g + Offset.
6357 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6358 DAG.getNode(X86ISD::GlobalBaseReg,
6359 DebugLoc(), getPointerTy()),
6366 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6367 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6369 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6371 unsigned char OpFlag = 0;
6372 unsigned WrapperKind = X86ISD::Wrapper;
6373 CodeModel::Model M = getTargetMachine().getCodeModel();
6375 if (Subtarget->isPICStyleRIPRel() &&
6376 (M == CodeModel::Small || M == CodeModel::Kernel))
6377 WrapperKind = X86ISD::WrapperRIP;
6378 else if (Subtarget->isPICStyleGOT())
6379 OpFlag = X86II::MO_GOTOFF;
6380 else if (Subtarget->isPICStyleStubPIC())
6381 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6383 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6385 DebugLoc DL = JT->getDebugLoc();
6386 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6388 // With PIC, the address is actually $g + Offset.
6390 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6391 DAG.getNode(X86ISD::GlobalBaseReg,
6392 DebugLoc(), getPointerTy()),
6399 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6400 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6402 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6404 unsigned char OpFlag = 0;
6405 unsigned WrapperKind = X86ISD::Wrapper;
6406 CodeModel::Model M = getTargetMachine().getCodeModel();
6408 if (Subtarget->isPICStyleRIPRel() &&
6409 (M == CodeModel::Small || M == CodeModel::Kernel))
6410 WrapperKind = X86ISD::WrapperRIP;
6411 else if (Subtarget->isPICStyleGOT())
6412 OpFlag = X86II::MO_GOTOFF;
6413 else if (Subtarget->isPICStyleStubPIC())
6414 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6416 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6418 DebugLoc DL = Op.getDebugLoc();
6419 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6422 // With PIC, the address is actually $g + Offset.
6423 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6424 !Subtarget->is64Bit()) {
6425 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6426 DAG.getNode(X86ISD::GlobalBaseReg,
6427 DebugLoc(), getPointerTy()),
6435 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6436 // Create the TargetBlockAddressAddress node.
6437 unsigned char OpFlags =
6438 Subtarget->ClassifyBlockAddressReference();
6439 CodeModel::Model M = getTargetMachine().getCodeModel();
6440 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6441 DebugLoc dl = Op.getDebugLoc();
6442 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6443 /*isTarget=*/true, OpFlags);
6445 if (Subtarget->isPICStyleRIPRel() &&
6446 (M == CodeModel::Small || M == CodeModel::Kernel))
6447 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6449 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6451 // With PIC, the address is actually $g + Offset.
6452 if (isGlobalRelativeToPICBase(OpFlags)) {
6453 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6454 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6462 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6464 SelectionDAG &DAG) const {
6465 // Create the TargetGlobalAddress node, folding in the constant
6466 // offset if it is legal.
6467 unsigned char OpFlags =
6468 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6469 CodeModel::Model M = getTargetMachine().getCodeModel();
6471 if (OpFlags == X86II::MO_NO_FLAG &&
6472 X86::isOffsetSuitableForCodeModel(Offset, M)) {
6473 // A direct static reference to a global.
6474 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6477 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6480 if (Subtarget->isPICStyleRIPRel() &&
6481 (M == CodeModel::Small || M == CodeModel::Kernel))
6482 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6484 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6486 // With PIC, the address is actually $g + Offset.
6487 if (isGlobalRelativeToPICBase(OpFlags)) {
6488 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6489 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6493 // For globals that require a load from a stub to get the address, emit the
6495 if (isGlobalStubReference(OpFlags))
6496 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6497 MachinePointerInfo::getGOT(), false, false, 0);
6499 // If there was a non-zero offset that we didn't fold, create an explicit
6502 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6503 DAG.getConstant(Offset, getPointerTy()));
6509 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6510 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6511 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6512 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6516 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6517 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6518 unsigned char OperandFlags) {
6519 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6520 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6521 DebugLoc dl = GA->getDebugLoc();
6522 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6523 GA->getValueType(0),
6527 SDValue Ops[] = { Chain, TGA, *InFlag };
6528 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6530 SDValue Ops[] = { Chain, TGA };
6531 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6534 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6535 MFI->setAdjustsStack(true);
6537 SDValue Flag = Chain.getValue(1);
6538 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6541 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6543 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6546 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6547 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6548 DAG.getNode(X86ISD::GlobalBaseReg,
6549 DebugLoc(), PtrVT), InFlag);
6550 InFlag = Chain.getValue(1);
6552 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6555 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6557 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6559 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6560 X86::RAX, X86II::MO_TLSGD);
6563 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6564 // "local exec" model.
6565 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6566 const EVT PtrVT, TLSModel::Model model,
6568 DebugLoc dl = GA->getDebugLoc();
6570 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6571 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6572 is64Bit ? 257 : 256));
6574 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6575 DAG.getIntPtrConstant(0),
6576 MachinePointerInfo(Ptr), false, false, 0);
6578 unsigned char OperandFlags = 0;
6579 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6581 unsigned WrapperKind = X86ISD::Wrapper;
6582 if (model == TLSModel::LocalExec) {
6583 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6584 } else if (is64Bit) {
6585 assert(model == TLSModel::InitialExec);
6586 OperandFlags = X86II::MO_GOTTPOFF;
6587 WrapperKind = X86ISD::WrapperRIP;
6589 assert(model == TLSModel::InitialExec);
6590 OperandFlags = X86II::MO_INDNTPOFF;
6593 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6595 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6596 GA->getValueType(0),
6597 GA->getOffset(), OperandFlags);
6598 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6600 if (model == TLSModel::InitialExec)
6601 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6602 MachinePointerInfo::getGOT(), false, false, 0);
6604 // The address of the thread local variable is the add of the thread
6605 // pointer with the offset of the variable.
6606 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6610 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6612 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6613 const GlobalValue *GV = GA->getGlobal();
6615 if (Subtarget->isTargetELF()) {
6616 // TODO: implement the "local dynamic" model
6617 // TODO: implement the "initial exec"model for pic executables
6619 // If GV is an alias then use the aliasee for determining
6620 // thread-localness.
6621 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6622 GV = GA->resolveAliasedGlobal(false);
6624 TLSModel::Model model
6625 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6628 case TLSModel::GeneralDynamic:
6629 case TLSModel::LocalDynamic: // not implemented
6630 if (Subtarget->is64Bit())
6631 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6632 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6634 case TLSModel::InitialExec:
6635 case TLSModel::LocalExec:
6636 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6637 Subtarget->is64Bit());
6639 } else if (Subtarget->isTargetDarwin()) {
6640 // Darwin only has one model of TLS. Lower to that.
6641 unsigned char OpFlag = 0;
6642 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6643 X86ISD::WrapperRIP : X86ISD::Wrapper;
6645 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6647 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6648 !Subtarget->is64Bit();
6650 OpFlag = X86II::MO_TLVP_PIC_BASE;
6652 OpFlag = X86II::MO_TLVP;
6653 DebugLoc DL = Op.getDebugLoc();
6654 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6655 GA->getValueType(0),
6656 GA->getOffset(), OpFlag);
6657 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6659 // With PIC32, the address is actually $g + Offset.
6661 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6662 DAG.getNode(X86ISD::GlobalBaseReg,
6663 DebugLoc(), getPointerTy()),
6666 // Lowering the machine isd will make sure everything is in the right
6668 SDValue Chain = DAG.getEntryNode();
6669 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6670 SDValue Args[] = { Chain, Offset };
6671 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6673 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6674 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6675 MFI->setAdjustsStack(true);
6677 // And our return value (tls address) is in the standard call return value
6679 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6680 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6684 "TLS not implemented for this target.");
6686 llvm_unreachable("Unreachable");
6691 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6692 /// take a 2 x i32 value to shift plus a shift amount.
6693 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6694 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6695 EVT VT = Op.getValueType();
6696 unsigned VTBits = VT.getSizeInBits();
6697 DebugLoc dl = Op.getDebugLoc();
6698 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6699 SDValue ShOpLo = Op.getOperand(0);
6700 SDValue ShOpHi = Op.getOperand(1);
6701 SDValue ShAmt = Op.getOperand(2);
6702 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6703 DAG.getConstant(VTBits - 1, MVT::i8))
6704 : DAG.getConstant(0, VT);
6707 if (Op.getOpcode() == ISD::SHL_PARTS) {
6708 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6709 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6711 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6712 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6715 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6716 DAG.getConstant(VTBits, MVT::i8));
6717 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6718 AndNode, DAG.getConstant(0, MVT::i8));
6721 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6722 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6723 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6725 if (Op.getOpcode() == ISD::SHL_PARTS) {
6726 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6727 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6729 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6730 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6733 SDValue Ops[2] = { Lo, Hi };
6734 return DAG.getMergeValues(Ops, 2, dl);
6737 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6738 SelectionDAG &DAG) const {
6739 EVT SrcVT = Op.getOperand(0).getValueType();
6741 if (SrcVT.isVector())
6744 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6745 "Unknown SINT_TO_FP to lower!");
6747 // These are really Legal; return the operand so the caller accepts it as
6749 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6751 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6752 Subtarget->is64Bit()) {
6756 DebugLoc dl = Op.getDebugLoc();
6757 unsigned Size = SrcVT.getSizeInBits()/8;
6758 MachineFunction &MF = DAG.getMachineFunction();
6759 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6760 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6761 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6763 MachinePointerInfo::getFixedStack(SSFI),
6765 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6768 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6770 SelectionDAG &DAG) const {
6772 DebugLoc DL = Op.getDebugLoc();
6774 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6776 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6778 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6780 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6782 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
6783 MachineMemOperand *MMO;
6785 int SSFI = FI->getIndex();
6787 DAG.getMachineFunction()
6788 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6789 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6791 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
6792 StackSlot = StackSlot.getOperand(1);
6794 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6795 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6797 Tys, Ops, array_lengthof(Ops),
6801 Chain = Result.getValue(1);
6802 SDValue InFlag = Result.getValue(2);
6804 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6805 // shouldn't be necessary except that RFP cannot be live across
6806 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6807 MachineFunction &MF = DAG.getMachineFunction();
6808 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6809 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6810 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6811 Tys = DAG.getVTList(MVT::Other);
6813 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6815 MachineMemOperand *MMO =
6816 DAG.getMachineFunction()
6817 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6818 MachineMemOperand::MOStore, SSFISize, SSFISize);
6820 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6821 Ops, array_lengthof(Ops),
6822 Op.getValueType(), MMO);
6823 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6824 MachinePointerInfo::getFixedStack(SSFI),
6831 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6832 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6833 SelectionDAG &DAG) const {
6834 // This algorithm is not obvious. Here it is in C code, more or less:
6836 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6837 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6838 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6840 // Copy ints to xmm registers.
6841 __m128i xh = _mm_cvtsi32_si128( hi );
6842 __m128i xl = _mm_cvtsi32_si128( lo );
6844 // Combine into low half of a single xmm register.
6845 __m128i x = _mm_unpacklo_epi32( xh, xl );
6849 // Merge in appropriate exponents to give the integer bits the right
6851 x = _mm_unpacklo_epi32( x, exp );
6853 // Subtract away the biases to deal with the IEEE-754 double precision
6855 d = _mm_sub_pd( (__m128d) x, bias );
6857 // All conversions up to here are exact. The correctly rounded result is
6858 // calculated using the current rounding mode using the following
6860 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6861 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6862 // store doesn't really need to be here (except
6863 // maybe to zero the other double)
6868 DebugLoc dl = Op.getDebugLoc();
6869 LLVMContext *Context = DAG.getContext();
6871 // Build some magic constants.
6872 std::vector<Constant*> CV0;
6873 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6874 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6875 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6876 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6877 Constant *C0 = ConstantVector::get(CV0);
6878 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6880 std::vector<Constant*> CV1;
6882 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6884 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6885 Constant *C1 = ConstantVector::get(CV1);
6886 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6888 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6889 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6891 DAG.getIntPtrConstant(1)));
6892 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6893 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6895 DAG.getIntPtrConstant(0)));
6896 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6897 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6898 MachinePointerInfo::getConstantPool(),
6900 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6901 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6902 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6903 MachinePointerInfo::getConstantPool(),
6905 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6907 // Add the halves; easiest way is to swap them into another reg first.
6908 int ShufMask[2] = { 1, -1 };
6909 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6910 DAG.getUNDEF(MVT::v2f64), ShufMask);
6911 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6912 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6913 DAG.getIntPtrConstant(0));
6916 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6917 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6918 SelectionDAG &DAG) const {
6919 DebugLoc dl = Op.getDebugLoc();
6920 // FP constant to bias correct the final result.
6921 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6924 // Load the 32-bit value into an XMM register.
6925 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6926 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6928 DAG.getIntPtrConstant(0)));
6930 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6931 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6932 DAG.getIntPtrConstant(0));
6934 // Or the load with the bias.
6935 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6936 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6937 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6939 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6940 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6941 MVT::v2f64, Bias)));
6942 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6943 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6944 DAG.getIntPtrConstant(0));
6946 // Subtract the bias.
6947 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6949 // Handle final rounding.
6950 EVT DestVT = Op.getValueType();
6952 if (DestVT.bitsLT(MVT::f64)) {
6953 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6954 DAG.getIntPtrConstant(0));
6955 } else if (DestVT.bitsGT(MVT::f64)) {
6956 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6959 // Handle final rounding.
6963 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6964 SelectionDAG &DAG) const {
6965 SDValue N0 = Op.getOperand(0);
6966 DebugLoc dl = Op.getDebugLoc();
6968 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6969 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6970 // the optimization here.
6971 if (DAG.SignBitIsZero(N0))
6972 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6974 EVT SrcVT = N0.getValueType();
6975 EVT DstVT = Op.getValueType();
6976 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6977 return LowerUINT_TO_FP_i64(Op, DAG);
6978 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6979 return LowerUINT_TO_FP_i32(Op, DAG);
6981 // Make a 64-bit buffer, and use it to build an FILD.
6982 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6983 if (SrcVT == MVT::i32) {
6984 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6985 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6986 getPointerTy(), StackSlot, WordOff);
6987 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6988 StackSlot, MachinePointerInfo(),
6990 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6991 OffsetSlot, MachinePointerInfo(),
6993 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6997 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6998 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6999 StackSlot, MachinePointerInfo(),
7001 // For i64 source, we need to add the appropriate power of 2 if the input
7002 // was negative. This is the same as the optimization in
7003 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7004 // we must be careful to do the computation in x87 extended precision, not
7005 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7006 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7007 MachineMemOperand *MMO =
7008 DAG.getMachineFunction()
7009 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7010 MachineMemOperand::MOLoad, 8, 8);
7012 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7013 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7014 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7017 APInt FF(32, 0x5F800000ULL);
7019 // Check whether the sign bit is set.
7020 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7021 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7024 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7025 SDValue FudgePtr = DAG.getConstantPool(
7026 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7029 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7030 SDValue Zero = DAG.getIntPtrConstant(0);
7031 SDValue Four = DAG.getIntPtrConstant(4);
7032 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7034 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7036 // Load the value out, extending it from f32 to f80.
7037 // FIXME: Avoid the extend by constructing the right constant pool?
7038 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7039 FudgePtr, MachinePointerInfo::getConstantPool(),
7040 MVT::f32, false, false, 4);
7041 // Extend everything to 80 bits to force it to be done on x87.
7042 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7043 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7046 std::pair<SDValue,SDValue> X86TargetLowering::
7047 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7048 DebugLoc DL = Op.getDebugLoc();
7050 EVT DstTy = Op.getValueType();
7053 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7057 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7058 DstTy.getSimpleVT() >= MVT::i16 &&
7059 "Unknown FP_TO_SINT to lower!");
7061 // These are really Legal.
7062 if (DstTy == MVT::i32 &&
7063 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7064 return std::make_pair(SDValue(), SDValue());
7065 if (Subtarget->is64Bit() &&
7066 DstTy == MVT::i64 &&
7067 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7068 return std::make_pair(SDValue(), SDValue());
7070 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7072 MachineFunction &MF = DAG.getMachineFunction();
7073 unsigned MemSize = DstTy.getSizeInBits()/8;
7074 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7075 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7080 switch (DstTy.getSimpleVT().SimpleTy) {
7081 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7082 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7083 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7084 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7087 SDValue Chain = DAG.getEntryNode();
7088 SDValue Value = Op.getOperand(0);
7089 EVT TheVT = Op.getOperand(0).getValueType();
7090 if (isScalarFPTypeInSSEReg(TheVT)) {
7091 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7092 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7093 MachinePointerInfo::getFixedStack(SSFI),
7095 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7097 Chain, StackSlot, DAG.getValueType(TheVT)
7100 MachineMemOperand *MMO =
7101 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7102 MachineMemOperand::MOLoad, MemSize, MemSize);
7103 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7105 Chain = Value.getValue(1);
7106 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7107 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7110 MachineMemOperand *MMO =
7111 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7112 MachineMemOperand::MOStore, MemSize, MemSize);
7114 // Build the FP_TO_INT*_IN_MEM
7115 SDValue Ops[] = { Chain, Value, StackSlot };
7116 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7117 Ops, 3, DstTy, MMO);
7119 return std::make_pair(FIST, StackSlot);
7122 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7123 SelectionDAG &DAG) const {
7124 if (Op.getValueType().isVector())
7127 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7128 SDValue FIST = Vals.first, StackSlot = Vals.second;
7129 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7130 if (FIST.getNode() == 0) return Op;
7133 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7134 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7137 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7138 SelectionDAG &DAG) const {
7139 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7140 SDValue FIST = Vals.first, StackSlot = Vals.second;
7141 assert(FIST.getNode() && "Unexpected failure");
7144 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7145 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7148 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7149 SelectionDAG &DAG) const {
7150 LLVMContext *Context = DAG.getContext();
7151 DebugLoc dl = Op.getDebugLoc();
7152 EVT VT = Op.getValueType();
7155 EltVT = VT.getVectorElementType();
7156 std::vector<Constant*> CV;
7157 if (EltVT == MVT::f64) {
7158 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7162 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7168 Constant *C = ConstantVector::get(CV);
7169 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7170 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7171 MachinePointerInfo::getConstantPool(),
7173 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7176 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7177 LLVMContext *Context = DAG.getContext();
7178 DebugLoc dl = Op.getDebugLoc();
7179 EVT VT = Op.getValueType();
7182 EltVT = VT.getVectorElementType();
7183 std::vector<Constant*> CV;
7184 if (EltVT == MVT::f64) {
7185 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7189 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7195 Constant *C = ConstantVector::get(CV);
7196 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7197 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7198 MachinePointerInfo::getConstantPool(),
7200 if (VT.isVector()) {
7201 return DAG.getNode(ISD::BITCAST, dl, VT,
7202 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7203 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7205 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7207 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7211 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7212 LLVMContext *Context = DAG.getContext();
7213 SDValue Op0 = Op.getOperand(0);
7214 SDValue Op1 = Op.getOperand(1);
7215 DebugLoc dl = Op.getDebugLoc();
7216 EVT VT = Op.getValueType();
7217 EVT SrcVT = Op1.getValueType();
7219 // If second operand is smaller, extend it first.
7220 if (SrcVT.bitsLT(VT)) {
7221 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7224 // And if it is bigger, shrink it first.
7225 if (SrcVT.bitsGT(VT)) {
7226 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7230 // At this point the operands and the result should have the same
7231 // type, and that won't be f80 since that is not custom lowered.
7233 // First get the sign bit of second operand.
7234 std::vector<Constant*> CV;
7235 if (SrcVT == MVT::f64) {
7236 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7237 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7239 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7240 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7241 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7242 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7244 Constant *C = ConstantVector::get(CV);
7245 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7246 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7247 MachinePointerInfo::getConstantPool(),
7249 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7251 // Shift sign bit right or left if the two operands have different types.
7252 if (SrcVT.bitsGT(VT)) {
7253 // Op0 is MVT::f32, Op1 is MVT::f64.
7254 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7255 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7256 DAG.getConstant(32, MVT::i32));
7257 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7258 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7259 DAG.getIntPtrConstant(0));
7262 // Clear first operand sign bit.
7264 if (VT == MVT::f64) {
7265 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7266 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7268 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7269 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7270 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7271 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7273 C = ConstantVector::get(CV);
7274 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7275 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7276 MachinePointerInfo::getConstantPool(),
7278 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7280 // Or the value with the sign bit.
7281 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7284 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7285 SDValue N0 = Op.getOperand(0);
7286 DebugLoc dl = Op.getDebugLoc();
7287 EVT VT = Op.getValueType();
7289 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7290 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7291 DAG.getConstant(1, VT));
7292 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7295 /// Emit nodes that will be selected as "test Op0,Op0", or something
7297 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7298 SelectionDAG &DAG) const {
7299 DebugLoc dl = Op.getDebugLoc();
7301 // CF and OF aren't always set the way we want. Determine which
7302 // of these we need.
7303 bool NeedCF = false;
7304 bool NeedOF = false;
7307 case X86::COND_A: case X86::COND_AE:
7308 case X86::COND_B: case X86::COND_BE:
7311 case X86::COND_G: case X86::COND_GE:
7312 case X86::COND_L: case X86::COND_LE:
7313 case X86::COND_O: case X86::COND_NO:
7318 // See if we can use the EFLAGS value from the operand instead of
7319 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7320 // we prove that the arithmetic won't overflow, we can't use OF or CF.
7321 if (Op.getResNo() != 0 || NeedOF || NeedCF)
7322 // Emit a CMP with 0, which is the TEST pattern.
7323 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7324 DAG.getConstant(0, Op.getValueType()));
7326 unsigned Opcode = 0;
7327 unsigned NumOperands = 0;
7328 switch (Op.getNode()->getOpcode()) {
7330 // Due to an isel shortcoming, be conservative if this add is likely to be
7331 // selected as part of a load-modify-store instruction. When the root node
7332 // in a match is a store, isel doesn't know how to remap non-chain non-flag
7333 // uses of other nodes in the match, such as the ADD in this case. This
7334 // leads to the ADD being left around and reselected, with the result being
7335 // two adds in the output. Alas, even if none our users are stores, that
7336 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
7337 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
7338 // climbing the DAG back to the root, and it doesn't seem to be worth the
7340 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7341 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7342 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7345 if (ConstantSDNode *C =
7346 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7347 // An add of one will be selected as an INC.
7348 if (C->getAPIntValue() == 1) {
7349 Opcode = X86ISD::INC;
7354 // An add of negative one (subtract of one) will be selected as a DEC.
7355 if (C->getAPIntValue().isAllOnesValue()) {
7356 Opcode = X86ISD::DEC;
7362 // Otherwise use a regular EFLAGS-setting add.
7363 Opcode = X86ISD::ADD;
7367 // If the primary and result isn't used, don't bother using X86ISD::AND,
7368 // because a TEST instruction will be better.
7369 bool NonFlagUse = false;
7370 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7371 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7373 unsigned UOpNo = UI.getOperandNo();
7374 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7375 // Look pass truncate.
7376 UOpNo = User->use_begin().getOperandNo();
7377 User = *User->use_begin();
7380 if (User->getOpcode() != ISD::BRCOND &&
7381 User->getOpcode() != ISD::SETCC &&
7382 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7395 // Due to the ISEL shortcoming noted above, be conservative if this op is
7396 // likely to be selected as part of a load-modify-store instruction.
7397 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7398 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7399 if (UI->getOpcode() == ISD::STORE)
7402 // Otherwise use a regular EFLAGS-setting instruction.
7403 switch (Op.getNode()->getOpcode()) {
7404 default: llvm_unreachable("unexpected operator!");
7405 case ISD::SUB: Opcode = X86ISD::SUB; break;
7406 case ISD::OR: Opcode = X86ISD::OR; break;
7407 case ISD::XOR: Opcode = X86ISD::XOR; break;
7408 case ISD::AND: Opcode = X86ISD::AND; break;
7420 return SDValue(Op.getNode(), 1);
7427 // Emit a CMP with 0, which is the TEST pattern.
7428 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7429 DAG.getConstant(0, Op.getValueType()));
7431 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7432 SmallVector<SDValue, 4> Ops;
7433 for (unsigned i = 0; i != NumOperands; ++i)
7434 Ops.push_back(Op.getOperand(i));
7436 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7437 DAG.ReplaceAllUsesWith(Op, New);
7438 return SDValue(New.getNode(), 1);
7441 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7443 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7444 SelectionDAG &DAG) const {
7445 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7446 if (C->getAPIntValue() == 0)
7447 return EmitTest(Op0, X86CC, DAG);
7449 DebugLoc dl = Op0.getDebugLoc();
7450 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7453 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7454 /// if it's possible.
7455 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7456 DebugLoc dl, SelectionDAG &DAG) const {
7457 SDValue Op0 = And.getOperand(0);
7458 SDValue Op1 = And.getOperand(1);
7459 if (Op0.getOpcode() == ISD::TRUNCATE)
7460 Op0 = Op0.getOperand(0);
7461 if (Op1.getOpcode() == ISD::TRUNCATE)
7462 Op1 = Op1.getOperand(0);
7465 if (Op1.getOpcode() == ISD::SHL)
7466 std::swap(Op0, Op1);
7467 if (Op0.getOpcode() == ISD::SHL) {
7468 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7469 if (And00C->getZExtValue() == 1) {
7470 // If we looked past a truncate, check that it's only truncating away
7472 unsigned BitWidth = Op0.getValueSizeInBits();
7473 unsigned AndBitWidth = And.getValueSizeInBits();
7474 if (BitWidth > AndBitWidth) {
7475 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7476 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7477 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7481 RHS = Op0.getOperand(1);
7483 } else if (Op1.getOpcode() == ISD::Constant) {
7484 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7485 SDValue AndLHS = Op0;
7486 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7487 LHS = AndLHS.getOperand(0);
7488 RHS = AndLHS.getOperand(1);
7492 if (LHS.getNode()) {
7493 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
7494 // instruction. Since the shift amount is in-range-or-undefined, we know
7495 // that doing a bittest on the i32 value is ok. We extend to i32 because
7496 // the encoding for the i16 version is larger than the i32 version.
7497 // Also promote i16 to i32 for performance / code size reason.
7498 if (LHS.getValueType() == MVT::i8 ||
7499 LHS.getValueType() == MVT::i16)
7500 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7502 // If the operand types disagree, extend the shift amount to match. Since
7503 // BT ignores high bits (like shifts) we can use anyextend.
7504 if (LHS.getValueType() != RHS.getValueType())
7505 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7507 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7508 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7509 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7510 DAG.getConstant(Cond, MVT::i8), BT);
7516 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7517 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7518 SDValue Op0 = Op.getOperand(0);
7519 SDValue Op1 = Op.getOperand(1);
7520 DebugLoc dl = Op.getDebugLoc();
7521 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7523 // Optimize to BT if possible.
7524 // Lower (X & (1 << N)) == 0 to BT(X, N).
7525 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7526 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7527 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7528 Op1.getOpcode() == ISD::Constant &&
7529 cast<ConstantSDNode>(Op1)->isNullValue() &&
7530 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7531 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7532 if (NewSetCC.getNode())
7536 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
7538 if (Op1.getOpcode() == ISD::Constant &&
7539 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7540 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7541 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7543 // If the input is a setcc, then reuse the input setcc or use a new one with
7544 // the inverted condition.
7545 if (Op0.getOpcode() == X86ISD::SETCC) {
7546 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7547 bool Invert = (CC == ISD::SETNE) ^
7548 cast<ConstantSDNode>(Op1)->isNullValue();
7549 if (!Invert) return Op0;
7551 CCode = X86::GetOppositeBranchCondition(CCode);
7552 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7553 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7557 bool isFP = Op1.getValueType().isFloatingPoint();
7558 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7559 if (X86CC == X86::COND_INVALID)
7562 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7563 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7564 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7567 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7569 SDValue Op0 = Op.getOperand(0);
7570 SDValue Op1 = Op.getOperand(1);
7571 SDValue CC = Op.getOperand(2);
7572 EVT VT = Op.getValueType();
7573 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7574 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7575 DebugLoc dl = Op.getDebugLoc();
7579 EVT VT0 = Op0.getValueType();
7580 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7581 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7584 switch (SetCCOpcode) {
7587 case ISD::SETEQ: SSECC = 0; break;
7589 case ISD::SETGT: Swap = true; // Fallthrough
7591 case ISD::SETOLT: SSECC = 1; break;
7593 case ISD::SETGE: Swap = true; // Fallthrough
7595 case ISD::SETOLE: SSECC = 2; break;
7596 case ISD::SETUO: SSECC = 3; break;
7598 case ISD::SETNE: SSECC = 4; break;
7599 case ISD::SETULE: Swap = true;
7600 case ISD::SETUGE: SSECC = 5; break;
7601 case ISD::SETULT: Swap = true;
7602 case ISD::SETUGT: SSECC = 6; break;
7603 case ISD::SETO: SSECC = 7; break;
7606 std::swap(Op0, Op1);
7608 // In the two special cases we can't handle, emit two comparisons.
7610 if (SetCCOpcode == ISD::SETUEQ) {
7612 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7613 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7614 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7616 else if (SetCCOpcode == ISD::SETONE) {
7618 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7619 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7620 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7622 llvm_unreachable("Illegal FP comparison");
7624 // Handle all other FP comparisons here.
7625 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7628 // We are handling one of the integer comparisons here. Since SSE only has
7629 // GT and EQ comparisons for integer, swapping operands and multiple
7630 // operations may be required for some comparisons.
7631 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7632 bool Swap = false, Invert = false, FlipSigns = false;
7634 switch (VT.getSimpleVT().SimpleTy) {
7636 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7637 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7638 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7639 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7642 switch (SetCCOpcode) {
7644 case ISD::SETNE: Invert = true;
7645 case ISD::SETEQ: Opc = EQOpc; break;
7646 case ISD::SETLT: Swap = true;
7647 case ISD::SETGT: Opc = GTOpc; break;
7648 case ISD::SETGE: Swap = true;
7649 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7650 case ISD::SETULT: Swap = true;
7651 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7652 case ISD::SETUGE: Swap = true;
7653 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7656 std::swap(Op0, Op1);
7658 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7659 // bits of the inputs before performing those operations.
7661 EVT EltVT = VT.getVectorElementType();
7662 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7664 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7665 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7667 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7668 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7671 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7673 // If the logical-not of the result is required, perform that now.
7675 Result = DAG.getNOT(dl, Result, VT);
7680 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7681 static bool isX86LogicalCmp(SDValue Op) {
7682 unsigned Opc = Op.getNode()->getOpcode();
7683 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7685 if (Op.getResNo() == 1 &&
7686 (Opc == X86ISD::ADD ||
7687 Opc == X86ISD::SUB ||
7688 Opc == X86ISD::ADC ||
7689 Opc == X86ISD::SBB ||
7690 Opc == X86ISD::SMUL ||
7691 Opc == X86ISD::UMUL ||
7692 Opc == X86ISD::INC ||
7693 Opc == X86ISD::DEC ||
7694 Opc == X86ISD::OR ||
7695 Opc == X86ISD::XOR ||
7696 Opc == X86ISD::AND))
7699 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7705 static bool isZero(SDValue V) {
7706 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7707 return C && C->isNullValue();
7710 static bool isAllOnes(SDValue V) {
7711 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7712 return C && C->isAllOnesValue();
7715 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7716 bool addTest = true;
7717 SDValue Cond = Op.getOperand(0);
7718 SDValue Op1 = Op.getOperand(1);
7719 SDValue Op2 = Op.getOperand(2);
7720 DebugLoc DL = Op.getDebugLoc();
7723 if (Cond.getOpcode() == ISD::SETCC) {
7724 SDValue NewCond = LowerSETCC(Cond, DAG);
7725 if (NewCond.getNode())
7729 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7730 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7731 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7732 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7733 if (Cond.getOpcode() == X86ISD::SETCC &&
7734 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7735 isZero(Cond.getOperand(1).getOperand(1))) {
7736 SDValue Cmp = Cond.getOperand(1);
7738 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7740 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7741 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7742 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7744 SDValue CmpOp0 = Cmp.getOperand(0);
7745 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7746 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7748 SDValue Res = // Res = 0 or -1.
7749 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7750 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7752 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7753 Res = DAG.getNOT(DL, Res, Res.getValueType());
7755 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7756 if (N2C == 0 || !N2C->isNullValue())
7757 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7762 // Look past (and (setcc_carry (cmp ...)), 1).
7763 if (Cond.getOpcode() == ISD::AND &&
7764 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7765 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7766 if (C && C->getAPIntValue() == 1)
7767 Cond = Cond.getOperand(0);
7770 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7771 // setting operand in place of the X86ISD::SETCC.
7772 if (Cond.getOpcode() == X86ISD::SETCC ||
7773 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7774 CC = Cond.getOperand(0);
7776 SDValue Cmp = Cond.getOperand(1);
7777 unsigned Opc = Cmp.getOpcode();
7778 EVT VT = Op.getValueType();
7780 bool IllegalFPCMov = false;
7781 if (VT.isFloatingPoint() && !VT.isVector() &&
7782 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7783 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7785 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7786 Opc == X86ISD::BT) { // FIXME
7793 // Look pass the truncate.
7794 if (Cond.getOpcode() == ISD::TRUNCATE)
7795 Cond = Cond.getOperand(0);
7797 // We know the result of AND is compared against zero. Try to match
7799 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7800 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7801 if (NewSetCC.getNode()) {
7802 CC = NewSetCC.getOperand(0);
7803 Cond = NewSetCC.getOperand(1);
7810 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7811 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7814 // a < b ? -1 : 0 -> RES = ~setcc_carry
7815 // a < b ? 0 : -1 -> RES = setcc_carry
7816 // a >= b ? -1 : 0 -> RES = setcc_carry
7817 // a >= b ? 0 : -1 -> RES = ~setcc_carry
7818 if (Cond.getOpcode() == X86ISD::CMP) {
7819 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7821 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7822 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7823 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7824 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7825 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7826 return DAG.getNOT(DL, Res, Res.getValueType());
7831 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7832 // condition is true.
7833 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7834 SDValue Ops[] = { Op2, Op1, CC, Cond };
7835 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7838 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7839 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7840 // from the AND / OR.
7841 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7842 Opc = Op.getOpcode();
7843 if (Opc != ISD::OR && Opc != ISD::AND)
7845 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7846 Op.getOperand(0).hasOneUse() &&
7847 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7848 Op.getOperand(1).hasOneUse());
7851 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7852 // 1 and that the SETCC node has a single use.
7853 static bool isXor1OfSetCC(SDValue Op) {
7854 if (Op.getOpcode() != ISD::XOR)
7856 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7857 if (N1C && N1C->getAPIntValue() == 1) {
7858 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7859 Op.getOperand(0).hasOneUse();
7864 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7865 bool addTest = true;
7866 SDValue Chain = Op.getOperand(0);
7867 SDValue Cond = Op.getOperand(1);
7868 SDValue Dest = Op.getOperand(2);
7869 DebugLoc dl = Op.getDebugLoc();
7872 if (Cond.getOpcode() == ISD::SETCC) {
7873 SDValue NewCond = LowerSETCC(Cond, DAG);
7874 if (NewCond.getNode())
7878 // FIXME: LowerXALUO doesn't handle these!!
7879 else if (Cond.getOpcode() == X86ISD::ADD ||
7880 Cond.getOpcode() == X86ISD::SUB ||
7881 Cond.getOpcode() == X86ISD::SMUL ||
7882 Cond.getOpcode() == X86ISD::UMUL)
7883 Cond = LowerXALUO(Cond, DAG);
7886 // Look pass (and (setcc_carry (cmp ...)), 1).
7887 if (Cond.getOpcode() == ISD::AND &&
7888 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7889 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7890 if (C && C->getAPIntValue() == 1)
7891 Cond = Cond.getOperand(0);
7894 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7895 // setting operand in place of the X86ISD::SETCC.
7896 if (Cond.getOpcode() == X86ISD::SETCC ||
7897 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7898 CC = Cond.getOperand(0);
7900 SDValue Cmp = Cond.getOperand(1);
7901 unsigned Opc = Cmp.getOpcode();
7902 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7903 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7907 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7911 // These can only come from an arithmetic instruction with overflow,
7912 // e.g. SADDO, UADDO.
7913 Cond = Cond.getNode()->getOperand(1);
7920 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7921 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7922 if (CondOpc == ISD::OR) {
7923 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7924 // two branches instead of an explicit OR instruction with a
7926 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7927 isX86LogicalCmp(Cmp)) {
7928 CC = Cond.getOperand(0).getOperand(0);
7929 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7930 Chain, Dest, CC, Cmp);
7931 CC = Cond.getOperand(1).getOperand(0);
7935 } else { // ISD::AND
7936 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7937 // two branches instead of an explicit AND instruction with a
7938 // separate test. However, we only do this if this block doesn't
7939 // have a fall-through edge, because this requires an explicit
7940 // jmp when the condition is false.
7941 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7942 isX86LogicalCmp(Cmp) &&
7943 Op.getNode()->hasOneUse()) {
7944 X86::CondCode CCode =
7945 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7946 CCode = X86::GetOppositeBranchCondition(CCode);
7947 CC = DAG.getConstant(CCode, MVT::i8);
7948 SDNode *User = *Op.getNode()->use_begin();
7949 // Look for an unconditional branch following this conditional branch.
7950 // We need this because we need to reverse the successors in order
7951 // to implement FCMP_OEQ.
7952 if (User->getOpcode() == ISD::BR) {
7953 SDValue FalseBB = User->getOperand(1);
7955 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7956 assert(NewBR == User);
7960 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7961 Chain, Dest, CC, Cmp);
7962 X86::CondCode CCode =
7963 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7964 CCode = X86::GetOppositeBranchCondition(CCode);
7965 CC = DAG.getConstant(CCode, MVT::i8);
7971 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7972 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7973 // It should be transformed during dag combiner except when the condition
7974 // is set by a arithmetics with overflow node.
7975 X86::CondCode CCode =
7976 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7977 CCode = X86::GetOppositeBranchCondition(CCode);
7978 CC = DAG.getConstant(CCode, MVT::i8);
7979 Cond = Cond.getOperand(0).getOperand(1);
7985 // Look pass the truncate.
7986 if (Cond.getOpcode() == ISD::TRUNCATE)
7987 Cond = Cond.getOperand(0);
7989 // We know the result of AND is compared against zero. Try to match
7991 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7992 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7993 if (NewSetCC.getNode()) {
7994 CC = NewSetCC.getOperand(0);
7995 Cond = NewSetCC.getOperand(1);
8002 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8003 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8005 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8006 Chain, Dest, CC, Cond);
8010 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8011 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8012 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8013 // that the guard pages used by the OS virtual memory manager are allocated in
8014 // correct sequence.
8016 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8017 SelectionDAG &DAG) const {
8018 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8019 "This should be used only on Windows targets");
8020 assert(!Subtarget->isTargetEnvMacho());
8021 DebugLoc dl = Op.getDebugLoc();
8024 SDValue Chain = Op.getOperand(0);
8025 SDValue Size = Op.getOperand(1);
8026 // FIXME: Ensure alignment here
8030 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8031 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8033 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8034 Flag = Chain.getValue(1);
8036 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8038 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8039 Flag = Chain.getValue(1);
8041 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8043 SDValue Ops1[2] = { Chain.getValue(0), Chain };
8044 return DAG.getMergeValues(Ops1, 2, dl);
8047 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8048 MachineFunction &MF = DAG.getMachineFunction();
8049 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8051 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8052 DebugLoc DL = Op.getDebugLoc();
8054 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8055 // vastart just stores the address of the VarArgsFrameIndex slot into the
8056 // memory location argument.
8057 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8059 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8060 MachinePointerInfo(SV), false, false, 0);
8064 // gp_offset (0 - 6 * 8)
8065 // fp_offset (48 - 48 + 8 * 16)
8066 // overflow_arg_area (point to parameters coming in memory).
8068 SmallVector<SDValue, 8> MemOps;
8069 SDValue FIN = Op.getOperand(1);
8071 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8072 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8074 FIN, MachinePointerInfo(SV), false, false, 0);
8075 MemOps.push_back(Store);
8078 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8079 FIN, DAG.getIntPtrConstant(4));
8080 Store = DAG.getStore(Op.getOperand(0), DL,
8081 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8083 FIN, MachinePointerInfo(SV, 4), false, false, 0);
8084 MemOps.push_back(Store);
8086 // Store ptr to overflow_arg_area
8087 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8088 FIN, DAG.getIntPtrConstant(4));
8089 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8091 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8092 MachinePointerInfo(SV, 8),
8094 MemOps.push_back(Store);
8096 // Store ptr to reg_save_area.
8097 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8098 FIN, DAG.getIntPtrConstant(8));
8099 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8101 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8102 MachinePointerInfo(SV, 16), false, false, 0);
8103 MemOps.push_back(Store);
8104 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8105 &MemOps[0], MemOps.size());
8108 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8109 assert(Subtarget->is64Bit() &&
8110 "LowerVAARG only handles 64-bit va_arg!");
8111 assert((Subtarget->isTargetLinux() ||
8112 Subtarget->isTargetDarwin()) &&
8113 "Unhandled target in LowerVAARG");
8114 assert(Op.getNode()->getNumOperands() == 4);
8115 SDValue Chain = Op.getOperand(0);
8116 SDValue SrcPtr = Op.getOperand(1);
8117 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8118 unsigned Align = Op.getConstantOperandVal(3);
8119 DebugLoc dl = Op.getDebugLoc();
8121 EVT ArgVT = Op.getNode()->getValueType(0);
8122 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8123 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8126 // Decide which area this value should be read from.
8127 // TODO: Implement the AMD64 ABI in its entirety. This simple
8128 // selection mechanism works only for the basic types.
8129 if (ArgVT == MVT::f80) {
8130 llvm_unreachable("va_arg for f80 not yet implemented");
8131 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8132 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
8133 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8134 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
8136 llvm_unreachable("Unhandled argument type in LowerVAARG");
8140 // Sanity Check: Make sure using fp_offset makes sense.
8141 assert(!UseSoftFloat &&
8142 !(DAG.getMachineFunction()
8143 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8144 Subtarget->hasXMM());
8147 // Insert VAARG_64 node into the DAG
8148 // VAARG_64 returns two values: Variable Argument Address, Chain
8149 SmallVector<SDValue, 11> InstOps;
8150 InstOps.push_back(Chain);
8151 InstOps.push_back(SrcPtr);
8152 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8153 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8154 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8155 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8156 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8157 VTs, &InstOps[0], InstOps.size(),
8159 MachinePointerInfo(SV),
8164 Chain = VAARG.getValue(1);
8166 // Load the next argument and return it
8167 return DAG.getLoad(ArgVT, dl,
8170 MachinePointerInfo(),
8174 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8175 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8176 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8177 SDValue Chain = Op.getOperand(0);
8178 SDValue DstPtr = Op.getOperand(1);
8179 SDValue SrcPtr = Op.getOperand(2);
8180 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8181 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8182 DebugLoc DL = Op.getDebugLoc();
8184 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8185 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8187 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8191 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8192 DebugLoc dl = Op.getDebugLoc();
8193 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8195 default: return SDValue(); // Don't custom lower most intrinsics.
8196 // Comparison intrinsics.
8197 case Intrinsic::x86_sse_comieq_ss:
8198 case Intrinsic::x86_sse_comilt_ss:
8199 case Intrinsic::x86_sse_comile_ss:
8200 case Intrinsic::x86_sse_comigt_ss:
8201 case Intrinsic::x86_sse_comige_ss:
8202 case Intrinsic::x86_sse_comineq_ss:
8203 case Intrinsic::x86_sse_ucomieq_ss:
8204 case Intrinsic::x86_sse_ucomilt_ss:
8205 case Intrinsic::x86_sse_ucomile_ss:
8206 case Intrinsic::x86_sse_ucomigt_ss:
8207 case Intrinsic::x86_sse_ucomige_ss:
8208 case Intrinsic::x86_sse_ucomineq_ss:
8209 case Intrinsic::x86_sse2_comieq_sd:
8210 case Intrinsic::x86_sse2_comilt_sd:
8211 case Intrinsic::x86_sse2_comile_sd:
8212 case Intrinsic::x86_sse2_comigt_sd:
8213 case Intrinsic::x86_sse2_comige_sd:
8214 case Intrinsic::x86_sse2_comineq_sd:
8215 case Intrinsic::x86_sse2_ucomieq_sd:
8216 case Intrinsic::x86_sse2_ucomilt_sd:
8217 case Intrinsic::x86_sse2_ucomile_sd:
8218 case Intrinsic::x86_sse2_ucomigt_sd:
8219 case Intrinsic::x86_sse2_ucomige_sd:
8220 case Intrinsic::x86_sse2_ucomineq_sd: {
8222 ISD::CondCode CC = ISD::SETCC_INVALID;
8225 case Intrinsic::x86_sse_comieq_ss:
8226 case Intrinsic::x86_sse2_comieq_sd:
8230 case Intrinsic::x86_sse_comilt_ss:
8231 case Intrinsic::x86_sse2_comilt_sd:
8235 case Intrinsic::x86_sse_comile_ss:
8236 case Intrinsic::x86_sse2_comile_sd:
8240 case Intrinsic::x86_sse_comigt_ss:
8241 case Intrinsic::x86_sse2_comigt_sd:
8245 case Intrinsic::x86_sse_comige_ss:
8246 case Intrinsic::x86_sse2_comige_sd:
8250 case Intrinsic::x86_sse_comineq_ss:
8251 case Intrinsic::x86_sse2_comineq_sd:
8255 case Intrinsic::x86_sse_ucomieq_ss:
8256 case Intrinsic::x86_sse2_ucomieq_sd:
8257 Opc = X86ISD::UCOMI;
8260 case Intrinsic::x86_sse_ucomilt_ss:
8261 case Intrinsic::x86_sse2_ucomilt_sd:
8262 Opc = X86ISD::UCOMI;
8265 case Intrinsic::x86_sse_ucomile_ss:
8266 case Intrinsic::x86_sse2_ucomile_sd:
8267 Opc = X86ISD::UCOMI;
8270 case Intrinsic::x86_sse_ucomigt_ss:
8271 case Intrinsic::x86_sse2_ucomigt_sd:
8272 Opc = X86ISD::UCOMI;
8275 case Intrinsic::x86_sse_ucomige_ss:
8276 case Intrinsic::x86_sse2_ucomige_sd:
8277 Opc = X86ISD::UCOMI;
8280 case Intrinsic::x86_sse_ucomineq_ss:
8281 case Intrinsic::x86_sse2_ucomineq_sd:
8282 Opc = X86ISD::UCOMI;
8287 SDValue LHS = Op.getOperand(1);
8288 SDValue RHS = Op.getOperand(2);
8289 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8290 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8291 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8292 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8293 DAG.getConstant(X86CC, MVT::i8), Cond);
8294 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8296 // ptest and testp intrinsics. The intrinsic these come from are designed to
8297 // return an integer value, not just an instruction so lower it to the ptest
8298 // or testp pattern and a setcc for the result.
8299 case Intrinsic::x86_sse41_ptestz:
8300 case Intrinsic::x86_sse41_ptestc:
8301 case Intrinsic::x86_sse41_ptestnzc:
8302 case Intrinsic::x86_avx_ptestz_256:
8303 case Intrinsic::x86_avx_ptestc_256:
8304 case Intrinsic::x86_avx_ptestnzc_256:
8305 case Intrinsic::x86_avx_vtestz_ps:
8306 case Intrinsic::x86_avx_vtestc_ps:
8307 case Intrinsic::x86_avx_vtestnzc_ps:
8308 case Intrinsic::x86_avx_vtestz_pd:
8309 case Intrinsic::x86_avx_vtestc_pd:
8310 case Intrinsic::x86_avx_vtestnzc_pd:
8311 case Intrinsic::x86_avx_vtestz_ps_256:
8312 case Intrinsic::x86_avx_vtestc_ps_256:
8313 case Intrinsic::x86_avx_vtestnzc_ps_256:
8314 case Intrinsic::x86_avx_vtestz_pd_256:
8315 case Intrinsic::x86_avx_vtestc_pd_256:
8316 case Intrinsic::x86_avx_vtestnzc_pd_256: {
8317 bool IsTestPacked = false;
8320 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8321 case Intrinsic::x86_avx_vtestz_ps:
8322 case Intrinsic::x86_avx_vtestz_pd:
8323 case Intrinsic::x86_avx_vtestz_ps_256:
8324 case Intrinsic::x86_avx_vtestz_pd_256:
8325 IsTestPacked = true; // Fallthrough
8326 case Intrinsic::x86_sse41_ptestz:
8327 case Intrinsic::x86_avx_ptestz_256:
8329 X86CC = X86::COND_E;
8331 case Intrinsic::x86_avx_vtestc_ps:
8332 case Intrinsic::x86_avx_vtestc_pd:
8333 case Intrinsic::x86_avx_vtestc_ps_256:
8334 case Intrinsic::x86_avx_vtestc_pd_256:
8335 IsTestPacked = true; // Fallthrough
8336 case Intrinsic::x86_sse41_ptestc:
8337 case Intrinsic::x86_avx_ptestc_256:
8339 X86CC = X86::COND_B;
8341 case Intrinsic::x86_avx_vtestnzc_ps:
8342 case Intrinsic::x86_avx_vtestnzc_pd:
8343 case Intrinsic::x86_avx_vtestnzc_ps_256:
8344 case Intrinsic::x86_avx_vtestnzc_pd_256:
8345 IsTestPacked = true; // Fallthrough
8346 case Intrinsic::x86_sse41_ptestnzc:
8347 case Intrinsic::x86_avx_ptestnzc_256:
8349 X86CC = X86::COND_A;
8353 SDValue LHS = Op.getOperand(1);
8354 SDValue RHS = Op.getOperand(2);
8355 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8356 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8357 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8358 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8359 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8362 // Fix vector shift instructions where the last operand is a non-immediate
8364 case Intrinsic::x86_sse2_pslli_w:
8365 case Intrinsic::x86_sse2_pslli_d:
8366 case Intrinsic::x86_sse2_pslli_q:
8367 case Intrinsic::x86_sse2_psrli_w:
8368 case Intrinsic::x86_sse2_psrli_d:
8369 case Intrinsic::x86_sse2_psrli_q:
8370 case Intrinsic::x86_sse2_psrai_w:
8371 case Intrinsic::x86_sse2_psrai_d:
8372 case Intrinsic::x86_mmx_pslli_w:
8373 case Intrinsic::x86_mmx_pslli_d:
8374 case Intrinsic::x86_mmx_pslli_q:
8375 case Intrinsic::x86_mmx_psrli_w:
8376 case Intrinsic::x86_mmx_psrli_d:
8377 case Intrinsic::x86_mmx_psrli_q:
8378 case Intrinsic::x86_mmx_psrai_w:
8379 case Intrinsic::x86_mmx_psrai_d: {
8380 SDValue ShAmt = Op.getOperand(2);
8381 if (isa<ConstantSDNode>(ShAmt))
8384 unsigned NewIntNo = 0;
8385 EVT ShAmtVT = MVT::v4i32;
8387 case Intrinsic::x86_sse2_pslli_w:
8388 NewIntNo = Intrinsic::x86_sse2_psll_w;
8390 case Intrinsic::x86_sse2_pslli_d:
8391 NewIntNo = Intrinsic::x86_sse2_psll_d;
8393 case Intrinsic::x86_sse2_pslli_q:
8394 NewIntNo = Intrinsic::x86_sse2_psll_q;
8396 case Intrinsic::x86_sse2_psrli_w:
8397 NewIntNo = Intrinsic::x86_sse2_psrl_w;
8399 case Intrinsic::x86_sse2_psrli_d:
8400 NewIntNo = Intrinsic::x86_sse2_psrl_d;
8402 case Intrinsic::x86_sse2_psrli_q:
8403 NewIntNo = Intrinsic::x86_sse2_psrl_q;
8405 case Intrinsic::x86_sse2_psrai_w:
8406 NewIntNo = Intrinsic::x86_sse2_psra_w;
8408 case Intrinsic::x86_sse2_psrai_d:
8409 NewIntNo = Intrinsic::x86_sse2_psra_d;
8412 ShAmtVT = MVT::v2i32;
8414 case Intrinsic::x86_mmx_pslli_w:
8415 NewIntNo = Intrinsic::x86_mmx_psll_w;
8417 case Intrinsic::x86_mmx_pslli_d:
8418 NewIntNo = Intrinsic::x86_mmx_psll_d;
8420 case Intrinsic::x86_mmx_pslli_q:
8421 NewIntNo = Intrinsic::x86_mmx_psll_q;
8423 case Intrinsic::x86_mmx_psrli_w:
8424 NewIntNo = Intrinsic::x86_mmx_psrl_w;
8426 case Intrinsic::x86_mmx_psrli_d:
8427 NewIntNo = Intrinsic::x86_mmx_psrl_d;
8429 case Intrinsic::x86_mmx_psrli_q:
8430 NewIntNo = Intrinsic::x86_mmx_psrl_q;
8432 case Intrinsic::x86_mmx_psrai_w:
8433 NewIntNo = Intrinsic::x86_mmx_psra_w;
8435 case Intrinsic::x86_mmx_psrai_d:
8436 NewIntNo = Intrinsic::x86_mmx_psra_d;
8438 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8444 // The vector shift intrinsics with scalars uses 32b shift amounts but
8445 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8449 ShOps[1] = DAG.getConstant(0, MVT::i32);
8450 if (ShAmtVT == MVT::v4i32) {
8451 ShOps[2] = DAG.getUNDEF(MVT::i32);
8452 ShOps[3] = DAG.getUNDEF(MVT::i32);
8453 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8455 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8456 // FIXME this must be lowered to get rid of the invalid type.
8459 EVT VT = Op.getValueType();
8460 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8461 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8462 DAG.getConstant(NewIntNo, MVT::i32),
8463 Op.getOperand(1), ShAmt);
8468 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8469 SelectionDAG &DAG) const {
8470 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8471 MFI->setReturnAddressIsTaken(true);
8473 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8474 DebugLoc dl = Op.getDebugLoc();
8477 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8479 DAG.getConstant(TD->getPointerSize(),
8480 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8481 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8482 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8484 MachinePointerInfo(), false, false, 0);
8487 // Just load the return address.
8488 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8489 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8490 RetAddrFI, MachinePointerInfo(), false, false, 0);
8493 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8494 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8495 MFI->setFrameAddressIsTaken(true);
8497 EVT VT = Op.getValueType();
8498 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
8499 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8500 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8501 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8503 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8504 MachinePointerInfo(),
8509 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8510 SelectionDAG &DAG) const {
8511 return DAG.getIntPtrConstant(2*TD->getPointerSize());
8514 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8515 MachineFunction &MF = DAG.getMachineFunction();
8516 SDValue Chain = Op.getOperand(0);
8517 SDValue Offset = Op.getOperand(1);
8518 SDValue Handler = Op.getOperand(2);
8519 DebugLoc dl = Op.getDebugLoc();
8521 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8522 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8524 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8526 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8527 DAG.getIntPtrConstant(TD->getPointerSize()));
8528 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8529 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8531 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8532 MF.getRegInfo().addLiveOut(StoreAddrReg);
8534 return DAG.getNode(X86ISD::EH_RETURN, dl,
8536 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8539 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8540 SelectionDAG &DAG) const {
8541 SDValue Root = Op.getOperand(0);
8542 SDValue Trmp = Op.getOperand(1); // trampoline
8543 SDValue FPtr = Op.getOperand(2); // nested function
8544 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8545 DebugLoc dl = Op.getDebugLoc();
8547 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8549 if (Subtarget->is64Bit()) {
8550 SDValue OutChains[6];
8552 // Large code-model.
8553 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8554 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8556 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8557 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8559 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8561 // Load the pointer to the nested function into R11.
8562 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8563 SDValue Addr = Trmp;
8564 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8565 Addr, MachinePointerInfo(TrmpAddr),
8568 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8569 DAG.getConstant(2, MVT::i64));
8570 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8571 MachinePointerInfo(TrmpAddr, 2),
8574 // Load the 'nest' parameter value into R10.
8575 // R10 is specified in X86CallingConv.td
8576 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8577 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8578 DAG.getConstant(10, MVT::i64));
8579 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8580 Addr, MachinePointerInfo(TrmpAddr, 10),
8583 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8584 DAG.getConstant(12, MVT::i64));
8585 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8586 MachinePointerInfo(TrmpAddr, 12),
8589 // Jump to the nested function.
8590 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8591 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8592 DAG.getConstant(20, MVT::i64));
8593 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8594 Addr, MachinePointerInfo(TrmpAddr, 20),
8597 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8598 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8599 DAG.getConstant(22, MVT::i64));
8600 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8601 MachinePointerInfo(TrmpAddr, 22),
8605 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8606 return DAG.getMergeValues(Ops, 2, dl);
8608 const Function *Func =
8609 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8610 CallingConv::ID CC = Func->getCallingConv();
8615 llvm_unreachable("Unsupported calling convention");
8616 case CallingConv::C:
8617 case CallingConv::X86_StdCall: {
8618 // Pass 'nest' parameter in ECX.
8619 // Must be kept in sync with X86CallingConv.td
8622 // Check that ECX wasn't needed by an 'inreg' parameter.
8623 const FunctionType *FTy = Func->getFunctionType();
8624 const AttrListPtr &Attrs = Func->getAttributes();
8626 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8627 unsigned InRegCount = 0;
8630 for (FunctionType::param_iterator I = FTy->param_begin(),
8631 E = FTy->param_end(); I != E; ++I, ++Idx)
8632 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8633 // FIXME: should only count parameters that are lowered to integers.
8634 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8636 if (InRegCount > 2) {
8637 report_fatal_error("Nest register in use - reduce number of inreg"
8643 case CallingConv::X86_FastCall:
8644 case CallingConv::X86_ThisCall:
8645 case CallingConv::Fast:
8646 // Pass 'nest' parameter in EAX.
8647 // Must be kept in sync with X86CallingConv.td
8652 SDValue OutChains[4];
8655 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8656 DAG.getConstant(10, MVT::i32));
8657 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8659 // This is storing the opcode for MOV32ri.
8660 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8661 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8662 OutChains[0] = DAG.getStore(Root, dl,
8663 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8664 Trmp, MachinePointerInfo(TrmpAddr),
8667 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8668 DAG.getConstant(1, MVT::i32));
8669 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8670 MachinePointerInfo(TrmpAddr, 1),
8673 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8674 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8675 DAG.getConstant(5, MVT::i32));
8676 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8677 MachinePointerInfo(TrmpAddr, 5),
8680 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8681 DAG.getConstant(6, MVT::i32));
8682 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8683 MachinePointerInfo(TrmpAddr, 6),
8687 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8688 return DAG.getMergeValues(Ops, 2, dl);
8692 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8693 SelectionDAG &DAG) const {
8695 The rounding mode is in bits 11:10 of FPSR, and has the following
8702 FLT_ROUNDS, on the other hand, expects the following:
8709 To perform the conversion, we do:
8710 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8713 MachineFunction &MF = DAG.getMachineFunction();
8714 const TargetMachine &TM = MF.getTarget();
8715 const TargetFrameLowering &TFI = *TM.getFrameLowering();
8716 unsigned StackAlignment = TFI.getStackAlignment();
8717 EVT VT = Op.getValueType();
8718 DebugLoc DL = Op.getDebugLoc();
8720 // Save FP Control Word to stack slot
8721 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8722 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8725 MachineMemOperand *MMO =
8726 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8727 MachineMemOperand::MOStore, 2, 2);
8729 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8730 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8731 DAG.getVTList(MVT::Other),
8732 Ops, 2, MVT::i16, MMO);
8734 // Load FP Control Word from stack slot
8735 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8736 MachinePointerInfo(), false, false, 0);
8738 // Transform as necessary
8740 DAG.getNode(ISD::SRL, DL, MVT::i16,
8741 DAG.getNode(ISD::AND, DL, MVT::i16,
8742 CWD, DAG.getConstant(0x800, MVT::i16)),
8743 DAG.getConstant(11, MVT::i8));
8745 DAG.getNode(ISD::SRL, DL, MVT::i16,
8746 DAG.getNode(ISD::AND, DL, MVT::i16,
8747 CWD, DAG.getConstant(0x400, MVT::i16)),
8748 DAG.getConstant(9, MVT::i8));
8751 DAG.getNode(ISD::AND, DL, MVT::i16,
8752 DAG.getNode(ISD::ADD, DL, MVT::i16,
8753 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8754 DAG.getConstant(1, MVT::i16)),
8755 DAG.getConstant(3, MVT::i16));
8758 return DAG.getNode((VT.getSizeInBits() < 16 ?
8759 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8762 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8763 EVT VT = Op.getValueType();
8765 unsigned NumBits = VT.getSizeInBits();
8766 DebugLoc dl = Op.getDebugLoc();
8768 Op = Op.getOperand(0);
8769 if (VT == MVT::i8) {
8770 // Zero extend to i32 since there is not an i8 bsr.
8772 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8775 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8776 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8777 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8779 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8782 DAG.getConstant(NumBits+NumBits-1, OpVT),
8783 DAG.getConstant(X86::COND_E, MVT::i8),
8786 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8788 // Finally xor with NumBits-1.
8789 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8792 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8796 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8797 EVT VT = Op.getValueType();
8799 unsigned NumBits = VT.getSizeInBits();
8800 DebugLoc dl = Op.getDebugLoc();
8802 Op = Op.getOperand(0);
8803 if (VT == MVT::i8) {
8805 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8808 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8809 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8810 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8812 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8815 DAG.getConstant(NumBits, OpVT),
8816 DAG.getConstant(X86::COND_E, MVT::i8),
8819 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8822 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8826 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8827 EVT VT = Op.getValueType();
8828 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8829 DebugLoc dl = Op.getDebugLoc();
8831 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8832 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8833 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8834 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8835 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8837 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8838 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8839 // return AloBlo + AloBhi + AhiBlo;
8841 SDValue A = Op.getOperand(0);
8842 SDValue B = Op.getOperand(1);
8844 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8845 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8846 A, DAG.getConstant(32, MVT::i32));
8847 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8848 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8849 B, DAG.getConstant(32, MVT::i32));
8850 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8851 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8853 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8854 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8856 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8857 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8859 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8860 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8861 AloBhi, DAG.getConstant(32, MVT::i32));
8862 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8863 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8864 AhiBlo, DAG.getConstant(32, MVT::i32));
8865 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8866 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8870 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8872 EVT VT = Op.getValueType();
8873 DebugLoc dl = Op.getDebugLoc();
8874 SDValue R = Op.getOperand(0);
8875 SDValue Amt = Op.getOperand(1);
8877 LLVMContext *Context = DAG.getContext();
8880 if (!Subtarget->hasSSE2()) return SDValue();
8882 // Optimize shl/srl/sra with constant shift amount.
8883 if (isSplatVector(Amt.getNode())) {
8884 SDValue SclrAmt = Amt->getOperand(0);
8885 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8886 uint64_t ShiftAmt = C->getZExtValue();
8888 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8889 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8890 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8891 R, DAG.getConstant(ShiftAmt, MVT::i32));
8893 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
8894 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8895 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8896 R, DAG.getConstant(ShiftAmt, MVT::i32));
8898 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
8899 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8900 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8901 R, DAG.getConstant(ShiftAmt, MVT::i32));
8903 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
8904 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8905 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8906 R, DAG.getConstant(ShiftAmt, MVT::i32));
8908 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
8909 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8910 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8911 R, DAG.getConstant(ShiftAmt, MVT::i32));
8913 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
8914 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8915 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8916 R, DAG.getConstant(ShiftAmt, MVT::i32));
8918 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
8919 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8920 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8921 R, DAG.getConstant(ShiftAmt, MVT::i32));
8923 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
8924 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8925 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8926 R, DAG.getConstant(ShiftAmt, MVT::i32));
8930 // Lower SHL with variable shift amount.
8931 // Cannot lower SHL without SSE4.1 or later.
8932 if (!Subtarget->hasSSE41()) return SDValue();
8934 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
8935 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8936 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8937 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8939 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8941 std::vector<Constant*> CV(4, CI);
8942 Constant *C = ConstantVector::get(CV);
8943 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8944 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8945 MachinePointerInfo::getConstantPool(),
8948 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8949 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8950 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8951 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8953 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
8955 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8956 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8957 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8959 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8960 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8962 std::vector<Constant*> CVM1(16, CM1);
8963 std::vector<Constant*> CVM2(16, CM2);
8964 Constant *C = ConstantVector::get(CVM1);
8965 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8966 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8967 MachinePointerInfo::getConstantPool(),
8970 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8971 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8972 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8973 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8974 DAG.getConstant(4, MVT::i32));
8975 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8977 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8979 C = ConstantVector::get(CVM2);
8980 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8981 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8982 MachinePointerInfo::getConstantPool(),
8985 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8986 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8987 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8988 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8989 DAG.getConstant(2, MVT::i32));
8990 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8992 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8994 // return pblendv(r, r+r, a);
8995 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8996 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
9002 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
9003 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
9004 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
9005 // looks for this combo and may remove the "setcc" instruction if the "setcc"
9006 // has only one use.
9007 SDNode *N = Op.getNode();
9008 SDValue LHS = N->getOperand(0);
9009 SDValue RHS = N->getOperand(1);
9010 unsigned BaseOp = 0;
9012 DebugLoc DL = Op.getDebugLoc();
9013 switch (Op.getOpcode()) {
9014 default: llvm_unreachable("Unknown ovf instruction!");
9016 // A subtract of one will be selected as a INC. Note that INC doesn't
9017 // set CF, so we can't do this for UADDO.
9018 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9020 BaseOp = X86ISD::INC;
9024 BaseOp = X86ISD::ADD;
9028 BaseOp = X86ISD::ADD;
9032 // A subtract of one will be selected as a DEC. Note that DEC doesn't
9033 // set CF, so we can't do this for USUBO.
9034 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9036 BaseOp = X86ISD::DEC;
9040 BaseOp = X86ISD::SUB;
9044 BaseOp = X86ISD::SUB;
9048 BaseOp = X86ISD::SMUL;
9051 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9052 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9054 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9057 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9058 DAG.getConstant(X86::COND_O, MVT::i32),
9059 SDValue(Sum.getNode(), 2));
9061 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9066 // Also sets EFLAGS.
9067 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9068 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9071 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9072 DAG.getConstant(Cond, MVT::i32),
9073 SDValue(Sum.getNode(), 1));
9075 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9079 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9080 DebugLoc dl = Op.getDebugLoc();
9082 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
9083 // There isn't any reason to disable it if the target processor supports it.
9084 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
9085 SDValue Chain = Op.getOperand(0);
9086 SDValue Zero = DAG.getConstant(0, MVT::i32);
9088 DAG.getRegister(X86::ESP, MVT::i32), // Base
9089 DAG.getTargetConstant(1, MVT::i8), // Scale
9090 DAG.getRegister(0, MVT::i32), // Index
9091 DAG.getTargetConstant(0, MVT::i32), // Disp
9092 DAG.getRegister(0, MVT::i32), // Segment.
9097 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9098 array_lengthof(Ops));
9099 return SDValue(Res, 0);
9102 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9104 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9106 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9107 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9108 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9109 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9111 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9112 if (!Op1 && !Op2 && !Op3 && Op4)
9113 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9115 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9116 if (Op1 && !Op2 && !Op3 && !Op4)
9117 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9119 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9121 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9124 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9125 EVT T = Op.getValueType();
9126 DebugLoc DL = Op.getDebugLoc();
9129 switch(T.getSimpleVT().SimpleTy) {
9131 assert(false && "Invalid value type!");
9132 case MVT::i8: Reg = X86::AL; size = 1; break;
9133 case MVT::i16: Reg = X86::AX; size = 2; break;
9134 case MVT::i32: Reg = X86::EAX; size = 4; break;
9136 assert(Subtarget->is64Bit() && "Node not type legal!");
9137 Reg = X86::RAX; size = 8;
9140 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9141 Op.getOperand(2), SDValue());
9142 SDValue Ops[] = { cpIn.getValue(0),
9145 DAG.getTargetConstant(size, MVT::i8),
9147 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9148 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9149 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9152 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9156 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9157 SelectionDAG &DAG) const {
9158 assert(Subtarget->is64Bit() && "Result not type legalized?");
9159 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9160 SDValue TheChain = Op.getOperand(0);
9161 DebugLoc dl = Op.getDebugLoc();
9162 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9163 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9164 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9166 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9167 DAG.getConstant(32, MVT::i8));
9169 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9172 return DAG.getMergeValues(Ops, 2, dl);
9175 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9176 SelectionDAG &DAG) const {
9177 EVT SrcVT = Op.getOperand(0).getValueType();
9178 EVT DstVT = Op.getValueType();
9179 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9180 Subtarget->hasMMX() && "Unexpected custom BITCAST");
9181 assert((DstVT == MVT::i64 ||
9182 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9183 "Unexpected custom BITCAST");
9184 // i64 <=> MMX conversions are Legal.
9185 if (SrcVT==MVT::i64 && DstVT.isVector())
9187 if (DstVT==MVT::i64 && SrcVT.isVector())
9189 // MMX <=> MMX conversions are Legal.
9190 if (SrcVT.isVector() && DstVT.isVector())
9192 // All other conversions need to be expanded.
9196 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9197 SDNode *Node = Op.getNode();
9198 DebugLoc dl = Node->getDebugLoc();
9199 EVT T = Node->getValueType(0);
9200 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9201 DAG.getConstant(0, T), Node->getOperand(2));
9202 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9203 cast<AtomicSDNode>(Node)->getMemoryVT(),
9204 Node->getOperand(0),
9205 Node->getOperand(1), negOp,
9206 cast<AtomicSDNode>(Node)->getSrcValue(),
9207 cast<AtomicSDNode>(Node)->getAlignment());
9210 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9211 EVT VT = Op.getNode()->getValueType(0);
9213 // Let legalize expand this if it isn't a legal type yet.
9214 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9217 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9220 bool ExtraOp = false;
9221 switch (Op.getOpcode()) {
9222 default: assert(0 && "Invalid code");
9223 case ISD::ADDC: Opc = X86ISD::ADD; break;
9224 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9225 case ISD::SUBC: Opc = X86ISD::SUB; break;
9226 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9230 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9232 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9233 Op.getOperand(1), Op.getOperand(2));
9236 /// LowerOperation - Provide custom lowering hooks for some operations.
9238 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9239 switch (Op.getOpcode()) {
9240 default: llvm_unreachable("Should not custom lower this!");
9241 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
9242 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
9243 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
9244 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
9245 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
9246 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
9247 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9248 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9249 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
9250 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
9251 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
9252 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9253 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9254 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9255 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
9256 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
9257 case ISD::SHL_PARTS:
9258 case ISD::SRA_PARTS:
9259 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
9260 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
9261 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
9262 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
9263 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
9264 case ISD::FABS: return LowerFABS(Op, DAG);
9265 case ISD::FNEG: return LowerFNEG(Op, DAG);
9266 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
9267 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
9268 case ISD::SETCC: return LowerSETCC(Op, DAG);
9269 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
9270 case ISD::SELECT: return LowerSELECT(Op, DAG);
9271 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
9272 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
9273 case ISD::VASTART: return LowerVASTART(Op, DAG);
9274 case ISD::VAARG: return LowerVAARG(Op, DAG);
9275 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
9276 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9277 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9278 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9279 case ISD::FRAME_TO_ARGS_OFFSET:
9280 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9281 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9282 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
9283 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
9284 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9285 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
9286 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
9287 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
9290 case ISD::SHL: return LowerShift(Op, DAG);
9296 case ISD::UMULO: return LowerXALUO(Op, DAG);
9297 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
9298 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
9302 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9306 void X86TargetLowering::
9307 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9308 SelectionDAG &DAG, unsigned NewOp) const {
9309 EVT T = Node->getValueType(0);
9310 DebugLoc dl = Node->getDebugLoc();
9311 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9313 SDValue Chain = Node->getOperand(0);
9314 SDValue In1 = Node->getOperand(1);
9315 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9316 Node->getOperand(2), DAG.getIntPtrConstant(0));
9317 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9318 Node->getOperand(2), DAG.getIntPtrConstant(1));
9319 SDValue Ops[] = { Chain, In1, In2L, In2H };
9320 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9322 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9323 cast<MemSDNode>(Node)->getMemOperand());
9324 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9325 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9326 Results.push_back(Result.getValue(2));
9329 /// ReplaceNodeResults - Replace a node with an illegal result type
9330 /// with a new node built out of custom code.
9331 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9332 SmallVectorImpl<SDValue>&Results,
9333 SelectionDAG &DAG) const {
9334 DebugLoc dl = N->getDebugLoc();
9335 switch (N->getOpcode()) {
9337 assert(false && "Do not know how to custom type legalize this operation!");
9343 // We don't want to expand or promote these.
9345 case ISD::FP_TO_SINT: {
9346 std::pair<SDValue,SDValue> Vals =
9347 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9348 SDValue FIST = Vals.first, StackSlot = Vals.second;
9349 if (FIST.getNode() != 0) {
9350 EVT VT = N->getValueType(0);
9351 // Return a load from the stack slot.
9352 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9353 MachinePointerInfo(), false, false, 0));
9357 case ISD::READCYCLECOUNTER: {
9358 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9359 SDValue TheChain = N->getOperand(0);
9360 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9361 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9363 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9365 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9366 SDValue Ops[] = { eax, edx };
9367 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9368 Results.push_back(edx.getValue(1));
9371 case ISD::ATOMIC_CMP_SWAP: {
9372 EVT T = N->getValueType(0);
9373 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9374 SDValue cpInL, cpInH;
9375 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9376 DAG.getConstant(0, MVT::i32));
9377 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9378 DAG.getConstant(1, MVT::i32));
9379 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9380 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9382 SDValue swapInL, swapInH;
9383 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9384 DAG.getConstant(0, MVT::i32));
9385 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9386 DAG.getConstant(1, MVT::i32));
9387 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9389 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9390 swapInL.getValue(1));
9391 SDValue Ops[] = { swapInH.getValue(0),
9393 swapInH.getValue(1) };
9394 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9395 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9396 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9398 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9399 MVT::i32, Result.getValue(1));
9400 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9401 MVT::i32, cpOutL.getValue(2));
9402 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9403 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9404 Results.push_back(cpOutH.getValue(1));
9407 case ISD::ATOMIC_LOAD_ADD:
9408 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9410 case ISD::ATOMIC_LOAD_AND:
9411 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9413 case ISD::ATOMIC_LOAD_NAND:
9414 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9416 case ISD::ATOMIC_LOAD_OR:
9417 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9419 case ISD::ATOMIC_LOAD_SUB:
9420 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9422 case ISD::ATOMIC_LOAD_XOR:
9423 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9425 case ISD::ATOMIC_SWAP:
9426 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9431 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9433 default: return NULL;
9434 case X86ISD::BSF: return "X86ISD::BSF";
9435 case X86ISD::BSR: return "X86ISD::BSR";
9436 case X86ISD::SHLD: return "X86ISD::SHLD";
9437 case X86ISD::SHRD: return "X86ISD::SHRD";
9438 case X86ISD::FAND: return "X86ISD::FAND";
9439 case X86ISD::FOR: return "X86ISD::FOR";
9440 case X86ISD::FXOR: return "X86ISD::FXOR";
9441 case X86ISD::FSRL: return "X86ISD::FSRL";
9442 case X86ISD::FILD: return "X86ISD::FILD";
9443 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
9444 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9445 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9446 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9447 case X86ISD::FLD: return "X86ISD::FLD";
9448 case X86ISD::FST: return "X86ISD::FST";
9449 case X86ISD::CALL: return "X86ISD::CALL";
9450 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
9451 case X86ISD::BT: return "X86ISD::BT";
9452 case X86ISD::CMP: return "X86ISD::CMP";
9453 case X86ISD::COMI: return "X86ISD::COMI";
9454 case X86ISD::UCOMI: return "X86ISD::UCOMI";
9455 case X86ISD::SETCC: return "X86ISD::SETCC";
9456 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
9457 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
9458 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
9459 case X86ISD::CMOV: return "X86ISD::CMOV";
9460 case X86ISD::BRCOND: return "X86ISD::BRCOND";
9461 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
9462 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
9463 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
9464 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
9465 case X86ISD::Wrapper: return "X86ISD::Wrapper";
9466 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
9467 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
9468 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
9469 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
9470 case X86ISD::PINSRB: return "X86ISD::PINSRB";
9471 case X86ISD::PINSRW: return "X86ISD::PINSRW";
9472 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
9473 case X86ISD::PANDN: return "X86ISD::PANDN";
9474 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
9475 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
9476 case X86ISD::PSIGND: return "X86ISD::PSIGND";
9477 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB";
9478 case X86ISD::FMAX: return "X86ISD::FMAX";
9479 case X86ISD::FMIN: return "X86ISD::FMIN";
9480 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
9481 case X86ISD::FRCP: return "X86ISD::FRCP";
9482 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
9483 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
9484 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
9485 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
9486 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
9487 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
9488 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
9489 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
9490 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
9491 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
9492 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
9493 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
9494 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
9495 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
9496 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
9497 case X86ISD::VSHL: return "X86ISD::VSHL";
9498 case X86ISD::VSRL: return "X86ISD::VSRL";
9499 case X86ISD::CMPPD: return "X86ISD::CMPPD";
9500 case X86ISD::CMPPS: return "X86ISD::CMPPS";
9501 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
9502 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
9503 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
9504 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
9505 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
9506 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
9507 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
9508 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
9509 case X86ISD::ADD: return "X86ISD::ADD";
9510 case X86ISD::SUB: return "X86ISD::SUB";
9511 case X86ISD::ADC: return "X86ISD::ADC";
9512 case X86ISD::SBB: return "X86ISD::SBB";
9513 case X86ISD::SMUL: return "X86ISD::SMUL";
9514 case X86ISD::UMUL: return "X86ISD::UMUL";
9515 case X86ISD::INC: return "X86ISD::INC";
9516 case X86ISD::DEC: return "X86ISD::DEC";
9517 case X86ISD::OR: return "X86ISD::OR";
9518 case X86ISD::XOR: return "X86ISD::XOR";
9519 case X86ISD::AND: return "X86ISD::AND";
9520 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
9521 case X86ISD::PTEST: return "X86ISD::PTEST";
9522 case X86ISD::TESTP: return "X86ISD::TESTP";
9523 case X86ISD::PALIGN: return "X86ISD::PALIGN";
9524 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
9525 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
9526 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
9527 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
9528 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
9529 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
9530 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
9531 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
9532 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
9533 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
9534 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
9535 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
9536 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
9537 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
9538 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
9539 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
9540 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
9541 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
9542 case X86ISD::MOVSD: return "X86ISD::MOVSD";
9543 case X86ISD::MOVSS: return "X86ISD::MOVSS";
9544 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
9545 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
9546 case X86ISD::VUNPCKLPS: return "X86ISD::VUNPCKLPS";
9547 case X86ISD::VUNPCKLPD: return "X86ISD::VUNPCKLPD";
9548 case X86ISD::VUNPCKLPSY: return "X86ISD::VUNPCKLPSY";
9549 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
9550 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
9551 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
9552 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
9553 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
9554 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
9555 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
9556 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
9557 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
9558 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
9559 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
9560 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9561 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
9562 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
9566 // isLegalAddressingMode - Return true if the addressing mode represented
9567 // by AM is legal for this target, for a load/store of the specified type.
9568 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9569 const Type *Ty) const {
9570 // X86 supports extremely general addressing modes.
9571 CodeModel::Model M = getTargetMachine().getCodeModel();
9572 Reloc::Model R = getTargetMachine().getRelocationModel();
9574 // X86 allows a sign-extended 32-bit immediate field as a displacement.
9575 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9580 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9582 // If a reference to this global requires an extra load, we can't fold it.
9583 if (isGlobalStubReference(GVFlags))
9586 // If BaseGV requires a register for the PIC base, we cannot also have a
9587 // BaseReg specified.
9588 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9591 // If lower 4G is not available, then we must use rip-relative addressing.
9592 if ((M != CodeModel::Small || R != Reloc::Static) &&
9593 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9603 // These scales always work.
9608 // These scales are formed with basereg+scalereg. Only accept if there is
9613 default: // Other stuff never works.
9621 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9622 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9624 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9625 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9626 if (NumBits1 <= NumBits2)
9631 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9632 if (!VT1.isInteger() || !VT2.isInteger())
9634 unsigned NumBits1 = VT1.getSizeInBits();
9635 unsigned NumBits2 = VT2.getSizeInBits();
9636 if (NumBits1 <= NumBits2)
9641 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9642 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9643 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9646 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9647 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9648 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9651 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9652 // i16 instructions are longer (0x66 prefix) and potentially slower.
9653 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9656 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9657 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9658 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9659 /// are assumed to be legal.
9661 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9663 // Very little shuffling can be done for 64-bit vectors right now.
9664 if (VT.getSizeInBits() == 64)
9665 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9667 // FIXME: pshufb, blends, shifts.
9668 return (VT.getVectorNumElements() == 2 ||
9669 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9670 isMOVLMask(M, VT) ||
9671 isSHUFPMask(M, VT) ||
9672 isPSHUFDMask(M, VT) ||
9673 isPSHUFHWMask(M, VT) ||
9674 isPSHUFLWMask(M, VT) ||
9675 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9676 isUNPCKLMask(M, VT) ||
9677 isUNPCKHMask(M, VT) ||
9678 isUNPCKL_v_undef_Mask(M, VT) ||
9679 isUNPCKH_v_undef_Mask(M, VT));
9683 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9685 unsigned NumElts = VT.getVectorNumElements();
9686 // FIXME: This collection of masks seems suspect.
9689 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9690 return (isMOVLMask(Mask, VT) ||
9691 isCommutedMOVLMask(Mask, VT, true) ||
9692 isSHUFPMask(Mask, VT) ||
9693 isCommutedSHUFPMask(Mask, VT));
9698 //===----------------------------------------------------------------------===//
9699 // X86 Scheduler Hooks
9700 //===----------------------------------------------------------------------===//
9702 // private utility function
9704 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9705 MachineBasicBlock *MBB,
9712 TargetRegisterClass *RC,
9713 bool invSrc) const {
9714 // For the atomic bitwise operator, we generate
9717 // ld t1 = [bitinstr.addr]
9718 // op t2 = t1, [bitinstr.val]
9720 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9722 // fallthrough -->nextMBB
9723 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9724 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9725 MachineFunction::iterator MBBIter = MBB;
9728 /// First build the CFG
9729 MachineFunction *F = MBB->getParent();
9730 MachineBasicBlock *thisMBB = MBB;
9731 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9732 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9733 F->insert(MBBIter, newMBB);
9734 F->insert(MBBIter, nextMBB);
9736 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9737 nextMBB->splice(nextMBB->begin(), thisMBB,
9738 llvm::next(MachineBasicBlock::iterator(bInstr)),
9740 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9742 // Update thisMBB to fall through to newMBB
9743 thisMBB->addSuccessor(newMBB);
9745 // newMBB jumps to itself and fall through to nextMBB
9746 newMBB->addSuccessor(nextMBB);
9747 newMBB->addSuccessor(newMBB);
9749 // Insert instructions into newMBB based on incoming instruction
9750 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9751 "unexpected number of operands");
9752 DebugLoc dl = bInstr->getDebugLoc();
9753 MachineOperand& destOper = bInstr->getOperand(0);
9754 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9755 int numArgs = bInstr->getNumOperands() - 1;
9756 for (int i=0; i < numArgs; ++i)
9757 argOpers[i] = &bInstr->getOperand(i+1);
9759 // x86 address has 4 operands: base, index, scale, and displacement
9760 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9761 int valArgIndx = lastAddrIndx + 1;
9763 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9764 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9765 for (int i=0; i <= lastAddrIndx; ++i)
9766 (*MIB).addOperand(*argOpers[i]);
9768 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9770 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9775 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9776 assert((argOpers[valArgIndx]->isReg() ||
9777 argOpers[valArgIndx]->isImm()) &&
9779 if (argOpers[valArgIndx]->isReg())
9780 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9782 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9784 (*MIB).addOperand(*argOpers[valArgIndx]);
9786 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9789 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9790 for (int i=0; i <= lastAddrIndx; ++i)
9791 (*MIB).addOperand(*argOpers[i]);
9793 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9794 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9795 bInstr->memoperands_end());
9797 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9801 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9803 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9807 // private utility function: 64 bit atomics on 32 bit host.
9809 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9810 MachineBasicBlock *MBB,
9815 bool invSrc) const {
9816 // For the atomic bitwise operator, we generate
9817 // thisMBB (instructions are in pairs, except cmpxchg8b)
9818 // ld t1,t2 = [bitinstr.addr]
9820 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9821 // op t5, t6 <- out1, out2, [bitinstr.val]
9822 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9823 // mov ECX, EBX <- t5, t6
9824 // mov EAX, EDX <- t1, t2
9825 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9826 // mov t3, t4 <- EAX, EDX
9828 // result in out1, out2
9829 // fallthrough -->nextMBB
9831 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9832 const unsigned LoadOpc = X86::MOV32rm;
9833 const unsigned NotOpc = X86::NOT32r;
9834 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9835 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9836 MachineFunction::iterator MBBIter = MBB;
9839 /// First build the CFG
9840 MachineFunction *F = MBB->getParent();
9841 MachineBasicBlock *thisMBB = MBB;
9842 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9843 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9844 F->insert(MBBIter, newMBB);
9845 F->insert(MBBIter, nextMBB);
9847 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9848 nextMBB->splice(nextMBB->begin(), thisMBB,
9849 llvm::next(MachineBasicBlock::iterator(bInstr)),
9851 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9853 // Update thisMBB to fall through to newMBB
9854 thisMBB->addSuccessor(newMBB);
9856 // newMBB jumps to itself and fall through to nextMBB
9857 newMBB->addSuccessor(nextMBB);
9858 newMBB->addSuccessor(newMBB);
9860 DebugLoc dl = bInstr->getDebugLoc();
9861 // Insert instructions into newMBB based on incoming instruction
9862 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9863 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9864 "unexpected number of operands");
9865 MachineOperand& dest1Oper = bInstr->getOperand(0);
9866 MachineOperand& dest2Oper = bInstr->getOperand(1);
9867 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9868 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9869 argOpers[i] = &bInstr->getOperand(i+2);
9871 // We use some of the operands multiple times, so conservatively just
9872 // clear any kill flags that might be present.
9873 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9874 argOpers[i]->setIsKill(false);
9877 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9878 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9880 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9881 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9882 for (int i=0; i <= lastAddrIndx; ++i)
9883 (*MIB).addOperand(*argOpers[i]);
9884 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9885 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9886 // add 4 to displacement.
9887 for (int i=0; i <= lastAddrIndx-2; ++i)
9888 (*MIB).addOperand(*argOpers[i]);
9889 MachineOperand newOp3 = *(argOpers[3]);
9891 newOp3.setImm(newOp3.getImm()+4);
9893 newOp3.setOffset(newOp3.getOffset()+4);
9894 (*MIB).addOperand(newOp3);
9895 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9897 // t3/4 are defined later, at the bottom of the loop
9898 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9899 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9900 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9901 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9902 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9903 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9905 // The subsequent operations should be using the destination registers of
9906 //the PHI instructions.
9908 t1 = F->getRegInfo().createVirtualRegister(RC);
9909 t2 = F->getRegInfo().createVirtualRegister(RC);
9910 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9911 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9913 t1 = dest1Oper.getReg();
9914 t2 = dest2Oper.getReg();
9917 int valArgIndx = lastAddrIndx + 1;
9918 assert((argOpers[valArgIndx]->isReg() ||
9919 argOpers[valArgIndx]->isImm()) &&
9921 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9922 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9923 if (argOpers[valArgIndx]->isReg())
9924 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9926 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9927 if (regOpcL != X86::MOV32rr)
9929 (*MIB).addOperand(*argOpers[valArgIndx]);
9930 assert(argOpers[valArgIndx + 1]->isReg() ==
9931 argOpers[valArgIndx]->isReg());
9932 assert(argOpers[valArgIndx + 1]->isImm() ==
9933 argOpers[valArgIndx]->isImm());
9934 if (argOpers[valArgIndx + 1]->isReg())
9935 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9937 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9938 if (regOpcH != X86::MOV32rr)
9940 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9942 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9944 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9947 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9949 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9952 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9953 for (int i=0; i <= lastAddrIndx; ++i)
9954 (*MIB).addOperand(*argOpers[i]);
9956 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9957 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9958 bInstr->memoperands_end());
9960 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9961 MIB.addReg(X86::EAX);
9962 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9963 MIB.addReg(X86::EDX);
9966 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9968 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9972 // private utility function
9974 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9975 MachineBasicBlock *MBB,
9976 unsigned cmovOpc) const {
9977 // For the atomic min/max operator, we generate
9980 // ld t1 = [min/max.addr]
9981 // mov t2 = [min/max.val]
9983 // cmov[cond] t2 = t1
9985 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9987 // fallthrough -->nextMBB
9989 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9990 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9991 MachineFunction::iterator MBBIter = MBB;
9994 /// First build the CFG
9995 MachineFunction *F = MBB->getParent();
9996 MachineBasicBlock *thisMBB = MBB;
9997 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9998 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9999 F->insert(MBBIter, newMBB);
10000 F->insert(MBBIter, nextMBB);
10002 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10003 nextMBB->splice(nextMBB->begin(), thisMBB,
10004 llvm::next(MachineBasicBlock::iterator(mInstr)),
10006 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10008 // Update thisMBB to fall through to newMBB
10009 thisMBB->addSuccessor(newMBB);
10011 // newMBB jumps to newMBB and fall through to nextMBB
10012 newMBB->addSuccessor(nextMBB);
10013 newMBB->addSuccessor(newMBB);
10015 DebugLoc dl = mInstr->getDebugLoc();
10016 // Insert instructions into newMBB based on incoming instruction
10017 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10018 "unexpected number of operands");
10019 MachineOperand& destOper = mInstr->getOperand(0);
10020 MachineOperand* argOpers[2 + X86::AddrNumOperands];
10021 int numArgs = mInstr->getNumOperands() - 1;
10022 for (int i=0; i < numArgs; ++i)
10023 argOpers[i] = &mInstr->getOperand(i+1);
10025 // x86 address has 4 operands: base, index, scale, and displacement
10026 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10027 int valArgIndx = lastAddrIndx + 1;
10029 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10030 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10031 for (int i=0; i <= lastAddrIndx; ++i)
10032 (*MIB).addOperand(*argOpers[i]);
10034 // We only support register and immediate values
10035 assert((argOpers[valArgIndx]->isReg() ||
10036 argOpers[valArgIndx]->isImm()) &&
10037 "invalid operand");
10039 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10040 if (argOpers[valArgIndx]->isReg())
10041 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10043 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10044 (*MIB).addOperand(*argOpers[valArgIndx]);
10046 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10049 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10054 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10055 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10059 // Cmp and exchange if none has modified the memory location
10060 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10061 for (int i=0; i <= lastAddrIndx; ++i)
10062 (*MIB).addOperand(*argOpers[i]);
10064 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10065 (*MIB).setMemRefs(mInstr->memoperands_begin(),
10066 mInstr->memoperands_end());
10068 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10069 MIB.addReg(X86::EAX);
10072 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10074 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
10078 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10079 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10080 // in the .td file.
10081 MachineBasicBlock *
10082 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10083 unsigned numArgs, bool memArg) const {
10084 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10085 "Target must have SSE4.2 or AVX features enabled");
10087 DebugLoc dl = MI->getDebugLoc();
10088 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10090 if (!Subtarget->hasAVX()) {
10092 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10094 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10097 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10099 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10102 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10103 for (unsigned i = 0; i < numArgs; ++i) {
10104 MachineOperand &Op = MI->getOperand(i+1);
10105 if (!(Op.isReg() && Op.isImplicit()))
10106 MIB.addOperand(Op);
10108 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10109 .addReg(X86::XMM0);
10111 MI->eraseFromParent();
10115 MachineBasicBlock *
10116 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10117 DebugLoc dl = MI->getDebugLoc();
10118 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10120 // Address into RAX/EAX, other two args into ECX, EDX.
10121 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10122 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10123 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10124 for (int i = 0; i < X86::AddrNumOperands; ++i)
10125 MIB.addOperand(MI->getOperand(i));
10127 unsigned ValOps = X86::AddrNumOperands;
10128 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10129 .addReg(MI->getOperand(ValOps).getReg());
10130 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10131 .addReg(MI->getOperand(ValOps+1).getReg());
10133 // The instruction doesn't actually take any operands though.
10134 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10136 MI->eraseFromParent(); // The pseudo is gone now.
10140 MachineBasicBlock *
10141 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10142 DebugLoc dl = MI->getDebugLoc();
10143 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10145 // First arg in ECX, the second in EAX.
10146 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10147 .addReg(MI->getOperand(0).getReg());
10148 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10149 .addReg(MI->getOperand(1).getReg());
10151 // The instruction doesn't actually take any operands though.
10152 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10154 MI->eraseFromParent(); // The pseudo is gone now.
10158 MachineBasicBlock *
10159 X86TargetLowering::EmitVAARG64WithCustomInserter(
10161 MachineBasicBlock *MBB) const {
10162 // Emit va_arg instruction on X86-64.
10164 // Operands to this pseudo-instruction:
10165 // 0 ) Output : destination address (reg)
10166 // 1-5) Input : va_list address (addr, i64mem)
10167 // 6 ) ArgSize : Size (in bytes) of vararg type
10168 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10169 // 8 ) Align : Alignment of type
10170 // 9 ) EFLAGS (implicit-def)
10172 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10173 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10175 unsigned DestReg = MI->getOperand(0).getReg();
10176 MachineOperand &Base = MI->getOperand(1);
10177 MachineOperand &Scale = MI->getOperand(2);
10178 MachineOperand &Index = MI->getOperand(3);
10179 MachineOperand &Disp = MI->getOperand(4);
10180 MachineOperand &Segment = MI->getOperand(5);
10181 unsigned ArgSize = MI->getOperand(6).getImm();
10182 unsigned ArgMode = MI->getOperand(7).getImm();
10183 unsigned Align = MI->getOperand(8).getImm();
10185 // Memory Reference
10186 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10187 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10188 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10190 // Machine Information
10191 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10192 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10193 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10194 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10195 DebugLoc DL = MI->getDebugLoc();
10197 // struct va_list {
10200 // i64 overflow_area (address)
10201 // i64 reg_save_area (address)
10203 // sizeof(va_list) = 24
10204 // alignment(va_list) = 8
10206 unsigned TotalNumIntRegs = 6;
10207 unsigned TotalNumXMMRegs = 8;
10208 bool UseGPOffset = (ArgMode == 1);
10209 bool UseFPOffset = (ArgMode == 2);
10210 unsigned MaxOffset = TotalNumIntRegs * 8 +
10211 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10213 /* Align ArgSize to a multiple of 8 */
10214 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10215 bool NeedsAlign = (Align > 8);
10217 MachineBasicBlock *thisMBB = MBB;
10218 MachineBasicBlock *overflowMBB;
10219 MachineBasicBlock *offsetMBB;
10220 MachineBasicBlock *endMBB;
10222 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
10223 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
10224 unsigned OffsetReg = 0;
10226 if (!UseGPOffset && !UseFPOffset) {
10227 // If we only pull from the overflow region, we don't create a branch.
10228 // We don't need to alter control flow.
10229 OffsetDestReg = 0; // unused
10230 OverflowDestReg = DestReg;
10233 overflowMBB = thisMBB;
10236 // First emit code to check if gp_offset (or fp_offset) is below the bound.
10237 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10238 // If not, pull from overflow_area. (branch to overflowMBB)
10243 // offsetMBB overflowMBB
10248 // Registers for the PHI in endMBB
10249 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10250 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10252 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10253 MachineFunction *MF = MBB->getParent();
10254 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10255 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10256 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10258 MachineFunction::iterator MBBIter = MBB;
10261 // Insert the new basic blocks
10262 MF->insert(MBBIter, offsetMBB);
10263 MF->insert(MBBIter, overflowMBB);
10264 MF->insert(MBBIter, endMBB);
10266 // Transfer the remainder of MBB and its successor edges to endMBB.
10267 endMBB->splice(endMBB->begin(), thisMBB,
10268 llvm::next(MachineBasicBlock::iterator(MI)),
10270 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10272 // Make offsetMBB and overflowMBB successors of thisMBB
10273 thisMBB->addSuccessor(offsetMBB);
10274 thisMBB->addSuccessor(overflowMBB);
10276 // endMBB is a successor of both offsetMBB and overflowMBB
10277 offsetMBB->addSuccessor(endMBB);
10278 overflowMBB->addSuccessor(endMBB);
10280 // Load the offset value into a register
10281 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10282 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10286 .addDisp(Disp, UseFPOffset ? 4 : 0)
10287 .addOperand(Segment)
10288 .setMemRefs(MMOBegin, MMOEnd);
10290 // Check if there is enough room left to pull this argument.
10291 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10293 .addImm(MaxOffset + 8 - ArgSizeA8);
10295 // Branch to "overflowMBB" if offset >= max
10296 // Fall through to "offsetMBB" otherwise
10297 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10298 .addMBB(overflowMBB);
10301 // In offsetMBB, emit code to use the reg_save_area.
10303 assert(OffsetReg != 0);
10305 // Read the reg_save_area address.
10306 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10307 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10312 .addOperand(Segment)
10313 .setMemRefs(MMOBegin, MMOEnd);
10315 // Zero-extend the offset
10316 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10317 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10320 .addImm(X86::sub_32bit);
10322 // Add the offset to the reg_save_area to get the final address.
10323 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10324 .addReg(OffsetReg64)
10325 .addReg(RegSaveReg);
10327 // Compute the offset for the next argument
10328 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10329 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10331 .addImm(UseFPOffset ? 16 : 8);
10333 // Store it back into the va_list.
10334 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10338 .addDisp(Disp, UseFPOffset ? 4 : 0)
10339 .addOperand(Segment)
10340 .addReg(NextOffsetReg)
10341 .setMemRefs(MMOBegin, MMOEnd);
10344 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10349 // Emit code to use overflow area
10352 // Load the overflow_area address into a register.
10353 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10354 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10359 .addOperand(Segment)
10360 .setMemRefs(MMOBegin, MMOEnd);
10362 // If we need to align it, do so. Otherwise, just copy the address
10363 // to OverflowDestReg.
10365 // Align the overflow address
10366 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10367 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10369 // aligned_addr = (addr + (align-1)) & ~(align-1)
10370 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10371 .addReg(OverflowAddrReg)
10374 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10376 .addImm(~(uint64_t)(Align-1));
10378 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10379 .addReg(OverflowAddrReg);
10382 // Compute the next overflow address after this argument.
10383 // (the overflow address should be kept 8-byte aligned)
10384 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10385 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10386 .addReg(OverflowDestReg)
10387 .addImm(ArgSizeA8);
10389 // Store the new overflow address.
10390 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10395 .addOperand(Segment)
10396 .addReg(NextAddrReg)
10397 .setMemRefs(MMOBegin, MMOEnd);
10399 // If we branched, emit the PHI to the front of endMBB.
10401 BuildMI(*endMBB, endMBB->begin(), DL,
10402 TII->get(X86::PHI), DestReg)
10403 .addReg(OffsetDestReg).addMBB(offsetMBB)
10404 .addReg(OverflowDestReg).addMBB(overflowMBB);
10407 // Erase the pseudo instruction
10408 MI->eraseFromParent();
10413 MachineBasicBlock *
10414 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10416 MachineBasicBlock *MBB) const {
10417 // Emit code to save XMM registers to the stack. The ABI says that the
10418 // number of registers to save is given in %al, so it's theoretically
10419 // possible to do an indirect jump trick to avoid saving all of them,
10420 // however this code takes a simpler approach and just executes all
10421 // of the stores if %al is non-zero. It's less code, and it's probably
10422 // easier on the hardware branch predictor, and stores aren't all that
10423 // expensive anyway.
10425 // Create the new basic blocks. One block contains all the XMM stores,
10426 // and one block is the final destination regardless of whether any
10427 // stores were performed.
10428 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10429 MachineFunction *F = MBB->getParent();
10430 MachineFunction::iterator MBBIter = MBB;
10432 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10433 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10434 F->insert(MBBIter, XMMSaveMBB);
10435 F->insert(MBBIter, EndMBB);
10437 // Transfer the remainder of MBB and its successor edges to EndMBB.
10438 EndMBB->splice(EndMBB->begin(), MBB,
10439 llvm::next(MachineBasicBlock::iterator(MI)),
10441 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10443 // The original block will now fall through to the XMM save block.
10444 MBB->addSuccessor(XMMSaveMBB);
10445 // The XMMSaveMBB will fall through to the end block.
10446 XMMSaveMBB->addSuccessor(EndMBB);
10448 // Now add the instructions.
10449 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10450 DebugLoc DL = MI->getDebugLoc();
10452 unsigned CountReg = MI->getOperand(0).getReg();
10453 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10454 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10456 if (!Subtarget->isTargetWin64()) {
10457 // If %al is 0, branch around the XMM save block.
10458 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10459 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10460 MBB->addSuccessor(EndMBB);
10463 // In the XMM save block, save all the XMM argument registers.
10464 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10465 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10466 MachineMemOperand *MMO =
10467 F->getMachineMemOperand(
10468 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10469 MachineMemOperand::MOStore,
10470 /*Size=*/16, /*Align=*/16);
10471 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10472 .addFrameIndex(RegSaveFrameIndex)
10473 .addImm(/*Scale=*/1)
10474 .addReg(/*IndexReg=*/0)
10475 .addImm(/*Disp=*/Offset)
10476 .addReg(/*Segment=*/0)
10477 .addReg(MI->getOperand(i).getReg())
10478 .addMemOperand(MMO);
10481 MI->eraseFromParent(); // The pseudo instruction is gone now.
10486 MachineBasicBlock *
10487 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10488 MachineBasicBlock *BB) const {
10489 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10490 DebugLoc DL = MI->getDebugLoc();
10492 // To "insert" a SELECT_CC instruction, we actually have to insert the
10493 // diamond control-flow pattern. The incoming instruction knows the
10494 // destination vreg to set, the condition code register to branch on, the
10495 // true/false values to select between, and a branch opcode to use.
10496 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10497 MachineFunction::iterator It = BB;
10503 // cmpTY ccX, r1, r2
10505 // fallthrough --> copy0MBB
10506 MachineBasicBlock *thisMBB = BB;
10507 MachineFunction *F = BB->getParent();
10508 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10509 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10510 F->insert(It, copy0MBB);
10511 F->insert(It, sinkMBB);
10513 // If the EFLAGS register isn't dead in the terminator, then claim that it's
10514 // live into the sink and copy blocks.
10515 const MachineFunction *MF = BB->getParent();
10516 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10517 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10519 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10520 const MachineOperand &MO = MI->getOperand(I);
10521 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10522 unsigned Reg = MO.getReg();
10523 if (Reg != X86::EFLAGS) continue;
10524 copy0MBB->addLiveIn(Reg);
10525 sinkMBB->addLiveIn(Reg);
10528 // Transfer the remainder of BB and its successor edges to sinkMBB.
10529 sinkMBB->splice(sinkMBB->begin(), BB,
10530 llvm::next(MachineBasicBlock::iterator(MI)),
10532 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10534 // Add the true and fallthrough blocks as its successors.
10535 BB->addSuccessor(copy0MBB);
10536 BB->addSuccessor(sinkMBB);
10538 // Create the conditional branch instruction.
10540 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10541 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10544 // %FalseValue = ...
10545 // # fallthrough to sinkMBB
10546 copy0MBB->addSuccessor(sinkMBB);
10549 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10551 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10552 TII->get(X86::PHI), MI->getOperand(0).getReg())
10553 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10554 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10556 MI->eraseFromParent(); // The pseudo instruction is gone now.
10560 MachineBasicBlock *
10561 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10562 MachineBasicBlock *BB) const {
10563 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10564 DebugLoc DL = MI->getDebugLoc();
10566 assert(!Subtarget->isTargetEnvMacho());
10568 // The lowering is pretty easy: we're just emitting the call to _alloca. The
10569 // non-trivial part is impdef of ESP.
10571 if (Subtarget->isTargetWin64()) {
10572 if (Subtarget->isTargetCygMing()) {
10573 // ___chkstk(Mingw64):
10574 // Clobbers R10, R11, RAX and EFLAGS.
10576 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10577 .addExternalSymbol("___chkstk")
10578 .addReg(X86::RAX, RegState::Implicit)
10579 .addReg(X86::RSP, RegState::Implicit)
10580 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10581 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10582 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10584 // __chkstk(MSVCRT): does not update stack pointer.
10585 // Clobbers R10, R11 and EFLAGS.
10586 // FIXME: RAX(allocated size) might be reused and not killed.
10587 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10588 .addExternalSymbol("__chkstk")
10589 .addReg(X86::RAX, RegState::Implicit)
10590 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10591 // RAX has the offset to subtracted from RSP.
10592 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10597 const char *StackProbeSymbol =
10598 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10600 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10601 .addExternalSymbol(StackProbeSymbol)
10602 .addReg(X86::EAX, RegState::Implicit)
10603 .addReg(X86::ESP, RegState::Implicit)
10604 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10605 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10606 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10609 MI->eraseFromParent(); // The pseudo instruction is gone now.
10613 MachineBasicBlock *
10614 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10615 MachineBasicBlock *BB) const {
10616 // This is pretty easy. We're taking the value that we received from
10617 // our load from the relocation, sticking it in either RDI (x86-64)
10618 // or EAX and doing an indirect call. The return value will then
10619 // be in the normal return register.
10620 const X86InstrInfo *TII
10621 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10622 DebugLoc DL = MI->getDebugLoc();
10623 MachineFunction *F = BB->getParent();
10625 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10626 assert(MI->getOperand(3).isGlobal() && "This should be a global");
10628 if (Subtarget->is64Bit()) {
10629 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10630 TII->get(X86::MOV64rm), X86::RDI)
10632 .addImm(0).addReg(0)
10633 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10634 MI->getOperand(3).getTargetFlags())
10636 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10637 addDirectMem(MIB, X86::RDI);
10638 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10639 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10640 TII->get(X86::MOV32rm), X86::EAX)
10642 .addImm(0).addReg(0)
10643 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10644 MI->getOperand(3).getTargetFlags())
10646 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10647 addDirectMem(MIB, X86::EAX);
10649 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10650 TII->get(X86::MOV32rm), X86::EAX)
10651 .addReg(TII->getGlobalBaseReg(F))
10652 .addImm(0).addReg(0)
10653 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10654 MI->getOperand(3).getTargetFlags())
10656 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10657 addDirectMem(MIB, X86::EAX);
10660 MI->eraseFromParent(); // The pseudo instruction is gone now.
10664 MachineBasicBlock *
10665 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10666 MachineBasicBlock *BB) const {
10667 switch (MI->getOpcode()) {
10668 default: assert(false && "Unexpected instr type to insert");
10669 case X86::TAILJMPd64:
10670 case X86::TAILJMPr64:
10671 case X86::TAILJMPm64:
10672 assert(!"TAILJMP64 would not be touched here.");
10673 case X86::TCRETURNdi64:
10674 case X86::TCRETURNri64:
10675 case X86::TCRETURNmi64:
10676 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10677 // On AMD64, additional defs should be added before register allocation.
10678 if (!Subtarget->isTargetWin64()) {
10679 MI->addRegisterDefined(X86::RSI);
10680 MI->addRegisterDefined(X86::RDI);
10681 MI->addRegisterDefined(X86::XMM6);
10682 MI->addRegisterDefined(X86::XMM7);
10683 MI->addRegisterDefined(X86::XMM8);
10684 MI->addRegisterDefined(X86::XMM9);
10685 MI->addRegisterDefined(X86::XMM10);
10686 MI->addRegisterDefined(X86::XMM11);
10687 MI->addRegisterDefined(X86::XMM12);
10688 MI->addRegisterDefined(X86::XMM13);
10689 MI->addRegisterDefined(X86::XMM14);
10690 MI->addRegisterDefined(X86::XMM15);
10693 case X86::WIN_ALLOCA:
10694 return EmitLoweredWinAlloca(MI, BB);
10695 case X86::TLSCall_32:
10696 case X86::TLSCall_64:
10697 return EmitLoweredTLSCall(MI, BB);
10698 case X86::CMOV_GR8:
10699 case X86::CMOV_FR32:
10700 case X86::CMOV_FR64:
10701 case X86::CMOV_V4F32:
10702 case X86::CMOV_V2F64:
10703 case X86::CMOV_V2I64:
10704 case X86::CMOV_GR16:
10705 case X86::CMOV_GR32:
10706 case X86::CMOV_RFP32:
10707 case X86::CMOV_RFP64:
10708 case X86::CMOV_RFP80:
10709 return EmitLoweredSelect(MI, BB);
10711 case X86::FP32_TO_INT16_IN_MEM:
10712 case X86::FP32_TO_INT32_IN_MEM:
10713 case X86::FP32_TO_INT64_IN_MEM:
10714 case X86::FP64_TO_INT16_IN_MEM:
10715 case X86::FP64_TO_INT32_IN_MEM:
10716 case X86::FP64_TO_INT64_IN_MEM:
10717 case X86::FP80_TO_INT16_IN_MEM:
10718 case X86::FP80_TO_INT32_IN_MEM:
10719 case X86::FP80_TO_INT64_IN_MEM: {
10720 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10721 DebugLoc DL = MI->getDebugLoc();
10723 // Change the floating point control register to use "round towards zero"
10724 // mode when truncating to an integer value.
10725 MachineFunction *F = BB->getParent();
10726 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10727 addFrameReference(BuildMI(*BB, MI, DL,
10728 TII->get(X86::FNSTCW16m)), CWFrameIdx);
10730 // Load the old value of the high byte of the control word...
10732 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10733 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10736 // Set the high part to be round to zero...
10737 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10740 // Reload the modified control word now...
10741 addFrameReference(BuildMI(*BB, MI, DL,
10742 TII->get(X86::FLDCW16m)), CWFrameIdx);
10744 // Restore the memory image of control word to original value
10745 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10748 // Get the X86 opcode to use.
10750 switch (MI->getOpcode()) {
10751 default: llvm_unreachable("illegal opcode!");
10752 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10753 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10754 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10755 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10756 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10757 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10758 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10759 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10760 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10764 MachineOperand &Op = MI->getOperand(0);
10766 AM.BaseType = X86AddressMode::RegBase;
10767 AM.Base.Reg = Op.getReg();
10769 AM.BaseType = X86AddressMode::FrameIndexBase;
10770 AM.Base.FrameIndex = Op.getIndex();
10772 Op = MI->getOperand(1);
10774 AM.Scale = Op.getImm();
10775 Op = MI->getOperand(2);
10777 AM.IndexReg = Op.getImm();
10778 Op = MI->getOperand(3);
10779 if (Op.isGlobal()) {
10780 AM.GV = Op.getGlobal();
10782 AM.Disp = Op.getImm();
10784 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10785 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10787 // Reload the original control word now.
10788 addFrameReference(BuildMI(*BB, MI, DL,
10789 TII->get(X86::FLDCW16m)), CWFrameIdx);
10791 MI->eraseFromParent(); // The pseudo instruction is gone now.
10794 // String/text processing lowering.
10795 case X86::PCMPISTRM128REG:
10796 case X86::VPCMPISTRM128REG:
10797 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10798 case X86::PCMPISTRM128MEM:
10799 case X86::VPCMPISTRM128MEM:
10800 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10801 case X86::PCMPESTRM128REG:
10802 case X86::VPCMPESTRM128REG:
10803 return EmitPCMP(MI, BB, 5, false /* in mem */);
10804 case X86::PCMPESTRM128MEM:
10805 case X86::VPCMPESTRM128MEM:
10806 return EmitPCMP(MI, BB, 5, true /* in mem */);
10808 // Thread synchronization.
10810 return EmitMonitor(MI, BB);
10812 return EmitMwait(MI, BB);
10814 // Atomic Lowering.
10815 case X86::ATOMAND32:
10816 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10817 X86::AND32ri, X86::MOV32rm,
10819 X86::NOT32r, X86::EAX,
10820 X86::GR32RegisterClass);
10821 case X86::ATOMOR32:
10822 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10823 X86::OR32ri, X86::MOV32rm,
10825 X86::NOT32r, X86::EAX,
10826 X86::GR32RegisterClass);
10827 case X86::ATOMXOR32:
10828 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10829 X86::XOR32ri, X86::MOV32rm,
10831 X86::NOT32r, X86::EAX,
10832 X86::GR32RegisterClass);
10833 case X86::ATOMNAND32:
10834 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10835 X86::AND32ri, X86::MOV32rm,
10837 X86::NOT32r, X86::EAX,
10838 X86::GR32RegisterClass, true);
10839 case X86::ATOMMIN32:
10840 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10841 case X86::ATOMMAX32:
10842 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10843 case X86::ATOMUMIN32:
10844 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10845 case X86::ATOMUMAX32:
10846 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10848 case X86::ATOMAND16:
10849 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10850 X86::AND16ri, X86::MOV16rm,
10852 X86::NOT16r, X86::AX,
10853 X86::GR16RegisterClass);
10854 case X86::ATOMOR16:
10855 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10856 X86::OR16ri, X86::MOV16rm,
10858 X86::NOT16r, X86::AX,
10859 X86::GR16RegisterClass);
10860 case X86::ATOMXOR16:
10861 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10862 X86::XOR16ri, X86::MOV16rm,
10864 X86::NOT16r, X86::AX,
10865 X86::GR16RegisterClass);
10866 case X86::ATOMNAND16:
10867 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10868 X86::AND16ri, X86::MOV16rm,
10870 X86::NOT16r, X86::AX,
10871 X86::GR16RegisterClass, true);
10872 case X86::ATOMMIN16:
10873 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10874 case X86::ATOMMAX16:
10875 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10876 case X86::ATOMUMIN16:
10877 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10878 case X86::ATOMUMAX16:
10879 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10881 case X86::ATOMAND8:
10882 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10883 X86::AND8ri, X86::MOV8rm,
10885 X86::NOT8r, X86::AL,
10886 X86::GR8RegisterClass);
10888 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10889 X86::OR8ri, X86::MOV8rm,
10891 X86::NOT8r, X86::AL,
10892 X86::GR8RegisterClass);
10893 case X86::ATOMXOR8:
10894 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10895 X86::XOR8ri, X86::MOV8rm,
10897 X86::NOT8r, X86::AL,
10898 X86::GR8RegisterClass);
10899 case X86::ATOMNAND8:
10900 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10901 X86::AND8ri, X86::MOV8rm,
10903 X86::NOT8r, X86::AL,
10904 X86::GR8RegisterClass, true);
10905 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10906 // This group is for 64-bit host.
10907 case X86::ATOMAND64:
10908 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10909 X86::AND64ri32, X86::MOV64rm,
10911 X86::NOT64r, X86::RAX,
10912 X86::GR64RegisterClass);
10913 case X86::ATOMOR64:
10914 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10915 X86::OR64ri32, X86::MOV64rm,
10917 X86::NOT64r, X86::RAX,
10918 X86::GR64RegisterClass);
10919 case X86::ATOMXOR64:
10920 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10921 X86::XOR64ri32, X86::MOV64rm,
10923 X86::NOT64r, X86::RAX,
10924 X86::GR64RegisterClass);
10925 case X86::ATOMNAND64:
10926 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10927 X86::AND64ri32, X86::MOV64rm,
10929 X86::NOT64r, X86::RAX,
10930 X86::GR64RegisterClass, true);
10931 case X86::ATOMMIN64:
10932 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10933 case X86::ATOMMAX64:
10934 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10935 case X86::ATOMUMIN64:
10936 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10937 case X86::ATOMUMAX64:
10938 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10940 // This group does 64-bit operations on a 32-bit host.
10941 case X86::ATOMAND6432:
10942 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10943 X86::AND32rr, X86::AND32rr,
10944 X86::AND32ri, X86::AND32ri,
10946 case X86::ATOMOR6432:
10947 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10948 X86::OR32rr, X86::OR32rr,
10949 X86::OR32ri, X86::OR32ri,
10951 case X86::ATOMXOR6432:
10952 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10953 X86::XOR32rr, X86::XOR32rr,
10954 X86::XOR32ri, X86::XOR32ri,
10956 case X86::ATOMNAND6432:
10957 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10958 X86::AND32rr, X86::AND32rr,
10959 X86::AND32ri, X86::AND32ri,
10961 case X86::ATOMADD6432:
10962 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10963 X86::ADD32rr, X86::ADC32rr,
10964 X86::ADD32ri, X86::ADC32ri,
10966 case X86::ATOMSUB6432:
10967 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10968 X86::SUB32rr, X86::SBB32rr,
10969 X86::SUB32ri, X86::SBB32ri,
10971 case X86::ATOMSWAP6432:
10972 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10973 X86::MOV32rr, X86::MOV32rr,
10974 X86::MOV32ri, X86::MOV32ri,
10976 case X86::VASTART_SAVE_XMM_REGS:
10977 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10979 case X86::VAARG_64:
10980 return EmitVAARG64WithCustomInserter(MI, BB);
10984 //===----------------------------------------------------------------------===//
10985 // X86 Optimization Hooks
10986 //===----------------------------------------------------------------------===//
10988 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10992 const SelectionDAG &DAG,
10993 unsigned Depth) const {
10994 unsigned Opc = Op.getOpcode();
10995 assert((Opc >= ISD::BUILTIN_OP_END ||
10996 Opc == ISD::INTRINSIC_WO_CHAIN ||
10997 Opc == ISD::INTRINSIC_W_CHAIN ||
10998 Opc == ISD::INTRINSIC_VOID) &&
10999 "Should use MaskedValueIsZero if you don't know whether Op"
11000 " is a target node!");
11002 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
11016 // These nodes' second result is a boolean.
11017 if (Op.getResNo() == 0)
11020 case X86ISD::SETCC:
11021 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11022 Mask.getBitWidth() - 1);
11027 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11028 unsigned Depth) const {
11029 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11030 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11031 return Op.getValueType().getScalarType().getSizeInBits();
11037 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11038 /// node is a GlobalAddress + offset.
11039 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11040 const GlobalValue* &GA,
11041 int64_t &Offset) const {
11042 if (N->getOpcode() == X86ISD::Wrapper) {
11043 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11044 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11045 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11049 return TargetLowering::isGAPlusOffset(N, GA, Offset);
11052 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
11053 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
11054 /// if the load addresses are consecutive, non-overlapping, and in the right
11056 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11057 TargetLowering::DAGCombinerInfo &DCI) {
11058 DebugLoc dl = N->getDebugLoc();
11059 EVT VT = N->getValueType(0);
11061 if (VT.getSizeInBits() != 128)
11064 // Don't create instructions with illegal types after legalize types has run.
11065 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11066 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11069 SmallVector<SDValue, 16> Elts;
11070 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11071 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11073 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11076 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11077 /// generation and convert it from being a bunch of shuffles and extracts
11078 /// to a simple store and scalar loads to extract the elements.
11079 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11080 const TargetLowering &TLI) {
11081 SDValue InputVector = N->getOperand(0);
11083 // Only operate on vectors of 4 elements, where the alternative shuffling
11084 // gets to be more expensive.
11085 if (InputVector.getValueType() != MVT::v4i32)
11088 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11089 // single use which is a sign-extend or zero-extend, and all elements are
11091 SmallVector<SDNode *, 4> Uses;
11092 unsigned ExtractedElements = 0;
11093 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11094 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11095 if (UI.getUse().getResNo() != InputVector.getResNo())
11098 SDNode *Extract = *UI;
11099 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11102 if (Extract->getValueType(0) != MVT::i32)
11104 if (!Extract->hasOneUse())
11106 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11107 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11109 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11112 // Record which element was extracted.
11113 ExtractedElements |=
11114 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11116 Uses.push_back(Extract);
11119 // If not all the elements were used, this may not be worthwhile.
11120 if (ExtractedElements != 15)
11123 // Ok, we've now decided to do the transformation.
11124 DebugLoc dl = InputVector.getDebugLoc();
11126 // Store the value to a temporary stack slot.
11127 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11128 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11129 MachinePointerInfo(), false, false, 0);
11131 // Replace each use (extract) with a load of the appropriate element.
11132 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11133 UE = Uses.end(); UI != UE; ++UI) {
11134 SDNode *Extract = *UI;
11136 // cOMpute the element's address.
11137 SDValue Idx = Extract->getOperand(1);
11139 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11140 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11141 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11143 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11144 StackPtr, OffsetVal);
11146 // Load the scalar.
11147 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11148 ScalarAddr, MachinePointerInfo(),
11151 // Replace the exact with the load.
11152 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11155 // The replacement was made in place; don't return anything.
11159 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11160 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11161 const X86Subtarget *Subtarget) {
11162 DebugLoc DL = N->getDebugLoc();
11163 SDValue Cond = N->getOperand(0);
11164 // Get the LHS/RHS of the select.
11165 SDValue LHS = N->getOperand(1);
11166 SDValue RHS = N->getOperand(2);
11168 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11169 // instructions match the semantics of the common C idiom x<y?x:y but not
11170 // x<=y?x:y, because of how they handle negative zero (which can be
11171 // ignored in unsafe-math mode).
11172 if (Subtarget->hasSSE2() &&
11173 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11174 Cond.getOpcode() == ISD::SETCC) {
11175 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11177 unsigned Opcode = 0;
11178 // Check for x CC y ? x : y.
11179 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11180 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11184 // Converting this to a min would handle NaNs incorrectly, and swapping
11185 // the operands would cause it to handle comparisons between positive
11186 // and negative zero incorrectly.
11187 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11188 if (!UnsafeFPMath &&
11189 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11191 std::swap(LHS, RHS);
11193 Opcode = X86ISD::FMIN;
11196 // Converting this to a min would handle comparisons between positive
11197 // and negative zero incorrectly.
11198 if (!UnsafeFPMath &&
11199 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11201 Opcode = X86ISD::FMIN;
11204 // Converting this to a min would handle both negative zeros and NaNs
11205 // incorrectly, but we can swap the operands to fix both.
11206 std::swap(LHS, RHS);
11210 Opcode = X86ISD::FMIN;
11214 // Converting this to a max would handle comparisons between positive
11215 // and negative zero incorrectly.
11216 if (!UnsafeFPMath &&
11217 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11219 Opcode = X86ISD::FMAX;
11222 // Converting this to a max would handle NaNs incorrectly, and swapping
11223 // the operands would cause it to handle comparisons between positive
11224 // and negative zero incorrectly.
11225 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11226 if (!UnsafeFPMath &&
11227 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11229 std::swap(LHS, RHS);
11231 Opcode = X86ISD::FMAX;
11234 // Converting this to a max would handle both negative zeros and NaNs
11235 // incorrectly, but we can swap the operands to fix both.
11236 std::swap(LHS, RHS);
11240 Opcode = X86ISD::FMAX;
11243 // Check for x CC y ? y : x -- a min/max with reversed arms.
11244 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11245 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11249 // Converting this to a min would handle comparisons between positive
11250 // and negative zero incorrectly, and swapping the operands would
11251 // cause it to handle NaNs incorrectly.
11252 if (!UnsafeFPMath &&
11253 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11254 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11256 std::swap(LHS, RHS);
11258 Opcode = X86ISD::FMIN;
11261 // Converting this to a min would handle NaNs incorrectly.
11262 if (!UnsafeFPMath &&
11263 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11265 Opcode = X86ISD::FMIN;
11268 // Converting this to a min would handle both negative zeros and NaNs
11269 // incorrectly, but we can swap the operands to fix both.
11270 std::swap(LHS, RHS);
11274 Opcode = X86ISD::FMIN;
11278 // Converting this to a max would handle NaNs incorrectly.
11279 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11281 Opcode = X86ISD::FMAX;
11284 // Converting this to a max would handle comparisons between positive
11285 // and negative zero incorrectly, and swapping the operands would
11286 // cause it to handle NaNs incorrectly.
11287 if (!UnsafeFPMath &&
11288 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11289 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(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;
11308 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11311 // If this is a select between two integer constants, try to do some
11313 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11314 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11315 // Don't do this for crazy integer types.
11316 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11317 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11318 // so that TrueC (the true value) is larger than FalseC.
11319 bool NeedsCondInvert = false;
11321 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11322 // Efficiently invertible.
11323 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
11324 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
11325 isa<ConstantSDNode>(Cond.getOperand(1))))) {
11326 NeedsCondInvert = true;
11327 std::swap(TrueC, FalseC);
11330 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
11331 if (FalseC->getAPIntValue() == 0 &&
11332 TrueC->getAPIntValue().isPowerOf2()) {
11333 if (NeedsCondInvert) // Invert the condition if needed.
11334 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11335 DAG.getConstant(1, Cond.getValueType()));
11337 // Zero extend the condition if needed.
11338 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11340 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11341 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11342 DAG.getConstant(ShAmt, MVT::i8));
11345 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11346 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11347 if (NeedsCondInvert) // Invert the condition if needed.
11348 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11349 DAG.getConstant(1, Cond.getValueType()));
11351 // Zero extend the condition if needed.
11352 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11353 FalseC->getValueType(0), Cond);
11354 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11355 SDValue(FalseC, 0));
11358 // Optimize cases that will turn into an LEA instruction. This requires
11359 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11360 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11361 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11362 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11364 bool isFastMultiplier = false;
11366 switch ((unsigned char)Diff) {
11368 case 1: // result = add base, cond
11369 case 2: // result = lea base( , cond*2)
11370 case 3: // result = lea base(cond, cond*2)
11371 case 4: // result = lea base( , cond*4)
11372 case 5: // result = lea base(cond, cond*4)
11373 case 8: // result = lea base( , cond*8)
11374 case 9: // result = lea base(cond, cond*8)
11375 isFastMultiplier = true;
11380 if (isFastMultiplier) {
11381 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11382 if (NeedsCondInvert) // Invert the condition if needed.
11383 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11384 DAG.getConstant(1, Cond.getValueType()));
11386 // Zero extend the condition if needed.
11387 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11389 // Scale the condition by the difference.
11391 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11392 DAG.getConstant(Diff, Cond.getValueType()));
11394 // Add the base if non-zero.
11395 if (FalseC->getAPIntValue() != 0)
11396 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11397 SDValue(FalseC, 0));
11407 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11408 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11409 TargetLowering::DAGCombinerInfo &DCI) {
11410 DebugLoc DL = N->getDebugLoc();
11412 // If the flag operand isn't dead, don't touch this CMOV.
11413 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11416 SDValue FalseOp = N->getOperand(0);
11417 SDValue TrueOp = N->getOperand(1);
11418 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11419 SDValue Cond = N->getOperand(3);
11420 if (CC == X86::COND_E || CC == X86::COND_NE) {
11421 switch (Cond.getOpcode()) {
11425 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11426 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11427 return (CC == X86::COND_E) ? FalseOp : TrueOp;
11431 // If this is a select between two integer constants, try to do some
11432 // optimizations. Note that the operands are ordered the opposite of SELECT
11434 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11435 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11436 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11437 // larger than FalseC (the false value).
11438 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11439 CC = X86::GetOppositeBranchCondition(CC);
11440 std::swap(TrueC, FalseC);
11443 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
11444 // This is efficient for any integer data type (including i8/i16) and
11446 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11447 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11448 DAG.getConstant(CC, MVT::i8), Cond);
11450 // Zero extend the condition if needed.
11451 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11453 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11454 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11455 DAG.getConstant(ShAmt, MVT::i8));
11456 if (N->getNumValues() == 2) // Dead flag value?
11457 return DCI.CombineTo(N, Cond, SDValue());
11461 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
11462 // for any integer data type, including i8/i16.
11463 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11464 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11465 DAG.getConstant(CC, MVT::i8), Cond);
11467 // Zero extend the condition if needed.
11468 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11469 FalseC->getValueType(0), Cond);
11470 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11471 SDValue(FalseC, 0));
11473 if (N->getNumValues() == 2) // Dead flag value?
11474 return DCI.CombineTo(N, Cond, SDValue());
11478 // Optimize cases that will turn into an LEA instruction. This requires
11479 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11480 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11481 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11482 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11484 bool isFastMultiplier = false;
11486 switch ((unsigned char)Diff) {
11488 case 1: // result = add base, cond
11489 case 2: // result = lea base( , cond*2)
11490 case 3: // result = lea base(cond, cond*2)
11491 case 4: // result = lea base( , cond*4)
11492 case 5: // result = lea base(cond, cond*4)
11493 case 8: // result = lea base( , cond*8)
11494 case 9: // result = lea base(cond, cond*8)
11495 isFastMultiplier = true;
11500 if (isFastMultiplier) {
11501 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11502 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11503 DAG.getConstant(CC, MVT::i8), Cond);
11504 // Zero extend the condition if needed.
11505 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11507 // Scale the condition by the difference.
11509 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11510 DAG.getConstant(Diff, Cond.getValueType()));
11512 // Add the base if non-zero.
11513 if (FalseC->getAPIntValue() != 0)
11514 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11515 SDValue(FalseC, 0));
11516 if (N->getNumValues() == 2) // Dead flag value?
11517 return DCI.CombineTo(N, Cond, SDValue());
11527 /// PerformMulCombine - Optimize a single multiply with constant into two
11528 /// in order to implement it with two cheaper instructions, e.g.
11529 /// LEA + SHL, LEA + LEA.
11530 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11531 TargetLowering::DAGCombinerInfo &DCI) {
11532 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11535 EVT VT = N->getValueType(0);
11536 if (VT != MVT::i64)
11539 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11542 uint64_t MulAmt = C->getZExtValue();
11543 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11546 uint64_t MulAmt1 = 0;
11547 uint64_t MulAmt2 = 0;
11548 if ((MulAmt % 9) == 0) {
11550 MulAmt2 = MulAmt / 9;
11551 } else if ((MulAmt % 5) == 0) {
11553 MulAmt2 = MulAmt / 5;
11554 } else if ((MulAmt % 3) == 0) {
11556 MulAmt2 = MulAmt / 3;
11559 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11560 DebugLoc DL = N->getDebugLoc();
11562 if (isPowerOf2_64(MulAmt2) &&
11563 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11564 // If second multiplifer is pow2, issue it first. We want the multiply by
11565 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11567 std::swap(MulAmt1, MulAmt2);
11570 if (isPowerOf2_64(MulAmt1))
11571 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11572 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11574 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11575 DAG.getConstant(MulAmt1, VT));
11577 if (isPowerOf2_64(MulAmt2))
11578 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11579 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11581 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11582 DAG.getConstant(MulAmt2, VT));
11584 // Do not add new nodes to DAG combiner worklist.
11585 DCI.CombineTo(N, NewMul, false);
11590 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11591 SDValue N0 = N->getOperand(0);
11592 SDValue N1 = N->getOperand(1);
11593 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11594 EVT VT = N0.getValueType();
11596 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11597 // since the result of setcc_c is all zero's or all ones.
11598 if (N1C && N0.getOpcode() == ISD::AND &&
11599 N0.getOperand(1).getOpcode() == ISD::Constant) {
11600 SDValue N00 = N0.getOperand(0);
11601 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11602 ((N00.getOpcode() == ISD::ANY_EXTEND ||
11603 N00.getOpcode() == ISD::ZERO_EXTEND) &&
11604 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11605 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11606 APInt ShAmt = N1C->getAPIntValue();
11607 Mask = Mask.shl(ShAmt);
11609 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11610 N00, DAG.getConstant(Mask, VT));
11617 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11619 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11620 const X86Subtarget *Subtarget) {
11621 EVT VT = N->getValueType(0);
11622 if (!VT.isVector() && VT.isInteger() &&
11623 N->getOpcode() == ISD::SHL)
11624 return PerformSHLCombine(N, DAG);
11626 // On X86 with SSE2 support, we can transform this to a vector shift if
11627 // all elements are shifted by the same amount. We can't do this in legalize
11628 // because the a constant vector is typically transformed to a constant pool
11629 // so we have no knowledge of the shift amount.
11630 if (!Subtarget->hasSSE2())
11633 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11636 SDValue ShAmtOp = N->getOperand(1);
11637 EVT EltVT = VT.getVectorElementType();
11638 DebugLoc DL = N->getDebugLoc();
11639 SDValue BaseShAmt = SDValue();
11640 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11641 unsigned NumElts = VT.getVectorNumElements();
11643 for (; i != NumElts; ++i) {
11644 SDValue Arg = ShAmtOp.getOperand(i);
11645 if (Arg.getOpcode() == ISD::UNDEF) continue;
11649 for (; i != NumElts; ++i) {
11650 SDValue Arg = ShAmtOp.getOperand(i);
11651 if (Arg.getOpcode() == ISD::UNDEF) continue;
11652 if (Arg != BaseShAmt) {
11656 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11657 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11658 SDValue InVec = ShAmtOp.getOperand(0);
11659 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11660 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11662 for (; i != NumElts; ++i) {
11663 SDValue Arg = InVec.getOperand(i);
11664 if (Arg.getOpcode() == ISD::UNDEF) continue;
11668 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11669 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11670 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11671 if (C->getZExtValue() == SplatIdx)
11672 BaseShAmt = InVec.getOperand(1);
11675 if (BaseShAmt.getNode() == 0)
11676 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11677 DAG.getIntPtrConstant(0));
11681 // The shift amount is an i32.
11682 if (EltVT.bitsGT(MVT::i32))
11683 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11684 else if (EltVT.bitsLT(MVT::i32))
11685 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11687 // The shift amount is identical so we can do a vector shift.
11688 SDValue ValOp = N->getOperand(0);
11689 switch (N->getOpcode()) {
11691 llvm_unreachable("Unknown shift opcode!");
11694 if (VT == MVT::v2i64)
11695 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11696 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11698 if (VT == MVT::v4i32)
11699 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11700 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11702 if (VT == MVT::v8i16)
11703 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11704 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11708 if (VT == MVT::v4i32)
11709 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11710 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11712 if (VT == MVT::v8i16)
11713 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11714 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11718 if (VT == MVT::v2i64)
11719 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11720 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11722 if (VT == MVT::v4i32)
11723 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11724 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11726 if (VT == MVT::v8i16)
11727 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11728 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11736 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
11737 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
11738 // and friends. Likewise for OR -> CMPNEQSS.
11739 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
11740 TargetLowering::DAGCombinerInfo &DCI,
11741 const X86Subtarget *Subtarget) {
11744 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
11745 // we're requiring SSE2 for both.
11746 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
11747 SDValue N0 = N->getOperand(0);
11748 SDValue N1 = N->getOperand(1);
11749 SDValue CMP0 = N0->getOperand(1);
11750 SDValue CMP1 = N1->getOperand(1);
11751 DebugLoc DL = N->getDebugLoc();
11753 // The SETCCs should both refer to the same CMP.
11754 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
11757 SDValue CMP00 = CMP0->getOperand(0);
11758 SDValue CMP01 = CMP0->getOperand(1);
11759 EVT VT = CMP00.getValueType();
11761 if (VT == MVT::f32 || VT == MVT::f64) {
11762 bool ExpectingFlags = false;
11763 // Check for any users that want flags:
11764 for (SDNode::use_iterator UI = N->use_begin(),
11766 !ExpectingFlags && UI != UE; ++UI)
11767 switch (UI->getOpcode()) {
11772 ExpectingFlags = true;
11774 case ISD::CopyToReg:
11775 case ISD::SIGN_EXTEND:
11776 case ISD::ZERO_EXTEND:
11777 case ISD::ANY_EXTEND:
11781 if (!ExpectingFlags) {
11782 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
11783 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
11785 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
11786 X86::CondCode tmp = cc0;
11791 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
11792 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
11793 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
11794 X86ISD::NodeType NTOperator = is64BitFP ?
11795 X86ISD::FSETCCsd : X86ISD::FSETCCss;
11796 // FIXME: need symbolic constants for these magic numbers.
11797 // See X86ATTInstPrinter.cpp:printSSECC().
11798 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
11799 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
11800 DAG.getConstant(x86cc, MVT::i8));
11801 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
11803 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
11804 DAG.getConstant(1, MVT::i32));
11805 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
11806 return OneBitOfTruth;
11814 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11815 TargetLowering::DAGCombinerInfo &DCI,
11816 const X86Subtarget *Subtarget) {
11817 if (DCI.isBeforeLegalizeOps())
11820 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11824 // Want to form PANDN nodes, in the hopes of then easily combining them with
11825 // OR and AND nodes to form PBLEND/PSIGN.
11826 EVT VT = N->getValueType(0);
11827 if (VT != MVT::v2i64)
11830 SDValue N0 = N->getOperand(0);
11831 SDValue N1 = N->getOperand(1);
11832 DebugLoc DL = N->getDebugLoc();
11834 // Check LHS for vnot
11835 if (N0.getOpcode() == ISD::XOR &&
11836 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11837 return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11839 // Check RHS for vnot
11840 if (N1.getOpcode() == ISD::XOR &&
11841 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11842 return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11847 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11848 TargetLowering::DAGCombinerInfo &DCI,
11849 const X86Subtarget *Subtarget) {
11850 if (DCI.isBeforeLegalizeOps())
11853 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11857 EVT VT = N->getValueType(0);
11858 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11861 SDValue N0 = N->getOperand(0);
11862 SDValue N1 = N->getOperand(1);
11864 // look for psign/blend
11865 if (Subtarget->hasSSSE3()) {
11866 if (VT == MVT::v2i64) {
11867 // Canonicalize pandn to RHS
11868 if (N0.getOpcode() == X86ISD::PANDN)
11870 // or (and (m, x), (pandn m, y))
11871 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11872 SDValue Mask = N1.getOperand(0);
11873 SDValue X = N1.getOperand(1);
11875 if (N0.getOperand(0) == Mask)
11876 Y = N0.getOperand(1);
11877 if (N0.getOperand(1) == Mask)
11878 Y = N0.getOperand(0);
11880 // Check to see if the mask appeared in both the AND and PANDN and
11884 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11885 if (Mask.getOpcode() != ISD::BITCAST ||
11886 X.getOpcode() != ISD::BITCAST ||
11887 Y.getOpcode() != ISD::BITCAST)
11890 // Look through mask bitcast.
11891 Mask = Mask.getOperand(0);
11892 EVT MaskVT = Mask.getValueType();
11894 // Validate that the Mask operand is a vector sra node. The sra node
11895 // will be an intrinsic.
11896 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11899 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11900 // there is no psrai.b
11901 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11902 case Intrinsic::x86_sse2_psrai_w:
11903 case Intrinsic::x86_sse2_psrai_d:
11905 default: return SDValue();
11908 // Check that the SRA is all signbits.
11909 SDValue SraC = Mask.getOperand(2);
11910 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
11911 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11912 if ((SraAmt + 1) != EltBits)
11915 DebugLoc DL = N->getDebugLoc();
11917 // Now we know we at least have a plendvb with the mask val. See if
11918 // we can form a psignb/w/d.
11919 // psign = x.type == y.type == mask.type && y = sub(0, x);
11920 X = X.getOperand(0);
11921 Y = Y.getOperand(0);
11922 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11923 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11924 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11927 case 8: Opc = X86ISD::PSIGNB; break;
11928 case 16: Opc = X86ISD::PSIGNW; break;
11929 case 32: Opc = X86ISD::PSIGND; break;
11933 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11934 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11937 // PBLENDVB only available on SSE 4.1
11938 if (!Subtarget->hasSSE41())
11941 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11942 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11943 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11944 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11945 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11950 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11951 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11953 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11955 if (!N0.hasOneUse() || !N1.hasOneUse())
11958 SDValue ShAmt0 = N0.getOperand(1);
11959 if (ShAmt0.getValueType() != MVT::i8)
11961 SDValue ShAmt1 = N1.getOperand(1);
11962 if (ShAmt1.getValueType() != MVT::i8)
11964 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11965 ShAmt0 = ShAmt0.getOperand(0);
11966 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11967 ShAmt1 = ShAmt1.getOperand(0);
11969 DebugLoc DL = N->getDebugLoc();
11970 unsigned Opc = X86ISD::SHLD;
11971 SDValue Op0 = N0.getOperand(0);
11972 SDValue Op1 = N1.getOperand(0);
11973 if (ShAmt0.getOpcode() == ISD::SUB) {
11974 Opc = X86ISD::SHRD;
11975 std::swap(Op0, Op1);
11976 std::swap(ShAmt0, ShAmt1);
11979 unsigned Bits = VT.getSizeInBits();
11980 if (ShAmt1.getOpcode() == ISD::SUB) {
11981 SDValue Sum = ShAmt1.getOperand(0);
11982 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11983 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11984 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11985 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11986 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11987 return DAG.getNode(Opc, DL, VT,
11989 DAG.getNode(ISD::TRUNCATE, DL,
11992 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11993 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11995 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11996 return DAG.getNode(Opc, DL, VT,
11997 N0.getOperand(0), N1.getOperand(0),
11998 DAG.getNode(ISD::TRUNCATE, DL,
12005 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
12006 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
12007 const X86Subtarget *Subtarget) {
12008 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
12009 // the FP state in cases where an emms may be missing.
12010 // A preferable solution to the general problem is to figure out the right
12011 // places to insert EMMS. This qualifies as a quick hack.
12013 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
12014 StoreSDNode *St = cast<StoreSDNode>(N);
12015 EVT VT = St->getValue().getValueType();
12016 if (VT.getSizeInBits() != 64)
12019 const Function *F = DAG.getMachineFunction().getFunction();
12020 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
12021 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
12022 && Subtarget->hasSSE2();
12023 if ((VT.isVector() ||
12024 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
12025 isa<LoadSDNode>(St->getValue()) &&
12026 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
12027 St->getChain().hasOneUse() && !St->isVolatile()) {
12028 SDNode* LdVal = St->getValue().getNode();
12029 LoadSDNode *Ld = 0;
12030 int TokenFactorIndex = -1;
12031 SmallVector<SDValue, 8> Ops;
12032 SDNode* ChainVal = St->getChain().getNode();
12033 // Must be a store of a load. We currently handle two cases: the load
12034 // is a direct child, and it's under an intervening TokenFactor. It is
12035 // possible to dig deeper under nested TokenFactors.
12036 if (ChainVal == LdVal)
12037 Ld = cast<LoadSDNode>(St->getChain());
12038 else if (St->getValue().hasOneUse() &&
12039 ChainVal->getOpcode() == ISD::TokenFactor) {
12040 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
12041 if (ChainVal->getOperand(i).getNode() == LdVal) {
12042 TokenFactorIndex = i;
12043 Ld = cast<LoadSDNode>(St->getValue());
12045 Ops.push_back(ChainVal->getOperand(i));
12049 if (!Ld || !ISD::isNormalLoad(Ld))
12052 // If this is not the MMX case, i.e. we are just turning i64 load/store
12053 // into f64 load/store, avoid the transformation if there are multiple
12054 // uses of the loaded value.
12055 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
12058 DebugLoc LdDL = Ld->getDebugLoc();
12059 DebugLoc StDL = N->getDebugLoc();
12060 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
12061 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
12063 if (Subtarget->is64Bit() || F64IsLegal) {
12064 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
12065 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
12066 Ld->getPointerInfo(), Ld->isVolatile(),
12067 Ld->isNonTemporal(), Ld->getAlignment());
12068 SDValue NewChain = NewLd.getValue(1);
12069 if (TokenFactorIndex != -1) {
12070 Ops.push_back(NewChain);
12071 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12074 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
12075 St->getPointerInfo(),
12076 St->isVolatile(), St->isNonTemporal(),
12077 St->getAlignment());
12080 // Otherwise, lower to two pairs of 32-bit loads / stores.
12081 SDValue LoAddr = Ld->getBasePtr();
12082 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
12083 DAG.getConstant(4, MVT::i32));
12085 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
12086 Ld->getPointerInfo(),
12087 Ld->isVolatile(), Ld->isNonTemporal(),
12088 Ld->getAlignment());
12089 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
12090 Ld->getPointerInfo().getWithOffset(4),
12091 Ld->isVolatile(), Ld->isNonTemporal(),
12092 MinAlign(Ld->getAlignment(), 4));
12094 SDValue NewChain = LoLd.getValue(1);
12095 if (TokenFactorIndex != -1) {
12096 Ops.push_back(LoLd);
12097 Ops.push_back(HiLd);
12098 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12102 LoAddr = St->getBasePtr();
12103 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
12104 DAG.getConstant(4, MVT::i32));
12106 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
12107 St->getPointerInfo(),
12108 St->isVolatile(), St->isNonTemporal(),
12109 St->getAlignment());
12110 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12111 St->getPointerInfo().getWithOffset(4),
12113 St->isNonTemporal(),
12114 MinAlign(St->getAlignment(), 4));
12115 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12120 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12121 /// X86ISD::FXOR nodes.
12122 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12123 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12124 // F[X]OR(0.0, x) -> x
12125 // F[X]OR(x, 0.0) -> x
12126 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12127 if (C->getValueAPF().isPosZero())
12128 return N->getOperand(1);
12129 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12130 if (C->getValueAPF().isPosZero())
12131 return N->getOperand(0);
12135 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12136 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12137 // FAND(0.0, x) -> 0.0
12138 // FAND(x, 0.0) -> 0.0
12139 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12140 if (C->getValueAPF().isPosZero())
12141 return N->getOperand(0);
12142 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12143 if (C->getValueAPF().isPosZero())
12144 return N->getOperand(1);
12148 static SDValue PerformBTCombine(SDNode *N,
12150 TargetLowering::DAGCombinerInfo &DCI) {
12151 // BT ignores high bits in the bit index operand.
12152 SDValue Op1 = N->getOperand(1);
12153 if (Op1.hasOneUse()) {
12154 unsigned BitWidth = Op1.getValueSizeInBits();
12155 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12156 APInt KnownZero, KnownOne;
12157 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12158 !DCI.isBeforeLegalizeOps());
12159 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12160 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12161 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12162 DCI.CommitTargetLoweringOpt(TLO);
12167 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12168 SDValue Op = N->getOperand(0);
12169 if (Op.getOpcode() == ISD::BITCAST)
12170 Op = Op.getOperand(0);
12171 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12172 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12173 VT.getVectorElementType().getSizeInBits() ==
12174 OpVT.getVectorElementType().getSizeInBits()) {
12175 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12180 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12181 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
12182 // (and (i32 x86isd::setcc_carry), 1)
12183 // This eliminates the zext. This transformation is necessary because
12184 // ISD::SETCC is always legalized to i8.
12185 DebugLoc dl = N->getDebugLoc();
12186 SDValue N0 = N->getOperand(0);
12187 EVT VT = N->getValueType(0);
12188 if (N0.getOpcode() == ISD::AND &&
12190 N0.getOperand(0).hasOneUse()) {
12191 SDValue N00 = N0.getOperand(0);
12192 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12194 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12195 if (!C || C->getZExtValue() != 1)
12197 return DAG.getNode(ISD::AND, dl, VT,
12198 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12199 N00.getOperand(0), N00.getOperand(1)),
12200 DAG.getConstant(1, VT));
12206 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12207 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12208 unsigned X86CC = N->getConstantOperandVal(0);
12209 SDValue EFLAG = N->getOperand(1);
12210 DebugLoc DL = N->getDebugLoc();
12212 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12213 // a zext and produces an all-ones bit which is more useful than 0/1 in some
12215 if (X86CC == X86::COND_B)
12216 return DAG.getNode(ISD::AND, DL, MVT::i8,
12217 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12218 DAG.getConstant(X86CC, MVT::i8), EFLAG),
12219 DAG.getConstant(1, MVT::i8));
12224 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
12225 const X86TargetLowering *XTLI) {
12226 SDValue Op0 = N->getOperand(0);
12227 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
12228 // a 32-bit target where SSE doesn't support i64->FP operations.
12229 if (Op0.getOpcode() == ISD::LOAD) {
12230 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
12231 EVT VT = Ld->getValueType(0);
12232 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
12233 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
12234 !XTLI->getSubtarget()->is64Bit() &&
12235 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12236 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
12237 Ld->getChain(), Op0, DAG);
12238 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
12245 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12246 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12247 X86TargetLowering::DAGCombinerInfo &DCI) {
12248 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12249 // the result is either zero or one (depending on the input carry bit).
12250 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12251 if (X86::isZeroNode(N->getOperand(0)) &&
12252 X86::isZeroNode(N->getOperand(1)) &&
12253 // We don't have a good way to replace an EFLAGS use, so only do this when
12255 SDValue(N, 1).use_empty()) {
12256 DebugLoc DL = N->getDebugLoc();
12257 EVT VT = N->getValueType(0);
12258 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12259 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12260 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12261 DAG.getConstant(X86::COND_B,MVT::i8),
12263 DAG.getConstant(1, VT));
12264 return DCI.CombineTo(N, Res1, CarryOut);
12270 // fold (add Y, (sete X, 0)) -> adc 0, Y
12271 // (add Y, (setne X, 0)) -> sbb -1, Y
12272 // (sub (sete X, 0), Y) -> sbb 0, Y
12273 // (sub (setne X, 0), Y) -> adc -1, Y
12274 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12275 DebugLoc DL = N->getDebugLoc();
12277 // Look through ZExts.
12278 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12279 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12282 SDValue SetCC = Ext.getOperand(0);
12283 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12286 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12287 if (CC != X86::COND_E && CC != X86::COND_NE)
12290 SDValue Cmp = SetCC.getOperand(1);
12291 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12292 !X86::isZeroNode(Cmp.getOperand(1)) ||
12293 !Cmp.getOperand(0).getValueType().isInteger())
12296 SDValue CmpOp0 = Cmp.getOperand(0);
12297 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12298 DAG.getConstant(1, CmpOp0.getValueType()));
12300 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12301 if (CC == X86::COND_NE)
12302 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12303 DL, OtherVal.getValueType(), OtherVal,
12304 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12305 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12306 DL, OtherVal.getValueType(), OtherVal,
12307 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12310 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12311 DAGCombinerInfo &DCI) const {
12312 SelectionDAG &DAG = DCI.DAG;
12313 switch (N->getOpcode()) {
12315 case ISD::EXTRACT_VECTOR_ELT:
12316 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12317 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
12318 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
12320 case ISD::SUB: return OptimizeConditonalInDecrement(N, DAG);
12321 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
12322 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
12325 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
12326 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
12327 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
12328 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
12329 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
12331 case X86ISD::FOR: return PerformFORCombine(N, DAG);
12332 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
12333 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
12334 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
12335 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
12336 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
12337 case X86ISD::SHUFPS: // Handle all target specific shuffles
12338 case X86ISD::SHUFPD:
12339 case X86ISD::PALIGN:
12340 case X86ISD::PUNPCKHBW:
12341 case X86ISD::PUNPCKHWD:
12342 case X86ISD::PUNPCKHDQ:
12343 case X86ISD::PUNPCKHQDQ:
12344 case X86ISD::UNPCKHPS:
12345 case X86ISD::UNPCKHPD:
12346 case X86ISD::PUNPCKLBW:
12347 case X86ISD::PUNPCKLWD:
12348 case X86ISD::PUNPCKLDQ:
12349 case X86ISD::PUNPCKLQDQ:
12350 case X86ISD::UNPCKLPS:
12351 case X86ISD::UNPCKLPD:
12352 case X86ISD::VUNPCKLPS:
12353 case X86ISD::VUNPCKLPD:
12354 case X86ISD::VUNPCKLPSY:
12355 case X86ISD::VUNPCKLPDY:
12356 case X86ISD::MOVHLPS:
12357 case X86ISD::MOVLHPS:
12358 case X86ISD::PSHUFD:
12359 case X86ISD::PSHUFHW:
12360 case X86ISD::PSHUFLW:
12361 case X86ISD::MOVSS:
12362 case X86ISD::MOVSD:
12363 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12369 /// isTypeDesirableForOp - Return true if the target has native support for
12370 /// the specified value type and it is 'desirable' to use the type for the
12371 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12372 /// instruction encodings are longer and some i16 instructions are slow.
12373 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12374 if (!isTypeLegal(VT))
12376 if (VT != MVT::i16)
12383 case ISD::SIGN_EXTEND:
12384 case ISD::ZERO_EXTEND:
12385 case ISD::ANY_EXTEND:
12398 /// IsDesirableToPromoteOp - This method query the target whether it is
12399 /// beneficial for dag combiner to promote the specified node. If true, it
12400 /// should return the desired promotion type by reference.
12401 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12402 EVT VT = Op.getValueType();
12403 if (VT != MVT::i16)
12406 bool Promote = false;
12407 bool Commute = false;
12408 switch (Op.getOpcode()) {
12411 LoadSDNode *LD = cast<LoadSDNode>(Op);
12412 // If the non-extending load has a single use and it's not live out, then it
12413 // might be folded.
12414 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12415 Op.hasOneUse()*/) {
12416 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12417 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12418 // The only case where we'd want to promote LOAD (rather then it being
12419 // promoted as an operand is when it's only use is liveout.
12420 if (UI->getOpcode() != ISD::CopyToReg)
12427 case ISD::SIGN_EXTEND:
12428 case ISD::ZERO_EXTEND:
12429 case ISD::ANY_EXTEND:
12434 SDValue N0 = Op.getOperand(0);
12435 // Look out for (store (shl (load), x)).
12436 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12449 SDValue N0 = Op.getOperand(0);
12450 SDValue N1 = Op.getOperand(1);
12451 if (!Commute && MayFoldLoad(N1))
12453 // Avoid disabling potential load folding opportunities.
12454 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12456 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12466 //===----------------------------------------------------------------------===//
12467 // X86 Inline Assembly Support
12468 //===----------------------------------------------------------------------===//
12470 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12471 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12473 std::string AsmStr = IA->getAsmString();
12475 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12476 SmallVector<StringRef, 4> AsmPieces;
12477 SplitString(AsmStr, AsmPieces, ";\n");
12479 switch (AsmPieces.size()) {
12480 default: return false;
12482 AsmStr = AsmPieces[0];
12484 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
12486 // FIXME: this should verify that we are targeting a 486 or better. If not,
12487 // we will turn this bswap into something that will be lowered to logical ops
12488 // instead of emitting the bswap asm. For now, we don't support 486 or lower
12489 // so don't worry about this.
12491 if (AsmPieces.size() == 2 &&
12492 (AsmPieces[0] == "bswap" ||
12493 AsmPieces[0] == "bswapq" ||
12494 AsmPieces[0] == "bswapl") &&
12495 (AsmPieces[1] == "$0" ||
12496 AsmPieces[1] == "${0:q}")) {
12497 // No need to check constraints, nothing other than the equivalent of
12498 // "=r,0" would be valid here.
12499 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12500 if (!Ty || Ty->getBitWidth() % 16 != 0)
12502 return IntrinsicLowering::LowerToByteSwap(CI);
12504 // rorw $$8, ${0:w} --> llvm.bswap.i16
12505 if (CI->getType()->isIntegerTy(16) &&
12506 AsmPieces.size() == 3 &&
12507 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12508 AsmPieces[1] == "$$8," &&
12509 AsmPieces[2] == "${0:w}" &&
12510 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12512 const std::string &ConstraintsStr = IA->getConstraintString();
12513 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12514 std::sort(AsmPieces.begin(), AsmPieces.end());
12515 if (AsmPieces.size() == 4 &&
12516 AsmPieces[0] == "~{cc}" &&
12517 AsmPieces[1] == "~{dirflag}" &&
12518 AsmPieces[2] == "~{flags}" &&
12519 AsmPieces[3] == "~{fpsr}") {
12520 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12521 if (!Ty || Ty->getBitWidth() % 16 != 0)
12523 return IntrinsicLowering::LowerToByteSwap(CI);
12528 if (CI->getType()->isIntegerTy(32) &&
12529 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12530 SmallVector<StringRef, 4> Words;
12531 SplitString(AsmPieces[0], Words, " \t,");
12532 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12533 Words[2] == "${0:w}") {
12535 SplitString(AsmPieces[1], Words, " \t,");
12536 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12537 Words[2] == "$0") {
12539 SplitString(AsmPieces[2], Words, " \t,");
12540 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12541 Words[2] == "${0:w}") {
12543 const std::string &ConstraintsStr = IA->getConstraintString();
12544 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12545 std::sort(AsmPieces.begin(), AsmPieces.end());
12546 if (AsmPieces.size() == 4 &&
12547 AsmPieces[0] == "~{cc}" &&
12548 AsmPieces[1] == "~{dirflag}" &&
12549 AsmPieces[2] == "~{flags}" &&
12550 AsmPieces[3] == "~{fpsr}") {
12551 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12552 if (!Ty || Ty->getBitWidth() % 16 != 0)
12554 return IntrinsicLowering::LowerToByteSwap(CI);
12561 if (CI->getType()->isIntegerTy(64)) {
12562 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12563 if (Constraints.size() >= 2 &&
12564 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12565 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12566 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
12567 SmallVector<StringRef, 4> Words;
12568 SplitString(AsmPieces[0], Words, " \t");
12569 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12571 SplitString(AsmPieces[1], Words, " \t");
12572 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12574 SplitString(AsmPieces[2], Words, " \t,");
12575 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12576 Words[2] == "%edx") {
12577 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12578 if (!Ty || Ty->getBitWidth() % 16 != 0)
12580 return IntrinsicLowering::LowerToByteSwap(CI);
12593 /// getConstraintType - Given a constraint letter, return the type of
12594 /// constraint it is for this target.
12595 X86TargetLowering::ConstraintType
12596 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12597 if (Constraint.size() == 1) {
12598 switch (Constraint[0]) {
12609 return C_RegisterClass;
12633 return TargetLowering::getConstraintType(Constraint);
12636 /// Examine constraint type and operand type and determine a weight value.
12637 /// This object must already have been set up with the operand type
12638 /// and the current alternative constraint selected.
12639 TargetLowering::ConstraintWeight
12640 X86TargetLowering::getSingleConstraintMatchWeight(
12641 AsmOperandInfo &info, const char *constraint) const {
12642 ConstraintWeight weight = CW_Invalid;
12643 Value *CallOperandVal = info.CallOperandVal;
12644 // If we don't have a value, we can't do a match,
12645 // but allow it at the lowest weight.
12646 if (CallOperandVal == NULL)
12648 const Type *type = CallOperandVal->getType();
12649 // Look at the constraint type.
12650 switch (*constraint) {
12652 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12663 if (CallOperandVal->getType()->isIntegerTy())
12664 weight = CW_SpecificReg;
12669 if (type->isFloatingPointTy())
12670 weight = CW_SpecificReg;
12673 if (type->isX86_MMXTy() && Subtarget->hasMMX())
12674 weight = CW_SpecificReg;
12678 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12679 weight = CW_Register;
12682 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12683 if (C->getZExtValue() <= 31)
12684 weight = CW_Constant;
12688 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12689 if (C->getZExtValue() <= 63)
12690 weight = CW_Constant;
12694 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12695 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12696 weight = CW_Constant;
12700 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12701 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12702 weight = CW_Constant;
12706 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12707 if (C->getZExtValue() <= 3)
12708 weight = CW_Constant;
12712 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12713 if (C->getZExtValue() <= 0xff)
12714 weight = CW_Constant;
12719 if (dyn_cast<ConstantFP>(CallOperandVal)) {
12720 weight = CW_Constant;
12724 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12725 if ((C->getSExtValue() >= -0x80000000LL) &&
12726 (C->getSExtValue() <= 0x7fffffffLL))
12727 weight = CW_Constant;
12731 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12732 if (C->getZExtValue() <= 0xffffffff)
12733 weight = CW_Constant;
12740 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12741 /// with another that has more specific requirements based on the type of the
12742 /// corresponding operand.
12743 const char *X86TargetLowering::
12744 LowerXConstraint(EVT ConstraintVT) const {
12745 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12746 // 'f' like normal targets.
12747 if (ConstraintVT.isFloatingPoint()) {
12748 if (Subtarget->hasXMMInt())
12750 if (Subtarget->hasXMM())
12754 return TargetLowering::LowerXConstraint(ConstraintVT);
12757 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12758 /// vector. If it is invalid, don't add anything to Ops.
12759 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12760 std::string &Constraint,
12761 std::vector<SDValue>&Ops,
12762 SelectionDAG &DAG) const {
12763 SDValue Result(0, 0);
12765 // Only support length 1 constraints for now.
12766 if (Constraint.length() > 1) return;
12768 char ConstraintLetter = Constraint[0];
12769 switch (ConstraintLetter) {
12772 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12773 if (C->getZExtValue() <= 31) {
12774 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12780 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12781 if (C->getZExtValue() <= 63) {
12782 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12788 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12789 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12790 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12796 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12797 if (C->getZExtValue() <= 255) {
12798 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12804 // 32-bit signed value
12805 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12806 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12807 C->getSExtValue())) {
12808 // Widen to 64 bits here to get it sign extended.
12809 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12812 // FIXME gcc accepts some relocatable values here too, but only in certain
12813 // memory models; it's complicated.
12818 // 32-bit unsigned value
12819 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12820 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12821 C->getZExtValue())) {
12822 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12826 // FIXME gcc accepts some relocatable values here too, but only in certain
12827 // memory models; it's complicated.
12831 // Literal immediates are always ok.
12832 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12833 // Widen to 64 bits here to get it sign extended.
12834 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12838 // In any sort of PIC mode addresses need to be computed at runtime by
12839 // adding in a register or some sort of table lookup. These can't
12840 // be used as immediates.
12841 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12844 // If we are in non-pic codegen mode, we allow the address of a global (with
12845 // an optional displacement) to be used with 'i'.
12846 GlobalAddressSDNode *GA = 0;
12847 int64_t Offset = 0;
12849 // Match either (GA), (GA+C), (GA+C1+C2), etc.
12851 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12852 Offset += GA->getOffset();
12854 } else if (Op.getOpcode() == ISD::ADD) {
12855 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12856 Offset += C->getZExtValue();
12857 Op = Op.getOperand(0);
12860 } else if (Op.getOpcode() == ISD::SUB) {
12861 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12862 Offset += -C->getZExtValue();
12863 Op = Op.getOperand(0);
12868 // Otherwise, this isn't something we can handle, reject it.
12872 const GlobalValue *GV = GA->getGlobal();
12873 // If we require an extra load to get this address, as in PIC mode, we
12874 // can't accept it.
12875 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12876 getTargetMachine())))
12879 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12880 GA->getValueType(0), Offset);
12885 if (Result.getNode()) {
12886 Ops.push_back(Result);
12889 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12892 std::pair<unsigned, const TargetRegisterClass*>
12893 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12895 // First, see if this is a constraint that directly corresponds to an LLVM
12897 if (Constraint.size() == 1) {
12898 // GCC Constraint Letters
12899 switch (Constraint[0]) {
12901 // TODO: Slight differences here in allocation order and leaving
12902 // RIP in the class. Do they matter any more here than they do
12903 // in the normal allocation?
12904 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12905 if (Subtarget->is64Bit()) {
12906 if (VT == MVT::i32 || VT == MVT::f32)
12907 return std::make_pair(0U, X86::GR32RegisterClass);
12908 else if (VT == MVT::i16)
12909 return std::make_pair(0U, X86::GR16RegisterClass);
12910 else if (VT == MVT::i8)
12911 return std::make_pair(0U, X86::GR8RegisterClass);
12912 else if (VT == MVT::i64 || VT == MVT::f64)
12913 return std::make_pair(0U, X86::GR64RegisterClass);
12916 // 32-bit fallthrough
12917 case 'Q': // Q_REGS
12918 if (VT == MVT::i32 || VT == MVT::f32)
12919 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
12920 else if (VT == MVT::i16)
12921 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
12922 else if (VT == MVT::i8)
12923 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
12924 else if (VT == MVT::i64)
12925 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
12927 case 'r': // GENERAL_REGS
12928 case 'l': // INDEX_REGS
12930 return std::make_pair(0U, X86::GR8RegisterClass);
12931 if (VT == MVT::i16)
12932 return std::make_pair(0U, X86::GR16RegisterClass);
12933 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
12934 return std::make_pair(0U, X86::GR32RegisterClass);
12935 return std::make_pair(0U, X86::GR64RegisterClass);
12936 case 'R': // LEGACY_REGS
12938 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12939 if (VT == MVT::i16)
12940 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12941 if (VT == MVT::i32 || !Subtarget->is64Bit())
12942 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12943 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12944 case 'f': // FP Stack registers.
12945 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12946 // value to the correct fpstack register class.
12947 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12948 return std::make_pair(0U, X86::RFP32RegisterClass);
12949 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12950 return std::make_pair(0U, X86::RFP64RegisterClass);
12951 return std::make_pair(0U, X86::RFP80RegisterClass);
12952 case 'y': // MMX_REGS if MMX allowed.
12953 if (!Subtarget->hasMMX()) break;
12954 return std::make_pair(0U, X86::VR64RegisterClass);
12955 case 'Y': // SSE_REGS if SSE2 allowed
12956 if (!Subtarget->hasXMMInt()) break;
12958 case 'x': // SSE_REGS if SSE1 allowed
12959 if (!Subtarget->hasXMM()) break;
12961 switch (VT.getSimpleVT().SimpleTy) {
12963 // Scalar SSE types.
12966 return std::make_pair(0U, X86::FR32RegisterClass);
12969 return std::make_pair(0U, X86::FR64RegisterClass);
12977 return std::make_pair(0U, X86::VR128RegisterClass);
12983 // Use the default implementation in TargetLowering to convert the register
12984 // constraint into a member of a register class.
12985 std::pair<unsigned, const TargetRegisterClass*> Res;
12986 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12988 // Not found as a standard register?
12989 if (Res.second == 0) {
12990 // Map st(0) -> st(7) -> ST0
12991 if (Constraint.size() == 7 && Constraint[0] == '{' &&
12992 tolower(Constraint[1]) == 's' &&
12993 tolower(Constraint[2]) == 't' &&
12994 Constraint[3] == '(' &&
12995 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12996 Constraint[5] == ')' &&
12997 Constraint[6] == '}') {
12999 Res.first = X86::ST0+Constraint[4]-'0';
13000 Res.second = X86::RFP80RegisterClass;
13004 // GCC allows "st(0)" to be called just plain "st".
13005 if (StringRef("{st}").equals_lower(Constraint)) {
13006 Res.first = X86::ST0;
13007 Res.second = X86::RFP80RegisterClass;
13012 if (StringRef("{flags}").equals_lower(Constraint)) {
13013 Res.first = X86::EFLAGS;
13014 Res.second = X86::CCRRegisterClass;
13018 // 'A' means EAX + EDX.
13019 if (Constraint == "A") {
13020 Res.first = X86::EAX;
13021 Res.second = X86::GR32_ADRegisterClass;
13027 // Otherwise, check to see if this is a register class of the wrong value
13028 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
13029 // turn into {ax},{dx}.
13030 if (Res.second->hasType(VT))
13031 return Res; // Correct type already, nothing to do.
13033 // All of the single-register GCC register classes map their values onto
13034 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
13035 // really want an 8-bit or 32-bit register, map to the appropriate register
13036 // class and return the appropriate register.
13037 if (Res.second == X86::GR16RegisterClass) {
13038 if (VT == MVT::i8) {
13039 unsigned DestReg = 0;
13040 switch (Res.first) {
13042 case X86::AX: DestReg = X86::AL; break;
13043 case X86::DX: DestReg = X86::DL; break;
13044 case X86::CX: DestReg = X86::CL; break;
13045 case X86::BX: DestReg = X86::BL; break;
13048 Res.first = DestReg;
13049 Res.second = X86::GR8RegisterClass;
13051 } else if (VT == MVT::i32) {
13052 unsigned DestReg = 0;
13053 switch (Res.first) {
13055 case X86::AX: DestReg = X86::EAX; break;
13056 case X86::DX: DestReg = X86::EDX; break;
13057 case X86::CX: DestReg = X86::ECX; break;
13058 case X86::BX: DestReg = X86::EBX; break;
13059 case X86::SI: DestReg = X86::ESI; break;
13060 case X86::DI: DestReg = X86::EDI; break;
13061 case X86::BP: DestReg = X86::EBP; break;
13062 case X86::SP: DestReg = X86::ESP; break;
13065 Res.first = DestReg;
13066 Res.second = X86::GR32RegisterClass;
13068 } else if (VT == MVT::i64) {
13069 unsigned DestReg = 0;
13070 switch (Res.first) {
13072 case X86::AX: DestReg = X86::RAX; break;
13073 case X86::DX: DestReg = X86::RDX; break;
13074 case X86::CX: DestReg = X86::RCX; break;
13075 case X86::BX: DestReg = X86::RBX; break;
13076 case X86::SI: DestReg = X86::RSI; break;
13077 case X86::DI: DestReg = X86::RDI; break;
13078 case X86::BP: DestReg = X86::RBP; break;
13079 case X86::SP: DestReg = X86::RSP; break;
13082 Res.first = DestReg;
13083 Res.second = X86::GR64RegisterClass;
13086 } else if (Res.second == X86::FR32RegisterClass ||
13087 Res.second == X86::FR64RegisterClass ||
13088 Res.second == X86::VR128RegisterClass) {
13089 // Handle references to XMM physical registers that got mapped into the
13090 // wrong class. This can happen with constraints like {xmm0} where the
13091 // target independent register mapper will just pick the first match it can
13092 // find, ignoring the required type.
13093 if (VT == MVT::f32)
13094 Res.second = X86::FR32RegisterClass;
13095 else if (VT == MVT::f64)
13096 Res.second = X86::FR64RegisterClass;
13097 else if (X86::VR128RegisterClass->hasType(VT))
13098 Res.second = X86::VR128RegisterClass;