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/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
54 using namespace dwarf;
56 STATISTIC(NumTailCalls, "Number of tail calls");
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62 static SDValue Insert128BitVector(SDValue Result,
68 static SDValue Extract128BitVector(SDValue Vec,
73 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
76 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
77 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
78 /// simple subregister reference. Idx is an index in the 128 bits we
79 /// want. It need not be aligned to a 128-bit bounday. That makes
80 /// lowering EXTRACT_VECTOR_ELT operations easier.
81 static SDValue Extract128BitVector(SDValue Vec,
85 EVT VT = Vec.getValueType();
86 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
88 EVT ElVT = VT.getVectorElementType();
90 int Factor = VT.getSizeInBits() / 128;
92 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(),
94 VT.getVectorNumElements() / Factor);
96 // Extract from UNDEF is UNDEF.
97 if (Vec.getOpcode() == ISD::UNDEF)
98 return DAG.getNode(ISD::UNDEF, dl, ResultVT);
100 if (isa<ConstantSDNode>(Idx)) {
101 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
103 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
104 // we can match to VEXTRACTF128.
105 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
107 // This is the index of the first element of the 128-bit chunk
109 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
112 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
114 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
123 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
124 /// sets things up to match to an AVX VINSERTF128 instruction or a
125 /// simple superregister reference. Idx is an index in the 128 bits
126 /// we want. It need not be aligned to a 128-bit bounday. That makes
127 /// lowering INSERT_VECTOR_ELT operations easier.
128 static SDValue Insert128BitVector(SDValue Result,
133 if (isa<ConstantSDNode>(Idx)) {
134 EVT VT = Vec.getValueType();
135 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
137 EVT ElVT = VT.getVectorElementType();
139 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
141 EVT ResultVT = Result.getValueType();
143 // Insert the relevant 128 bits.
144 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
146 // This is the index of the first element of the 128-bit chunk
148 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
151 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
153 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
161 /// Given two vectors, concat them.
162 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
163 DebugLoc dl = Lower.getDebugLoc();
165 assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
167 EVT VT = EVT::getVectorVT(*DAG.getContext(),
168 Lower.getValueType().getVectorElementType(),
169 Lower.getValueType().getVectorNumElements() * 2);
171 // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
172 assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
174 // Insert the upper subvector.
175 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
177 // This is half the length of the result
178 // vector. Start inserting the upper 128
180 Lower.getValueType().getVectorNumElements(),
184 // Insert the lower subvector.
185 Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
189 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
190 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
191 bool is64Bit = Subtarget->is64Bit();
193 if (Subtarget->isTargetEnvMacho()) {
195 return new X8664_MachoTargetObjectFile();
196 return new TargetLoweringObjectFileMachO();
199 if (Subtarget->isTargetELF()) {
201 return new X8664_ELFTargetObjectFile(TM);
202 return new X8632_ELFTargetObjectFile(TM);
204 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
205 return new TargetLoweringObjectFileCOFF();
206 llvm_unreachable("unknown subtarget type");
209 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
210 : TargetLowering(TM, createTLOF(TM)) {
211 Subtarget = &TM.getSubtarget<X86Subtarget>();
212 X86ScalarSSEf64 = Subtarget->hasXMMInt();
213 X86ScalarSSEf32 = Subtarget->hasXMM();
214 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
216 RegInfo = TM.getRegisterInfo();
217 TD = getTargetData();
219 // Set up the TargetLowering object.
220 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
222 // X86 is weird, it always uses i8 for shift amounts and setcc results.
223 setBooleanContents(ZeroOrOneBooleanContent);
225 // For 64-bit since we have so many registers use the ILP scheduler, for
226 // 32-bit code use the register pressure specific scheduling.
227 if (Subtarget->is64Bit())
228 setSchedulingPreference(Sched::ILP);
230 setSchedulingPreference(Sched::RegPressure);
231 setStackPointerRegisterToSaveRestore(X86StackPtr);
233 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
234 // Setup Windows compiler runtime calls.
235 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
236 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
237 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
238 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
239 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
240 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
241 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
242 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
245 if (Subtarget->isTargetDarwin()) {
246 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
247 setUseUnderscoreSetJmp(false);
248 setUseUnderscoreLongJmp(false);
249 } else if (Subtarget->isTargetMingw()) {
250 // MS runtime is weird: it exports _setjmp, but longjmp!
251 setUseUnderscoreSetJmp(true);
252 setUseUnderscoreLongJmp(false);
254 setUseUnderscoreSetJmp(true);
255 setUseUnderscoreLongJmp(true);
258 // Set up the register classes.
259 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
260 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
261 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
262 if (Subtarget->is64Bit())
263 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
265 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
267 // We don't accept any truncstore of integer registers.
268 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
269 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
270 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
271 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
272 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
273 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
275 // SETOEQ and SETUNE require checking two conditions.
276 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
277 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
278 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
279 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
280 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
281 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
283 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
285 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
286 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
287 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
289 if (Subtarget->is64Bit()) {
290 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
291 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
292 } else if (!UseSoftFloat) {
293 // We have an algorithm for SSE2->double, and we turn this into a
294 // 64-bit FILD followed by conditional FADD for other targets.
295 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
296 // We have an algorithm for SSE2, and we turn this into a 64-bit
297 // FILD for other targets.
298 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
301 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
303 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
304 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
307 // SSE has no i16 to fp conversion, only i32
308 if (X86ScalarSSEf32) {
309 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
310 // f32 and f64 cases are Legal, f80 case is not
311 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
313 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
314 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
317 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
318 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
321 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
322 // are Legal, f80 is custom lowered.
323 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
324 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
326 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
328 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
329 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
331 if (X86ScalarSSEf32) {
332 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
333 // f32 and f64 cases are Legal, f80 case is not
334 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
336 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
337 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
340 // Handle FP_TO_UINT by promoting the destination to a larger signed
342 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
343 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
344 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
346 if (Subtarget->is64Bit()) {
347 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
348 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
349 } else if (!UseSoftFloat) {
350 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
351 // Expand FP_TO_UINT into a select.
352 // FIXME: We would like to use a Custom expander here eventually to do
353 // the optimal thing for SSE vs. the default expansion in the legalizer.
354 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
356 // With SSE3 we can use fisttpll to convert to a signed i64; without
357 // SSE, we're stuck with a fistpll.
358 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
361 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
362 if (!X86ScalarSSEf64) {
363 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
364 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
365 if (Subtarget->is64Bit()) {
366 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
367 // Without SSE, i64->f64 goes through memory.
368 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
372 // Scalar integer divide and remainder are lowered to use operations that
373 // produce two results, to match the available instructions. This exposes
374 // the two-result form to trivial CSE, which is able to combine x/y and x%y
375 // into a single instruction.
377 // Scalar integer multiply-high is also lowered to use two-result
378 // operations, to match the available instructions. However, plain multiply
379 // (low) operations are left as Legal, as there are single-result
380 // instructions for this in x86. Using the two-result multiply instructions
381 // when both high and low results are needed must be arranged by dagcombine.
382 for (unsigned i = 0, e = 4; i != e; ++i) {
384 setOperationAction(ISD::MULHS, VT, Expand);
385 setOperationAction(ISD::MULHU, VT, Expand);
386 setOperationAction(ISD::SDIV, VT, Expand);
387 setOperationAction(ISD::UDIV, VT, Expand);
388 setOperationAction(ISD::SREM, VT, Expand);
389 setOperationAction(ISD::UREM, VT, Expand);
391 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
392 setOperationAction(ISD::ADDC, VT, Custom);
393 setOperationAction(ISD::ADDE, VT, Custom);
394 setOperationAction(ISD::SUBC, VT, Custom);
395 setOperationAction(ISD::SUBE, VT, Custom);
398 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
399 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
400 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
401 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
402 if (Subtarget->is64Bit())
403 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
404 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
405 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
406 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
407 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
408 setOperationAction(ISD::FREM , MVT::f32 , Expand);
409 setOperationAction(ISD::FREM , MVT::f64 , Expand);
410 setOperationAction(ISD::FREM , MVT::f80 , Expand);
411 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
413 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
414 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
415 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
416 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
417 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
418 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
419 if (Subtarget->is64Bit()) {
420 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
421 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
424 if (Subtarget->hasPOPCNT()) {
425 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
427 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
428 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
429 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
430 if (Subtarget->is64Bit())
431 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
434 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
435 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
437 // These should be promoted to a larger select which is supported.
438 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
439 // X86 wants to expand cmov itself.
440 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
441 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
442 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
443 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
444 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
445 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
446 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
447 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
448 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
449 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
450 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
451 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
452 if (Subtarget->is64Bit()) {
453 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
454 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
456 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
459 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
460 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
461 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
462 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
463 if (Subtarget->is64Bit())
464 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
465 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
466 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
467 if (Subtarget->is64Bit()) {
468 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
469 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
470 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
471 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
472 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
474 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
475 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
476 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
477 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
478 if (Subtarget->is64Bit()) {
479 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
480 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
481 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
484 if (Subtarget->hasXMM())
485 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
487 // We may not have a libcall for MEMBARRIER so we should lower this.
488 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
490 // On X86 and X86-64, atomic operations are lowered to locked instructions.
491 // Locked instructions, in turn, have implicit fence semantics (all memory
492 // operations are flushed before issuing the locked instruction, and they
493 // are not buffered), so we can fold away the common pattern of
494 // fence-atomic-fence.
495 setShouldFoldAtomicFences(true);
497 // Expand certain atomics
498 for (unsigned i = 0, e = 4; i != e; ++i) {
500 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
501 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
504 if (!Subtarget->is64Bit()) {
505 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
506 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
507 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
508 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
509 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
510 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
511 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
514 // FIXME - use subtarget debug flags
515 if (!Subtarget->isTargetDarwin() &&
516 !Subtarget->isTargetELF() &&
517 !Subtarget->isTargetCygMing()) {
518 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
521 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
522 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
523 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
524 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
525 if (Subtarget->is64Bit()) {
526 setExceptionPointerRegister(X86::RAX);
527 setExceptionSelectorRegister(X86::RDX);
529 setExceptionPointerRegister(X86::EAX);
530 setExceptionSelectorRegister(X86::EDX);
532 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
533 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
535 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
537 setOperationAction(ISD::TRAP, MVT::Other, Legal);
539 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
540 setOperationAction(ISD::VASTART , MVT::Other, Custom);
541 setOperationAction(ISD::VAEND , MVT::Other, Expand);
542 if (Subtarget->is64Bit()) {
543 setOperationAction(ISD::VAARG , MVT::Other, Custom);
544 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
546 setOperationAction(ISD::VAARG , MVT::Other, Expand);
547 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
550 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
551 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
552 if (Subtarget->is64Bit())
553 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
554 if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
555 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
557 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
559 if (!UseSoftFloat && X86ScalarSSEf64) {
560 // f32 and f64 use SSE.
561 // Set up the FP register classes.
562 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
563 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
565 // Use ANDPD to simulate FABS.
566 setOperationAction(ISD::FABS , MVT::f64, Custom);
567 setOperationAction(ISD::FABS , MVT::f32, Custom);
569 // Use XORP to simulate FNEG.
570 setOperationAction(ISD::FNEG , MVT::f64, Custom);
571 setOperationAction(ISD::FNEG , MVT::f32, Custom);
573 // Use ANDPD and ORPD to simulate FCOPYSIGN.
574 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
575 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
577 // We don't support sin/cos/fmod
578 setOperationAction(ISD::FSIN , MVT::f64, Expand);
579 setOperationAction(ISD::FCOS , MVT::f64, Expand);
580 setOperationAction(ISD::FSIN , MVT::f32, Expand);
581 setOperationAction(ISD::FCOS , MVT::f32, Expand);
583 // Expand FP immediates into loads from the stack, except for the special
585 addLegalFPImmediate(APFloat(+0.0)); // xorpd
586 addLegalFPImmediate(APFloat(+0.0f)); // xorps
587 } else if (!UseSoftFloat && X86ScalarSSEf32) {
588 // Use SSE for f32, x87 for f64.
589 // Set up the FP register classes.
590 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
591 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
593 // Use ANDPS to simulate FABS.
594 setOperationAction(ISD::FABS , MVT::f32, Custom);
596 // Use XORP to simulate FNEG.
597 setOperationAction(ISD::FNEG , MVT::f32, Custom);
599 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
601 // Use ANDPS and ORPS to simulate FCOPYSIGN.
602 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
603 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
605 // We don't support sin/cos/fmod
606 setOperationAction(ISD::FSIN , MVT::f32, Expand);
607 setOperationAction(ISD::FCOS , MVT::f32, Expand);
609 // Special cases we handle for FP constants.
610 addLegalFPImmediate(APFloat(+0.0f)); // xorps
611 addLegalFPImmediate(APFloat(+0.0)); // FLD0
612 addLegalFPImmediate(APFloat(+1.0)); // FLD1
613 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
614 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
617 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
618 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
620 } else if (!UseSoftFloat) {
621 // f32 and f64 in x87.
622 // Set up the FP register classes.
623 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
624 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
626 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
627 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
628 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
629 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
632 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
633 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
635 addLegalFPImmediate(APFloat(+0.0)); // FLD0
636 addLegalFPImmediate(APFloat(+1.0)); // FLD1
637 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
638 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
639 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
640 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
641 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
642 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
645 // Long double always uses X87.
647 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
648 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
649 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
651 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
652 addLegalFPImmediate(TmpFlt); // FLD0
654 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
657 APFloat TmpFlt2(+1.0);
658 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
660 addLegalFPImmediate(TmpFlt2); // FLD1
661 TmpFlt2.changeSign();
662 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
666 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
667 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
671 // Always use a library call for pow.
672 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
673 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
674 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
676 setOperationAction(ISD::FLOG, MVT::f80, Expand);
677 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
678 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
679 setOperationAction(ISD::FEXP, MVT::f80, Expand);
680 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
682 // First set operation action for all vector types to either promote
683 // (for widening) or expand (for scalarization). Then we will selectively
684 // turn on ones that can be effectively codegen'd.
685 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
686 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
687 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
688 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
689 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
690 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
691 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
692 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
693 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
694 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
695 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
696 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
698 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
699 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
700 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
701 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
702 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
703 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
704 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
705 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
737 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
741 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
742 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
743 setTruncStoreAction((MVT::SimpleValueType)VT,
744 (MVT::SimpleValueType)InnerVT, Expand);
745 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
747 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
750 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
751 // with -msoft-float, disable use of MMX as well.
752 if (!UseSoftFloat && Subtarget->hasMMX()) {
753 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
754 // No operations on x86mmx supported, everything uses intrinsics.
757 // MMX-sized vectors (other than x86mmx) are expected to be expanded
758 // into smaller operations.
759 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
760 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
761 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
762 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
763 setOperationAction(ISD::AND, MVT::v8i8, Expand);
764 setOperationAction(ISD::AND, MVT::v4i16, Expand);
765 setOperationAction(ISD::AND, MVT::v2i32, Expand);
766 setOperationAction(ISD::AND, MVT::v1i64, Expand);
767 setOperationAction(ISD::OR, MVT::v8i8, Expand);
768 setOperationAction(ISD::OR, MVT::v4i16, Expand);
769 setOperationAction(ISD::OR, MVT::v2i32, Expand);
770 setOperationAction(ISD::OR, MVT::v1i64, Expand);
771 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
772 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
773 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
774 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
775 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
776 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
777 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
778 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
779 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
780 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
781 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
782 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
783 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
784 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
785 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
786 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
787 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
789 if (!UseSoftFloat && Subtarget->hasXMM()) {
790 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
792 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
793 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
794 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
795 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
796 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
797 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
798 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
799 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
800 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
801 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
802 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
803 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
806 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
807 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
809 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
810 // registers cannot be used even for integer operations.
811 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
812 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
813 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
814 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
816 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
817 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
818 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
819 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
820 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
821 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
822 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
823 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
824 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
825 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
826 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
827 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
828 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
829 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
830 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
831 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
833 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
834 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
835 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
836 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
838 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
839 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
840 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
841 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
842 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
844 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
845 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
846 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
847 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
848 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
850 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
851 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
852 EVT VT = (MVT::SimpleValueType)i;
853 // Do not attempt to custom lower non-power-of-2 vectors
854 if (!isPowerOf2_32(VT.getVectorNumElements()))
856 // Do not attempt to custom lower non-128-bit vectors
857 if (!VT.is128BitVector())
859 setOperationAction(ISD::BUILD_VECTOR,
860 VT.getSimpleVT().SimpleTy, Custom);
861 setOperationAction(ISD::VECTOR_SHUFFLE,
862 VT.getSimpleVT().SimpleTy, Custom);
863 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
864 VT.getSimpleVT().SimpleTy, Custom);
867 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
868 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
869 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
870 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
871 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
872 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
874 if (Subtarget->is64Bit()) {
875 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
876 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
879 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
880 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
881 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
884 // Do not attempt to promote non-128-bit vectors
885 if (!VT.is128BitVector())
888 setOperationAction(ISD::AND, SVT, Promote);
889 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
890 setOperationAction(ISD::OR, SVT, Promote);
891 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
892 setOperationAction(ISD::XOR, SVT, Promote);
893 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
894 setOperationAction(ISD::LOAD, SVT, Promote);
895 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
896 setOperationAction(ISD::SELECT, SVT, Promote);
897 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
900 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
902 // Custom lower v2i64 and v2f64 selects.
903 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
904 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
905 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
906 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
908 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
909 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
912 if (Subtarget->hasSSE41()) {
913 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
914 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
915 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
916 setOperationAction(ISD::FRINT, MVT::f32, Legal);
917 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
918 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
919 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
920 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
921 setOperationAction(ISD::FRINT, MVT::f64, Legal);
922 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
924 // FIXME: Do we need to handle scalar-to-vector here?
925 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
927 // Can turn SHL into an integer multiply.
928 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
929 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
931 // i8 and i16 vectors are custom , because the source register and source
932 // source memory operand types are not the same width. f32 vectors are
933 // custom since the immediate controlling the insert encodes additional
935 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
936 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
937 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
938 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
940 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
941 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
942 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
943 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
945 if (Subtarget->is64Bit()) {
946 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
947 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
951 if (Subtarget->hasSSE42())
952 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
954 if (!UseSoftFloat && Subtarget->hasAVX()) {
955 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
956 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
957 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
958 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
959 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
961 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
962 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
963 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
964 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
966 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
967 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
968 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
969 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
970 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
971 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
973 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
974 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
975 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
976 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
977 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
978 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
980 // Custom lower build_vector, vector_shuffle, scalar_to_vector,
981 // insert_vector_elt extract_subvector and extract_vector_elt for
983 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
984 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
986 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
987 // Do not attempt to custom lower non-256-bit vectors
988 if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
989 || (MVT(VT).getSizeInBits() < 256))
991 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
992 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
993 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
994 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
995 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
997 // Custom-lower insert_subvector and extract_subvector based on
999 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1000 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1002 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1003 // Do not attempt to custom lower non-256-bit vectors
1004 if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1007 if (MVT(VT).getSizeInBits() == 128) {
1008 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1010 else if (MVT(VT).getSizeInBits() == 256) {
1011 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1015 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1016 // Don't promote loads because we need them for VPERM vector index versions.
1018 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1019 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1021 if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1022 || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1024 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
1025 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v4i64);
1026 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
1027 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v4i64);
1028 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
1029 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v4i64);
1030 //setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
1031 //AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v4i64);
1032 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1033 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1037 // We want to custom lower some of our intrinsics.
1038 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1041 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1042 // handle type legalization for these operations here.
1044 // FIXME: We really should do custom legalization for addition and
1045 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1046 // than generic legalization for 64-bit multiplication-with-overflow, though.
1047 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1048 // Add/Sub/Mul with overflow operations are custom lowered.
1050 setOperationAction(ISD::SADDO, VT, Custom);
1051 setOperationAction(ISD::UADDO, VT, Custom);
1052 setOperationAction(ISD::SSUBO, VT, Custom);
1053 setOperationAction(ISD::USUBO, VT, Custom);
1054 setOperationAction(ISD::SMULO, VT, Custom);
1055 setOperationAction(ISD::UMULO, VT, Custom);
1058 // There are no 8-bit 3-address imul/mul instructions
1059 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1060 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1062 if (!Subtarget->is64Bit()) {
1063 // These libcalls are not available in 32-bit.
1064 setLibcallName(RTLIB::SHL_I128, 0);
1065 setLibcallName(RTLIB::SRL_I128, 0);
1066 setLibcallName(RTLIB::SRA_I128, 0);
1069 // We have target-specific dag combine patterns for the following nodes:
1070 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1071 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1072 setTargetDAGCombine(ISD::BUILD_VECTOR);
1073 setTargetDAGCombine(ISD::SELECT);
1074 setTargetDAGCombine(ISD::SHL);
1075 setTargetDAGCombine(ISD::SRA);
1076 setTargetDAGCombine(ISD::SRL);
1077 setTargetDAGCombine(ISD::OR);
1078 setTargetDAGCombine(ISD::AND);
1079 setTargetDAGCombine(ISD::ADD);
1080 setTargetDAGCombine(ISD::SUB);
1081 setTargetDAGCombine(ISD::STORE);
1082 setTargetDAGCombine(ISD::ZERO_EXTEND);
1083 if (Subtarget->is64Bit())
1084 setTargetDAGCombine(ISD::MUL);
1086 computeRegisterProperties();
1088 // On Darwin, -Os means optimize for size without hurting performance,
1089 // do not reduce the limit.
1090 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1091 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1092 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1093 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1094 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1095 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1096 setPrefLoopAlignment(16);
1097 benefitFromCodePlacementOpt = true;
1101 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1106 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1107 /// the desired ByVal argument alignment.
1108 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1111 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1112 if (VTy->getBitWidth() == 128)
1114 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1115 unsigned EltAlign = 0;
1116 getMaxByValAlign(ATy->getElementType(), EltAlign);
1117 if (EltAlign > MaxAlign)
1118 MaxAlign = EltAlign;
1119 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1120 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1121 unsigned EltAlign = 0;
1122 getMaxByValAlign(STy->getElementType(i), EltAlign);
1123 if (EltAlign > MaxAlign)
1124 MaxAlign = EltAlign;
1132 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1133 /// function arguments in the caller parameter area. For X86, aggregates
1134 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1135 /// are at 4-byte boundaries.
1136 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1137 if (Subtarget->is64Bit()) {
1138 // Max of 8 and alignment of type.
1139 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1146 if (Subtarget->hasXMM())
1147 getMaxByValAlign(Ty, Align);
1151 /// getOptimalMemOpType - Returns the target specific optimal type for load
1152 /// and store operations as a result of memset, memcpy, and memmove
1153 /// lowering. If DstAlign is zero that means it's safe to destination
1154 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1155 /// means there isn't a need to check it against alignment requirement,
1156 /// probably because the source does not need to be loaded. If
1157 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1158 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1159 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1160 /// constant so it does not need to be loaded.
1161 /// It returns EVT::Other if the type should be determined using generic
1162 /// target-independent logic.
1164 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1165 unsigned DstAlign, unsigned SrcAlign,
1166 bool NonScalarIntSafe,
1168 MachineFunction &MF) const {
1169 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1170 // linux. This is because the stack realignment code can't handle certain
1171 // cases like PR2962. This should be removed when PR2962 is fixed.
1172 const Function *F = MF.getFunction();
1173 if (NonScalarIntSafe &&
1174 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1176 (Subtarget->isUnalignedMemAccessFast() ||
1177 ((DstAlign == 0 || DstAlign >= 16) &&
1178 (SrcAlign == 0 || SrcAlign >= 16))) &&
1179 Subtarget->getStackAlignment() >= 16) {
1180 if (Subtarget->hasSSE2())
1182 if (Subtarget->hasSSE1())
1184 } else if (!MemcpyStrSrc && Size >= 8 &&
1185 !Subtarget->is64Bit() &&
1186 Subtarget->getStackAlignment() >= 8 &&
1187 Subtarget->hasXMMInt()) {
1188 // Do not use f64 to lower memcpy if source is string constant. It's
1189 // better to use i32 to avoid the loads.
1193 if (Subtarget->is64Bit() && Size >= 8)
1198 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1199 /// current function. The returned value is a member of the
1200 /// MachineJumpTableInfo::JTEntryKind enum.
1201 unsigned X86TargetLowering::getJumpTableEncoding() const {
1202 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1204 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1205 Subtarget->isPICStyleGOT())
1206 return MachineJumpTableInfo::EK_Custom32;
1208 // Otherwise, use the normal jump table encoding heuristics.
1209 return TargetLowering::getJumpTableEncoding();
1213 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1214 const MachineBasicBlock *MBB,
1215 unsigned uid,MCContext &Ctx) const{
1216 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1217 Subtarget->isPICStyleGOT());
1218 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1220 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1221 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1224 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1226 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1227 SelectionDAG &DAG) const {
1228 if (!Subtarget->is64Bit())
1229 // This doesn't have DebugLoc associated with it, but is not really the
1230 // same as a Register.
1231 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1235 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1236 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1238 const MCExpr *X86TargetLowering::
1239 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1240 MCContext &Ctx) const {
1241 // X86-64 uses RIP relative addressing based on the jump table label.
1242 if (Subtarget->isPICStyleRIPRel())
1243 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1245 // Otherwise, the reference is relative to the PIC base.
1246 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1249 /// getFunctionAlignment - Return the Log2 alignment of this function.
1250 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1251 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1254 // FIXME: Why this routine is here? Move to RegInfo!
1255 std::pair<const TargetRegisterClass*, uint8_t>
1256 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1257 const TargetRegisterClass *RRC = 0;
1259 switch (VT.getSimpleVT().SimpleTy) {
1261 return TargetLowering::findRepresentativeClass(VT);
1262 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1263 RRC = (Subtarget->is64Bit()
1264 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1267 RRC = X86::VR64RegisterClass;
1269 case MVT::f32: case MVT::f64:
1270 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1271 case MVT::v4f32: case MVT::v2f64:
1272 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1274 RRC = X86::VR128RegisterClass;
1277 return std::make_pair(RRC, Cost);
1280 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1281 unsigned &Offset) const {
1282 if (!Subtarget->isTargetLinux())
1285 if (Subtarget->is64Bit()) {
1286 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1288 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1301 //===----------------------------------------------------------------------===//
1302 // Return Value Calling Convention Implementation
1303 //===----------------------------------------------------------------------===//
1305 #include "X86GenCallingConv.inc"
1308 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1309 const SmallVectorImpl<ISD::OutputArg> &Outs,
1310 LLVMContext &Context) const {
1311 SmallVector<CCValAssign, 16> RVLocs;
1312 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1314 return CCInfo.CheckReturn(Outs, RetCC_X86);
1318 X86TargetLowering::LowerReturn(SDValue Chain,
1319 CallingConv::ID CallConv, bool isVarArg,
1320 const SmallVectorImpl<ISD::OutputArg> &Outs,
1321 const SmallVectorImpl<SDValue> &OutVals,
1322 DebugLoc dl, SelectionDAG &DAG) const {
1323 MachineFunction &MF = DAG.getMachineFunction();
1324 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1326 SmallVector<CCValAssign, 16> RVLocs;
1327 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1328 RVLocs, *DAG.getContext());
1329 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1331 // Add the regs to the liveout set for the function.
1332 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1333 for (unsigned i = 0; i != RVLocs.size(); ++i)
1334 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1335 MRI.addLiveOut(RVLocs[i].getLocReg());
1339 SmallVector<SDValue, 6> RetOps;
1340 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1341 // Operand #1 = Bytes To Pop
1342 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1345 // Copy the result values into the output registers.
1346 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1347 CCValAssign &VA = RVLocs[i];
1348 assert(VA.isRegLoc() && "Can only return in registers!");
1349 SDValue ValToCopy = OutVals[i];
1350 EVT ValVT = ValToCopy.getValueType();
1352 // If this is x86-64, and we disabled SSE, we can't return FP values,
1353 // or SSE or MMX vectors.
1354 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1355 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1356 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1357 report_fatal_error("SSE register return with SSE disabled");
1359 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1360 // llvm-gcc has never done it right and no one has noticed, so this
1361 // should be OK for now.
1362 if (ValVT == MVT::f64 &&
1363 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1364 report_fatal_error("SSE2 register return with SSE2 disabled");
1366 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1367 // the RET instruction and handled by the FP Stackifier.
1368 if (VA.getLocReg() == X86::ST0 ||
1369 VA.getLocReg() == X86::ST1) {
1370 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1371 // change the value to the FP stack register class.
1372 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1373 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1374 RetOps.push_back(ValToCopy);
1375 // Don't emit a copytoreg.
1379 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1380 // which is returned in RAX / RDX.
1381 if (Subtarget->is64Bit()) {
1382 if (ValVT == MVT::x86mmx) {
1383 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1384 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1385 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1387 // If we don't have SSE2 available, convert to v4f32 so the generated
1388 // register is legal.
1389 if (!Subtarget->hasSSE2())
1390 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1395 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1396 Flag = Chain.getValue(1);
1399 // The x86-64 ABI for returning structs by value requires that we copy
1400 // the sret argument into %rax for the return. We saved the argument into
1401 // a virtual register in the entry block, so now we copy the value out
1403 if (Subtarget->is64Bit() &&
1404 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1405 MachineFunction &MF = DAG.getMachineFunction();
1406 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1407 unsigned Reg = FuncInfo->getSRetReturnReg();
1409 "SRetReturnReg should have been set in LowerFormalArguments().");
1410 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1412 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1413 Flag = Chain.getValue(1);
1415 // RAX now acts like a return value.
1416 MRI.addLiveOut(X86::RAX);
1419 RetOps[0] = Chain; // Update chain.
1421 // Add the flag if we have it.
1423 RetOps.push_back(Flag);
1425 return DAG.getNode(X86ISD::RET_FLAG, dl,
1426 MVT::Other, &RetOps[0], RetOps.size());
1429 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1430 if (N->getNumValues() != 1)
1432 if (!N->hasNUsesOfValue(1, 0))
1435 SDNode *Copy = *N->use_begin();
1436 if (Copy->getOpcode() != ISD::CopyToReg &&
1437 Copy->getOpcode() != ISD::FP_EXTEND)
1440 bool HasRet = false;
1441 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1443 if (UI->getOpcode() != X86ISD::RET_FLAG)
1452 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1453 ISD::NodeType ExtendKind) const {
1455 // TODO: Is this also valid on 32-bit?
1456 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1457 ReturnMVT = MVT::i8;
1459 ReturnMVT = MVT::i32;
1461 EVT MinVT = getRegisterType(Context, ReturnMVT);
1462 return VT.bitsLT(MinVT) ? MinVT : VT;
1465 /// LowerCallResult - Lower the result values of a call into the
1466 /// appropriate copies out of appropriate physical registers.
1469 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1470 CallingConv::ID CallConv, bool isVarArg,
1471 const SmallVectorImpl<ISD::InputArg> &Ins,
1472 DebugLoc dl, SelectionDAG &DAG,
1473 SmallVectorImpl<SDValue> &InVals) const {
1475 // Assign locations to each value returned by this call.
1476 SmallVector<CCValAssign, 16> RVLocs;
1477 bool Is64Bit = Subtarget->is64Bit();
1478 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1479 RVLocs, *DAG.getContext());
1480 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1482 // Copy all of the result registers out of their specified physreg.
1483 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1484 CCValAssign &VA = RVLocs[i];
1485 EVT CopyVT = VA.getValVT();
1487 // If this is x86-64, and we disabled SSE, we can't return FP values
1488 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1489 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1490 report_fatal_error("SSE register return with SSE disabled");
1495 // If this is a call to a function that returns an fp value on the floating
1496 // point stack, we must guarantee the the value is popped from the stack, so
1497 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1498 // if the return value is not used. We use the FpGET_ST0 instructions
1500 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1501 // If we prefer to use the value in xmm registers, copy it out as f80 and
1502 // use a truncate to move it from fp stack reg to xmm reg.
1503 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1504 bool isST0 = VA.getLocReg() == X86::ST0;
1506 if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1507 if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1508 if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1509 SDValue Ops[] = { Chain, InFlag };
1510 Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1512 Val = Chain.getValue(0);
1514 // Round the f80 to the right size, which also moves it to the appropriate
1516 if (CopyVT != VA.getValVT())
1517 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1518 // This truncation won't change the value.
1519 DAG.getIntPtrConstant(1));
1520 } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1521 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1522 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1523 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1524 MVT::v2i64, InFlag).getValue(1);
1525 Val = Chain.getValue(0);
1526 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1527 Val, DAG.getConstant(0, MVT::i64));
1529 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1530 MVT::i64, InFlag).getValue(1);
1531 Val = Chain.getValue(0);
1533 Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1535 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1536 CopyVT, InFlag).getValue(1);
1537 Val = Chain.getValue(0);
1539 InFlag = Chain.getValue(2);
1540 InVals.push_back(Val);
1547 //===----------------------------------------------------------------------===//
1548 // C & StdCall & Fast Calling Convention implementation
1549 //===----------------------------------------------------------------------===//
1550 // StdCall calling convention seems to be standard for many Windows' API
1551 // routines and around. It differs from C calling convention just a little:
1552 // callee should clean up the stack, not caller. Symbols should be also
1553 // decorated in some fancy way :) It doesn't support any vector arguments.
1554 // For info on fast calling convention see Fast Calling Convention (tail call)
1555 // implementation LowerX86_32FastCCCallTo.
1557 /// CallIsStructReturn - Determines whether a call uses struct return
1559 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1563 return Outs[0].Flags.isSRet();
1566 /// ArgsAreStructReturn - Determines whether a function uses struct
1567 /// return semantics.
1569 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1573 return Ins[0].Flags.isSRet();
1576 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1577 /// by "Src" to address "Dst" with size and alignment information specified by
1578 /// the specific parameter attribute. The copy will be passed as a byval
1579 /// function parameter.
1581 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1582 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1584 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1586 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1587 /*isVolatile*/false, /*AlwaysInline=*/true,
1588 MachinePointerInfo(), MachinePointerInfo());
1591 /// IsTailCallConvention - Return true if the calling convention is one that
1592 /// supports tail call optimization.
1593 static bool IsTailCallConvention(CallingConv::ID CC) {
1594 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1597 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1598 /// a tailcall target by changing its ABI.
1599 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1600 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1604 X86TargetLowering::LowerMemArgument(SDValue Chain,
1605 CallingConv::ID CallConv,
1606 const SmallVectorImpl<ISD::InputArg> &Ins,
1607 DebugLoc dl, SelectionDAG &DAG,
1608 const CCValAssign &VA,
1609 MachineFrameInfo *MFI,
1611 // Create the nodes corresponding to a load from this parameter slot.
1612 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1613 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1614 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1617 // If value is passed by pointer we have address passed instead of the value
1619 if (VA.getLocInfo() == CCValAssign::Indirect)
1620 ValVT = VA.getLocVT();
1622 ValVT = VA.getValVT();
1624 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1625 // changed with more analysis.
1626 // In case of tail call optimization mark all arguments mutable. Since they
1627 // could be overwritten by lowering of arguments in case of a tail call.
1628 if (Flags.isByVal()) {
1629 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1630 VA.getLocMemOffset(), isImmutable);
1631 return DAG.getFrameIndex(FI, getPointerTy());
1633 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1634 VA.getLocMemOffset(), isImmutable);
1635 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1636 return DAG.getLoad(ValVT, dl, Chain, FIN,
1637 MachinePointerInfo::getFixedStack(FI),
1643 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1644 CallingConv::ID CallConv,
1646 const SmallVectorImpl<ISD::InputArg> &Ins,
1649 SmallVectorImpl<SDValue> &InVals)
1651 MachineFunction &MF = DAG.getMachineFunction();
1652 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1654 const Function* Fn = MF.getFunction();
1655 if (Fn->hasExternalLinkage() &&
1656 Subtarget->isTargetCygMing() &&
1657 Fn->getName() == "main")
1658 FuncInfo->setForceFramePointer(true);
1660 MachineFrameInfo *MFI = MF.getFrameInfo();
1661 bool Is64Bit = Subtarget->is64Bit();
1662 bool IsWin64 = Subtarget->isTargetWin64();
1664 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1665 "Var args not supported with calling convention fastcc or ghc");
1667 // Assign locations to all of the incoming arguments.
1668 SmallVector<CCValAssign, 16> ArgLocs;
1669 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1670 ArgLocs, *DAG.getContext());
1672 // Allocate shadow area for Win64
1674 CCInfo.AllocateStack(32, 8);
1677 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1679 unsigned LastVal = ~0U;
1681 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1682 CCValAssign &VA = ArgLocs[i];
1683 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1685 assert(VA.getValNo() != LastVal &&
1686 "Don't support value assigned to multiple locs yet");
1687 LastVal = VA.getValNo();
1689 if (VA.isRegLoc()) {
1690 EVT RegVT = VA.getLocVT();
1691 TargetRegisterClass *RC = NULL;
1692 if (RegVT == MVT::i32)
1693 RC = X86::GR32RegisterClass;
1694 else if (Is64Bit && RegVT == MVT::i64)
1695 RC = X86::GR64RegisterClass;
1696 else if (RegVT == MVT::f32)
1697 RC = X86::FR32RegisterClass;
1698 else if (RegVT == MVT::f64)
1699 RC = X86::FR64RegisterClass;
1700 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1701 RC = X86::VR256RegisterClass;
1702 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1703 RC = X86::VR128RegisterClass;
1704 else if (RegVT == MVT::x86mmx)
1705 RC = X86::VR64RegisterClass;
1707 llvm_unreachable("Unknown argument type!");
1709 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1710 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1712 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1713 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1715 if (VA.getLocInfo() == CCValAssign::SExt)
1716 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1717 DAG.getValueType(VA.getValVT()));
1718 else if (VA.getLocInfo() == CCValAssign::ZExt)
1719 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1720 DAG.getValueType(VA.getValVT()));
1721 else if (VA.getLocInfo() == CCValAssign::BCvt)
1722 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1724 if (VA.isExtInLoc()) {
1725 // Handle MMX values passed in XMM regs.
1726 if (RegVT.isVector()) {
1727 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1730 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1733 assert(VA.isMemLoc());
1734 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1737 // If value is passed via pointer - do a load.
1738 if (VA.getLocInfo() == CCValAssign::Indirect)
1739 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1740 MachinePointerInfo(), false, false, 0);
1742 InVals.push_back(ArgValue);
1745 // The x86-64 ABI for returning structs by value requires that we copy
1746 // the sret argument into %rax for the return. Save the argument into
1747 // a virtual register so that we can access it from the return points.
1748 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1749 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1750 unsigned Reg = FuncInfo->getSRetReturnReg();
1752 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1753 FuncInfo->setSRetReturnReg(Reg);
1755 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1756 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1759 unsigned StackSize = CCInfo.getNextStackOffset();
1760 // Align stack specially for tail calls.
1761 if (FuncIsMadeTailCallSafe(CallConv))
1762 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1764 // If the function takes variable number of arguments, make a frame index for
1765 // the start of the first vararg value... for expansion of llvm.va_start.
1767 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1768 CallConv != CallingConv::X86_ThisCall)) {
1769 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1772 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1774 // FIXME: We should really autogenerate these arrays
1775 static const unsigned GPR64ArgRegsWin64[] = {
1776 X86::RCX, X86::RDX, X86::R8, X86::R9
1778 static const unsigned GPR64ArgRegs64Bit[] = {
1779 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1781 static const unsigned XMMArgRegs64Bit[] = {
1782 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1783 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1785 const unsigned *GPR64ArgRegs;
1786 unsigned NumXMMRegs = 0;
1789 // The XMM registers which might contain var arg parameters are shadowed
1790 // in their paired GPR. So we only need to save the GPR to their home
1792 TotalNumIntRegs = 4;
1793 GPR64ArgRegs = GPR64ArgRegsWin64;
1795 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1796 GPR64ArgRegs = GPR64ArgRegs64Bit;
1798 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1800 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1803 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1804 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1805 "SSE register cannot be used when SSE is disabled!");
1806 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1807 "SSE register cannot be used when SSE is disabled!");
1808 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1809 // Kernel mode asks for SSE to be disabled, so don't push them
1811 TotalNumXMMRegs = 0;
1814 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1815 // Get to the caller-allocated home save location. Add 8 to account
1816 // for the return address.
1817 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1818 FuncInfo->setRegSaveFrameIndex(
1819 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1820 // Fixup to set vararg frame on shadow area (4 x i64).
1822 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1824 // For X86-64, if there are vararg parameters that are passed via
1825 // registers, then we must store them to their spots on the stack so they
1826 // may be loaded by deferencing the result of va_next.
1827 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1828 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1829 FuncInfo->setRegSaveFrameIndex(
1830 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1834 // Store the integer parameter registers.
1835 SmallVector<SDValue, 8> MemOps;
1836 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1838 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1839 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1840 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1841 DAG.getIntPtrConstant(Offset));
1842 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1843 X86::GR64RegisterClass);
1844 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1846 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1847 MachinePointerInfo::getFixedStack(
1848 FuncInfo->getRegSaveFrameIndex(), Offset),
1850 MemOps.push_back(Store);
1854 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1855 // Now store the XMM (fp + vector) parameter registers.
1856 SmallVector<SDValue, 11> SaveXMMOps;
1857 SaveXMMOps.push_back(Chain);
1859 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1860 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1861 SaveXMMOps.push_back(ALVal);
1863 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1864 FuncInfo->getRegSaveFrameIndex()));
1865 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1866 FuncInfo->getVarArgsFPOffset()));
1868 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1869 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1870 X86::VR128RegisterClass);
1871 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1872 SaveXMMOps.push_back(Val);
1874 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1876 &SaveXMMOps[0], SaveXMMOps.size()));
1879 if (!MemOps.empty())
1880 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1881 &MemOps[0], MemOps.size());
1885 // Some CCs need callee pop.
1886 if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1887 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1889 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1890 // If this is an sret function, the return should pop the hidden pointer.
1891 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1892 FuncInfo->setBytesToPopOnReturn(4);
1896 // RegSaveFrameIndex is X86-64 only.
1897 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1898 if (CallConv == CallingConv::X86_FastCall ||
1899 CallConv == CallingConv::X86_ThisCall)
1900 // fastcc functions can't have varargs.
1901 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1908 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1909 SDValue StackPtr, SDValue Arg,
1910 DebugLoc dl, SelectionDAG &DAG,
1911 const CCValAssign &VA,
1912 ISD::ArgFlagsTy Flags) const {
1913 unsigned LocMemOffset = VA.getLocMemOffset();
1914 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1915 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1916 if (Flags.isByVal())
1917 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1919 return DAG.getStore(Chain, dl, Arg, PtrOff,
1920 MachinePointerInfo::getStack(LocMemOffset),
1924 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1925 /// optimization is performed and it is required.
1927 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1928 SDValue &OutRetAddr, SDValue Chain,
1929 bool IsTailCall, bool Is64Bit,
1930 int FPDiff, DebugLoc dl) const {
1931 // Adjust the Return address stack slot.
1932 EVT VT = getPointerTy();
1933 OutRetAddr = getReturnAddressFrameIndex(DAG);
1935 // Load the "old" Return address.
1936 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1938 return SDValue(OutRetAddr.getNode(), 1);
1941 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1942 /// optimization is performed and it is required (FPDiff!=0).
1944 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1945 SDValue Chain, SDValue RetAddrFrIdx,
1946 bool Is64Bit, int FPDiff, DebugLoc dl) {
1947 // Store the return address to the appropriate stack slot.
1948 if (!FPDiff) return Chain;
1949 // Calculate the new stack slot for the return address.
1950 int SlotSize = Is64Bit ? 8 : 4;
1951 int NewReturnAddrFI =
1952 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1953 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1954 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1955 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1956 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1962 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1963 CallingConv::ID CallConv, bool isVarArg,
1965 const SmallVectorImpl<ISD::OutputArg> &Outs,
1966 const SmallVectorImpl<SDValue> &OutVals,
1967 const SmallVectorImpl<ISD::InputArg> &Ins,
1968 DebugLoc dl, SelectionDAG &DAG,
1969 SmallVectorImpl<SDValue> &InVals) const {
1970 MachineFunction &MF = DAG.getMachineFunction();
1971 bool Is64Bit = Subtarget->is64Bit();
1972 bool IsWin64 = Subtarget->isTargetWin64();
1973 bool IsStructRet = CallIsStructReturn(Outs);
1974 bool IsSibcall = false;
1977 // Check if it's really possible to do a tail call.
1978 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1979 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1980 Outs, OutVals, Ins, DAG);
1982 // Sibcalls are automatically detected tailcalls which do not require
1984 if (!GuaranteedTailCallOpt && isTailCall)
1991 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1992 "Var args not supported with calling convention fastcc or ghc");
1994 // Analyze operands of the call, assigning locations to each operand.
1995 SmallVector<CCValAssign, 16> ArgLocs;
1996 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1997 ArgLocs, *DAG.getContext());
1999 // Allocate shadow area for Win64
2001 CCInfo.AllocateStack(32, 8);
2004 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2006 // Get a count of how many bytes are to be pushed on the stack.
2007 unsigned NumBytes = CCInfo.getNextStackOffset();
2009 // This is a sibcall. The memory operands are available in caller's
2010 // own caller's stack.
2012 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2013 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2016 if (isTailCall && !IsSibcall) {
2017 // Lower arguments at fp - stackoffset + fpdiff.
2018 unsigned NumBytesCallerPushed =
2019 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2020 FPDiff = NumBytesCallerPushed - NumBytes;
2022 // Set the delta of movement of the returnaddr stackslot.
2023 // But only set if delta is greater than previous delta.
2024 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2025 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2029 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2031 SDValue RetAddrFrIdx;
2032 // Load return adress for tail calls.
2033 if (isTailCall && FPDiff)
2034 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2035 Is64Bit, FPDiff, dl);
2037 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2038 SmallVector<SDValue, 8> MemOpChains;
2041 // Walk the register/memloc assignments, inserting copies/loads. In the case
2042 // of tail call optimization arguments are handle later.
2043 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2044 CCValAssign &VA = ArgLocs[i];
2045 EVT RegVT = VA.getLocVT();
2046 SDValue Arg = OutVals[i];
2047 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2048 bool isByVal = Flags.isByVal();
2050 // Promote the value if needed.
2051 switch (VA.getLocInfo()) {
2052 default: llvm_unreachable("Unknown loc info!");
2053 case CCValAssign::Full: break;
2054 case CCValAssign::SExt:
2055 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2057 case CCValAssign::ZExt:
2058 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2060 case CCValAssign::AExt:
2061 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2062 // Special case: passing MMX values in XMM registers.
2063 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2064 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2065 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2067 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2069 case CCValAssign::BCvt:
2070 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2072 case CCValAssign::Indirect: {
2073 // Store the argument.
2074 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2075 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2076 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2077 MachinePointerInfo::getFixedStack(FI),
2084 if (VA.isRegLoc()) {
2085 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2086 if (isVarArg && IsWin64) {
2087 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2088 // shadow reg if callee is a varargs function.
2089 unsigned ShadowReg = 0;
2090 switch (VA.getLocReg()) {
2091 case X86::XMM0: ShadowReg = X86::RCX; break;
2092 case X86::XMM1: ShadowReg = X86::RDX; break;
2093 case X86::XMM2: ShadowReg = X86::R8; break;
2094 case X86::XMM3: ShadowReg = X86::R9; break;
2097 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2099 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2100 assert(VA.isMemLoc());
2101 if (StackPtr.getNode() == 0)
2102 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2103 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2104 dl, DAG, VA, Flags));
2108 if (!MemOpChains.empty())
2109 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2110 &MemOpChains[0], MemOpChains.size());
2112 // Build a sequence of copy-to-reg nodes chained together with token chain
2113 // and flag operands which copy the outgoing args into registers.
2115 // Tail call byval lowering might overwrite argument registers so in case of
2116 // tail call optimization the copies to registers are lowered later.
2118 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2119 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2120 RegsToPass[i].second, InFlag);
2121 InFlag = Chain.getValue(1);
2124 if (Subtarget->isPICStyleGOT()) {
2125 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2128 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2129 DAG.getNode(X86ISD::GlobalBaseReg,
2130 DebugLoc(), getPointerTy()),
2132 InFlag = Chain.getValue(1);
2134 // If we are tail calling and generating PIC/GOT style code load the
2135 // address of the callee into ECX. The value in ecx is used as target of
2136 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2137 // for tail calls on PIC/GOT architectures. Normally we would just put the
2138 // address of GOT into ebx and then call target@PLT. But for tail calls
2139 // ebx would be restored (since ebx is callee saved) before jumping to the
2142 // Note: The actual moving to ECX is done further down.
2143 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2144 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2145 !G->getGlobal()->hasProtectedVisibility())
2146 Callee = LowerGlobalAddress(Callee, DAG);
2147 else if (isa<ExternalSymbolSDNode>(Callee))
2148 Callee = LowerExternalSymbol(Callee, DAG);
2152 if (Is64Bit && isVarArg && !IsWin64) {
2153 // From AMD64 ABI document:
2154 // For calls that may call functions that use varargs or stdargs
2155 // (prototype-less calls or calls to functions containing ellipsis (...) in
2156 // the declaration) %al is used as hidden argument to specify the number
2157 // of SSE registers used. The contents of %al do not need to match exactly
2158 // the number of registers, but must be an ubound on the number of SSE
2159 // registers used and is in the range 0 - 8 inclusive.
2161 // Count the number of XMM registers allocated.
2162 static const unsigned XMMArgRegs[] = {
2163 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2164 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2166 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2167 assert((Subtarget->hasXMM() || !NumXMMRegs)
2168 && "SSE registers cannot be used when SSE is disabled");
2170 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2171 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2172 InFlag = Chain.getValue(1);
2176 // For tail calls lower the arguments to the 'real' stack slot.
2178 // Force all the incoming stack arguments to be loaded from the stack
2179 // before any new outgoing arguments are stored to the stack, because the
2180 // outgoing stack slots may alias the incoming argument stack slots, and
2181 // the alias isn't otherwise explicit. This is slightly more conservative
2182 // than necessary, because it means that each store effectively depends
2183 // on every argument instead of just those arguments it would clobber.
2184 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2186 SmallVector<SDValue, 8> MemOpChains2;
2189 // Do not flag preceeding copytoreg stuff together with the following stuff.
2191 if (GuaranteedTailCallOpt) {
2192 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2193 CCValAssign &VA = ArgLocs[i];
2196 assert(VA.isMemLoc());
2197 SDValue Arg = OutVals[i];
2198 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2199 // Create frame index.
2200 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2201 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2202 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2203 FIN = DAG.getFrameIndex(FI, getPointerTy());
2205 if (Flags.isByVal()) {
2206 // Copy relative to framepointer.
2207 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2208 if (StackPtr.getNode() == 0)
2209 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2211 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2213 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2217 // Store relative to framepointer.
2218 MemOpChains2.push_back(
2219 DAG.getStore(ArgChain, dl, Arg, FIN,
2220 MachinePointerInfo::getFixedStack(FI),
2226 if (!MemOpChains2.empty())
2227 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2228 &MemOpChains2[0], MemOpChains2.size());
2230 // Copy arguments to their registers.
2231 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2232 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2233 RegsToPass[i].second, InFlag);
2234 InFlag = Chain.getValue(1);
2238 // Store the return address to the appropriate stack slot.
2239 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2243 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2244 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2245 // In the 64-bit large code model, we have to make all calls
2246 // through a register, since the call instruction's 32-bit
2247 // pc-relative offset may not be large enough to hold the whole
2249 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2250 // If the callee is a GlobalAddress node (quite common, every direct call
2251 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2254 // We should use extra load for direct calls to dllimported functions in
2256 const GlobalValue *GV = G->getGlobal();
2257 if (!GV->hasDLLImportLinkage()) {
2258 unsigned char OpFlags = 0;
2260 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2261 // external symbols most go through the PLT in PIC mode. If the symbol
2262 // has hidden or protected visibility, or if it is static or local, then
2263 // we don't need to use the PLT - we can directly call it.
2264 if (Subtarget->isTargetELF() &&
2265 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2266 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2267 OpFlags = X86II::MO_PLT;
2268 } else if (Subtarget->isPICStyleStubAny() &&
2269 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2270 Subtarget->getDarwinVers() < 9) {
2271 // PC-relative references to external symbols should go through $stub,
2272 // unless we're building with the leopard linker or later, which
2273 // automatically synthesizes these stubs.
2274 OpFlags = X86II::MO_DARWIN_STUB;
2277 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2278 G->getOffset(), OpFlags);
2280 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2281 unsigned char OpFlags = 0;
2283 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2284 // external symbols should go through the PLT.
2285 if (Subtarget->isTargetELF() &&
2286 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2287 OpFlags = X86II::MO_PLT;
2288 } else if (Subtarget->isPICStyleStubAny() &&
2289 Subtarget->getDarwinVers() < 9) {
2290 // PC-relative references to external symbols should go through $stub,
2291 // unless we're building with the leopard linker or later, which
2292 // automatically synthesizes these stubs.
2293 OpFlags = X86II::MO_DARWIN_STUB;
2296 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2300 // Returns a chain & a flag for retval copy to use.
2301 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2302 SmallVector<SDValue, 8> Ops;
2304 if (!IsSibcall && isTailCall) {
2305 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2306 DAG.getIntPtrConstant(0, true), InFlag);
2307 InFlag = Chain.getValue(1);
2310 Ops.push_back(Chain);
2311 Ops.push_back(Callee);
2314 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2316 // Add argument registers to the end of the list so that they are known live
2318 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2319 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2320 RegsToPass[i].second.getValueType()));
2322 // Add an implicit use GOT pointer in EBX.
2323 if (!isTailCall && Subtarget->isPICStyleGOT())
2324 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2326 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2327 if (Is64Bit && isVarArg && !IsWin64)
2328 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2330 if (InFlag.getNode())
2331 Ops.push_back(InFlag);
2335 //// If this is the first return lowered for this function, add the regs
2336 //// to the liveout set for the function.
2337 // This isn't right, although it's probably harmless on x86; liveouts
2338 // should be computed from returns not tail calls. Consider a void
2339 // function making a tail call to a function returning int.
2340 return DAG.getNode(X86ISD::TC_RETURN, dl,
2341 NodeTys, &Ops[0], Ops.size());
2344 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2345 InFlag = Chain.getValue(1);
2347 // Create the CALLSEQ_END node.
2348 unsigned NumBytesForCalleeToPush;
2349 if (Subtarget->IsCalleePop(isVarArg, CallConv))
2350 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2351 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2352 // If this is a call to a struct-return function, the callee
2353 // pops the hidden struct pointer, so we have to push it back.
2354 // This is common for Darwin/X86, Linux & Mingw32 targets.
2355 NumBytesForCalleeToPush = 4;
2357 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2359 // Returns a flag for retval copy to use.
2361 Chain = DAG.getCALLSEQ_END(Chain,
2362 DAG.getIntPtrConstant(NumBytes, true),
2363 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2366 InFlag = Chain.getValue(1);
2369 // Handle result values, copying them out of physregs into vregs that we
2371 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2372 Ins, dl, DAG, InVals);
2376 //===----------------------------------------------------------------------===//
2377 // Fast Calling Convention (tail call) implementation
2378 //===----------------------------------------------------------------------===//
2380 // Like std call, callee cleans arguments, convention except that ECX is
2381 // reserved for storing the tail called function address. Only 2 registers are
2382 // free for argument passing (inreg). Tail call optimization is performed
2384 // * tailcallopt is enabled
2385 // * caller/callee are fastcc
2386 // On X86_64 architecture with GOT-style position independent code only local
2387 // (within module) calls are supported at the moment.
2388 // To keep the stack aligned according to platform abi the function
2389 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2390 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2391 // If a tail called function callee has more arguments than the caller the
2392 // caller needs to make sure that there is room to move the RETADDR to. This is
2393 // achieved by reserving an area the size of the argument delta right after the
2394 // original REtADDR, but before the saved framepointer or the spilled registers
2395 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2407 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2408 /// for a 16 byte align requirement.
2410 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2411 SelectionDAG& DAG) const {
2412 MachineFunction &MF = DAG.getMachineFunction();
2413 const TargetMachine &TM = MF.getTarget();
2414 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2415 unsigned StackAlignment = TFI.getStackAlignment();
2416 uint64_t AlignMask = StackAlignment - 1;
2417 int64_t Offset = StackSize;
2418 uint64_t SlotSize = TD->getPointerSize();
2419 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2420 // Number smaller than 12 so just add the difference.
2421 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2423 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2424 Offset = ((~AlignMask) & Offset) + StackAlignment +
2425 (StackAlignment-SlotSize);
2430 /// MatchingStackOffset - Return true if the given stack call argument is
2431 /// already available in the same position (relatively) of the caller's
2432 /// incoming argument stack.
2434 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2435 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2436 const X86InstrInfo *TII) {
2437 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2439 if (Arg.getOpcode() == ISD::CopyFromReg) {
2440 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2441 if (!TargetRegisterInfo::isVirtualRegister(VR))
2443 MachineInstr *Def = MRI->getVRegDef(VR);
2446 if (!Flags.isByVal()) {
2447 if (!TII->isLoadFromStackSlot(Def, FI))
2450 unsigned Opcode = Def->getOpcode();
2451 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2452 Def->getOperand(1).isFI()) {
2453 FI = Def->getOperand(1).getIndex();
2454 Bytes = Flags.getByValSize();
2458 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2459 if (Flags.isByVal())
2460 // ByVal argument is passed in as a pointer but it's now being
2461 // dereferenced. e.g.
2462 // define @foo(%struct.X* %A) {
2463 // tail call @bar(%struct.X* byval %A)
2466 SDValue Ptr = Ld->getBasePtr();
2467 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2470 FI = FINode->getIndex();
2474 assert(FI != INT_MAX);
2475 if (!MFI->isFixedObjectIndex(FI))
2477 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2480 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2481 /// for tail call optimization. Targets which want to do tail call
2482 /// optimization should implement this function.
2484 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2485 CallingConv::ID CalleeCC,
2487 bool isCalleeStructRet,
2488 bool isCallerStructRet,
2489 const SmallVectorImpl<ISD::OutputArg> &Outs,
2490 const SmallVectorImpl<SDValue> &OutVals,
2491 const SmallVectorImpl<ISD::InputArg> &Ins,
2492 SelectionDAG& DAG) const {
2493 if (!IsTailCallConvention(CalleeCC) &&
2494 CalleeCC != CallingConv::C)
2497 // If -tailcallopt is specified, make fastcc functions tail-callable.
2498 const MachineFunction &MF = DAG.getMachineFunction();
2499 const Function *CallerF = DAG.getMachineFunction().getFunction();
2500 CallingConv::ID CallerCC = CallerF->getCallingConv();
2501 bool CCMatch = CallerCC == CalleeCC;
2503 if (GuaranteedTailCallOpt) {
2504 if (IsTailCallConvention(CalleeCC) && CCMatch)
2509 // Look for obvious safe cases to perform tail call optimization that do not
2510 // require ABI changes. This is what gcc calls sibcall.
2512 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2513 // emit a special epilogue.
2514 if (RegInfo->needsStackRealignment(MF))
2517 // Do not sibcall optimize vararg calls unless the call site is not passing
2519 if (isVarArg && !Outs.empty())
2522 // Also avoid sibcall optimization if either caller or callee uses struct
2523 // return semantics.
2524 if (isCalleeStructRet || isCallerStructRet)
2527 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2528 // Therefore if it's not used by the call it is not safe to optimize this into
2530 bool Unused = false;
2531 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2538 SmallVector<CCValAssign, 16> RVLocs;
2539 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2540 RVLocs, *DAG.getContext());
2541 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2542 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2543 CCValAssign &VA = RVLocs[i];
2544 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2549 // If the calling conventions do not match, then we'd better make sure the
2550 // results are returned in the same way as what the caller expects.
2552 SmallVector<CCValAssign, 16> RVLocs1;
2553 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2554 RVLocs1, *DAG.getContext());
2555 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2557 SmallVector<CCValAssign, 16> RVLocs2;
2558 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2559 RVLocs2, *DAG.getContext());
2560 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2562 if (RVLocs1.size() != RVLocs2.size())
2564 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2565 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2567 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2569 if (RVLocs1[i].isRegLoc()) {
2570 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2573 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2579 // If the callee takes no arguments then go on to check the results of the
2581 if (!Outs.empty()) {
2582 // Check if stack adjustment is needed. For now, do not do this if any
2583 // argument is passed on the stack.
2584 SmallVector<CCValAssign, 16> ArgLocs;
2585 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2586 ArgLocs, *DAG.getContext());
2588 // Allocate shadow area for Win64
2589 if (Subtarget->isTargetWin64()) {
2590 CCInfo.AllocateStack(32, 8);
2593 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2594 if (CCInfo.getNextStackOffset()) {
2595 MachineFunction &MF = DAG.getMachineFunction();
2596 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2599 // Check if the arguments are already laid out in the right way as
2600 // the caller's fixed stack objects.
2601 MachineFrameInfo *MFI = MF.getFrameInfo();
2602 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2603 const X86InstrInfo *TII =
2604 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2605 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2606 CCValAssign &VA = ArgLocs[i];
2607 SDValue Arg = OutVals[i];
2608 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2609 if (VA.getLocInfo() == CCValAssign::Indirect)
2611 if (!VA.isRegLoc()) {
2612 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2619 // If the tailcall address may be in a register, then make sure it's
2620 // possible to register allocate for it. In 32-bit, the call address can
2621 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2622 // callee-saved registers are restored. These happen to be the same
2623 // registers used to pass 'inreg' arguments so watch out for those.
2624 if (!Subtarget->is64Bit() &&
2625 !isa<GlobalAddressSDNode>(Callee) &&
2626 !isa<ExternalSymbolSDNode>(Callee)) {
2627 unsigned NumInRegs = 0;
2628 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2629 CCValAssign &VA = ArgLocs[i];
2632 unsigned Reg = VA.getLocReg();
2635 case X86::EAX: case X86::EDX: case X86::ECX:
2636 if (++NumInRegs == 3)
2644 // An stdcall caller is expected to clean up its arguments; the callee
2645 // isn't going to do that.
2646 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2653 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2654 return X86::createFastISel(funcInfo);
2658 //===----------------------------------------------------------------------===//
2659 // Other Lowering Hooks
2660 //===----------------------------------------------------------------------===//
2662 static bool MayFoldLoad(SDValue Op) {
2663 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2666 static bool MayFoldIntoStore(SDValue Op) {
2667 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2670 static bool isTargetShuffle(unsigned Opcode) {
2672 default: return false;
2673 case X86ISD::PSHUFD:
2674 case X86ISD::PSHUFHW:
2675 case X86ISD::PSHUFLW:
2676 case X86ISD::SHUFPD:
2677 case X86ISD::PALIGN:
2678 case X86ISD::SHUFPS:
2679 case X86ISD::MOVLHPS:
2680 case X86ISD::MOVLHPD:
2681 case X86ISD::MOVHLPS:
2682 case X86ISD::MOVLPS:
2683 case X86ISD::MOVLPD:
2684 case X86ISD::MOVSHDUP:
2685 case X86ISD::MOVSLDUP:
2686 case X86ISD::MOVDDUP:
2689 case X86ISD::UNPCKLPS:
2690 case X86ISD::UNPCKLPD:
2691 case X86ISD::VUNPCKLPS:
2692 case X86ISD::VUNPCKLPD:
2693 case X86ISD::VUNPCKLPSY:
2694 case X86ISD::VUNPCKLPDY:
2695 case X86ISD::PUNPCKLWD:
2696 case X86ISD::PUNPCKLBW:
2697 case X86ISD::PUNPCKLDQ:
2698 case X86ISD::PUNPCKLQDQ:
2699 case X86ISD::UNPCKHPS:
2700 case X86ISD::UNPCKHPD:
2701 case X86ISD::PUNPCKHWD:
2702 case X86ISD::PUNPCKHBW:
2703 case X86ISD::PUNPCKHDQ:
2704 case X86ISD::PUNPCKHQDQ:
2710 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2711 SDValue V1, SelectionDAG &DAG) {
2713 default: llvm_unreachable("Unknown x86 shuffle node");
2714 case X86ISD::MOVSHDUP:
2715 case X86ISD::MOVSLDUP:
2716 case X86ISD::MOVDDUP:
2717 return DAG.getNode(Opc, dl, VT, V1);
2723 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2724 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2726 default: llvm_unreachable("Unknown x86 shuffle node");
2727 case X86ISD::PSHUFD:
2728 case X86ISD::PSHUFHW:
2729 case X86ISD::PSHUFLW:
2730 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2736 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2737 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2739 default: llvm_unreachable("Unknown x86 shuffle node");
2740 case X86ISD::PALIGN:
2741 case X86ISD::SHUFPD:
2742 case X86ISD::SHUFPS:
2743 return DAG.getNode(Opc, dl, VT, V1, V2,
2744 DAG.getConstant(TargetMask, MVT::i8));
2749 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2750 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2752 default: llvm_unreachable("Unknown x86 shuffle node");
2753 case X86ISD::MOVLHPS:
2754 case X86ISD::MOVLHPD:
2755 case X86ISD::MOVHLPS:
2756 case X86ISD::MOVLPS:
2757 case X86ISD::MOVLPD:
2760 case X86ISD::UNPCKLPS:
2761 case X86ISD::UNPCKLPD:
2762 case X86ISD::VUNPCKLPS:
2763 case X86ISD::VUNPCKLPD:
2764 case X86ISD::VUNPCKLPSY:
2765 case X86ISD::VUNPCKLPDY:
2766 case X86ISD::PUNPCKLWD:
2767 case X86ISD::PUNPCKLBW:
2768 case X86ISD::PUNPCKLDQ:
2769 case X86ISD::PUNPCKLQDQ:
2770 case X86ISD::UNPCKHPS:
2771 case X86ISD::UNPCKHPD:
2772 case X86ISD::PUNPCKHWD:
2773 case X86ISD::PUNPCKHBW:
2774 case X86ISD::PUNPCKHDQ:
2775 case X86ISD::PUNPCKHQDQ:
2776 return DAG.getNode(Opc, dl, VT, V1, V2);
2781 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2782 MachineFunction &MF = DAG.getMachineFunction();
2783 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2784 int ReturnAddrIndex = FuncInfo->getRAIndex();
2786 if (ReturnAddrIndex == 0) {
2787 // Set up a frame object for the return address.
2788 uint64_t SlotSize = TD->getPointerSize();
2789 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2791 FuncInfo->setRAIndex(ReturnAddrIndex);
2794 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2798 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2799 bool hasSymbolicDisplacement) {
2800 // Offset should fit into 32 bit immediate field.
2801 if (!isInt<32>(Offset))
2804 // If we don't have a symbolic displacement - we don't have any extra
2806 if (!hasSymbolicDisplacement)
2809 // FIXME: Some tweaks might be needed for medium code model.
2810 if (M != CodeModel::Small && M != CodeModel::Kernel)
2813 // For small code model we assume that latest object is 16MB before end of 31
2814 // bits boundary. We may also accept pretty large negative constants knowing
2815 // that all objects are in the positive half of address space.
2816 if (M == CodeModel::Small && Offset < 16*1024*1024)
2819 // For kernel code model we know that all object resist in the negative half
2820 // of 32bits address space. We may not accept negative offsets, since they may
2821 // be just off and we may accept pretty large positive ones.
2822 if (M == CodeModel::Kernel && Offset > 0)
2828 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2829 /// specific condition code, returning the condition code and the LHS/RHS of the
2830 /// comparison to make.
2831 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2832 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2834 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2835 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2836 // X > -1 -> X == 0, jump !sign.
2837 RHS = DAG.getConstant(0, RHS.getValueType());
2838 return X86::COND_NS;
2839 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2840 // X < 0 -> X == 0, jump on sign.
2842 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2844 RHS = DAG.getConstant(0, RHS.getValueType());
2845 return X86::COND_LE;
2849 switch (SetCCOpcode) {
2850 default: llvm_unreachable("Invalid integer condition!");
2851 case ISD::SETEQ: return X86::COND_E;
2852 case ISD::SETGT: return X86::COND_G;
2853 case ISD::SETGE: return X86::COND_GE;
2854 case ISD::SETLT: return X86::COND_L;
2855 case ISD::SETLE: return X86::COND_LE;
2856 case ISD::SETNE: return X86::COND_NE;
2857 case ISD::SETULT: return X86::COND_B;
2858 case ISD::SETUGT: return X86::COND_A;
2859 case ISD::SETULE: return X86::COND_BE;
2860 case ISD::SETUGE: return X86::COND_AE;
2864 // First determine if it is required or is profitable to flip the operands.
2866 // If LHS is a foldable load, but RHS is not, flip the condition.
2867 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2868 !ISD::isNON_EXTLoad(RHS.getNode())) {
2869 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2870 std::swap(LHS, RHS);
2873 switch (SetCCOpcode) {
2879 std::swap(LHS, RHS);
2883 // On a floating point condition, the flags are set as follows:
2885 // 0 | 0 | 0 | X > Y
2886 // 0 | 0 | 1 | X < Y
2887 // 1 | 0 | 0 | X == Y
2888 // 1 | 1 | 1 | unordered
2889 switch (SetCCOpcode) {
2890 default: llvm_unreachable("Condcode should be pre-legalized away");
2892 case ISD::SETEQ: return X86::COND_E;
2893 case ISD::SETOLT: // flipped
2895 case ISD::SETGT: return X86::COND_A;
2896 case ISD::SETOLE: // flipped
2898 case ISD::SETGE: return X86::COND_AE;
2899 case ISD::SETUGT: // flipped
2901 case ISD::SETLT: return X86::COND_B;
2902 case ISD::SETUGE: // flipped
2904 case ISD::SETLE: return X86::COND_BE;
2906 case ISD::SETNE: return X86::COND_NE;
2907 case ISD::SETUO: return X86::COND_P;
2908 case ISD::SETO: return X86::COND_NP;
2910 case ISD::SETUNE: return X86::COND_INVALID;
2914 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2915 /// code. Current x86 isa includes the following FP cmov instructions:
2916 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2917 static bool hasFPCMov(unsigned X86CC) {
2933 /// isFPImmLegal - Returns true if the target can instruction select the
2934 /// specified FP immediate natively. If false, the legalizer will
2935 /// materialize the FP immediate as a load from a constant pool.
2936 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2937 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2938 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2944 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2945 /// the specified range (L, H].
2946 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2947 return (Val < 0) || (Val >= Low && Val < Hi);
2950 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2951 /// specified value.
2952 static bool isUndefOrEqual(int Val, int CmpVal) {
2953 if (Val < 0 || Val == CmpVal)
2958 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2959 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2960 /// the second operand.
2961 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2962 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2963 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2964 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2965 return (Mask[0] < 2 && Mask[1] < 2);
2969 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2970 SmallVector<int, 8> M;
2972 return ::isPSHUFDMask(M, N->getValueType(0));
2975 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2976 /// is suitable for input to PSHUFHW.
2977 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2978 if (VT != MVT::v8i16)
2981 // Lower quadword copied in order or undef.
2982 for (int i = 0; i != 4; ++i)
2983 if (Mask[i] >= 0 && Mask[i] != i)
2986 // Upper quadword shuffled.
2987 for (int i = 4; i != 8; ++i)
2988 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2994 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2995 SmallVector<int, 8> M;
2997 return ::isPSHUFHWMask(M, N->getValueType(0));
3000 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3001 /// is suitable for input to PSHUFLW.
3002 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3003 if (VT != MVT::v8i16)
3006 // Upper quadword copied in order.
3007 for (int i = 4; i != 8; ++i)
3008 if (Mask[i] >= 0 && Mask[i] != i)
3011 // Lower quadword shuffled.
3012 for (int i = 0; i != 4; ++i)
3019 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3020 SmallVector<int, 8> M;
3022 return ::isPSHUFLWMask(M, N->getValueType(0));
3025 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3026 /// is suitable for input to PALIGNR.
3027 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3029 int i, e = VT.getVectorNumElements();
3031 // Do not handle v2i64 / v2f64 shuffles with palignr.
3032 if (e < 4 || !hasSSSE3)
3035 for (i = 0; i != e; ++i)
3039 // All undef, not a palignr.
3043 // Determine if it's ok to perform a palignr with only the LHS, since we
3044 // don't have access to the actual shuffle elements to see if RHS is undef.
3045 bool Unary = Mask[i] < (int)e;
3046 bool NeedsUnary = false;
3048 int s = Mask[i] - i;
3050 // Check the rest of the elements to see if they are consecutive.
3051 for (++i; i != e; ++i) {
3056 Unary = Unary && (m < (int)e);
3057 NeedsUnary = NeedsUnary || (m < s);
3059 if (NeedsUnary && !Unary)
3061 if (Unary && m != ((s+i) & (e-1)))
3063 if (!Unary && m != (s+i))
3069 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3070 SmallVector<int, 8> M;
3072 return ::isPALIGNRMask(M, N->getValueType(0), true);
3075 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3076 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3077 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3078 int NumElems = VT.getVectorNumElements();
3079 if (NumElems != 2 && NumElems != 4)
3082 int Half = NumElems / 2;
3083 for (int i = 0; i < Half; ++i)
3084 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3086 for (int i = Half; i < NumElems; ++i)
3087 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3093 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3094 SmallVector<int, 8> M;
3096 return ::isSHUFPMask(M, N->getValueType(0));
3099 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3100 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3101 /// half elements to come from vector 1 (which would equal the dest.) and
3102 /// the upper half to come from vector 2.
3103 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3104 int NumElems = VT.getVectorNumElements();
3106 if (NumElems != 2 && NumElems != 4)
3109 int Half = NumElems / 2;
3110 for (int i = 0; i < Half; ++i)
3111 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3113 for (int i = Half; i < NumElems; ++i)
3114 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3119 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3120 SmallVector<int, 8> M;
3122 return isCommutedSHUFPMask(M, N->getValueType(0));
3125 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3126 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3127 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3128 if (N->getValueType(0).getVectorNumElements() != 4)
3131 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3132 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3133 isUndefOrEqual(N->getMaskElt(1), 7) &&
3134 isUndefOrEqual(N->getMaskElt(2), 2) &&
3135 isUndefOrEqual(N->getMaskElt(3), 3);
3138 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3139 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3141 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3142 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3147 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3148 isUndefOrEqual(N->getMaskElt(1), 3) &&
3149 isUndefOrEqual(N->getMaskElt(2), 2) &&
3150 isUndefOrEqual(N->getMaskElt(3), 3);
3153 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3154 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3155 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3156 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3158 if (NumElems != 2 && NumElems != 4)
3161 for (unsigned i = 0; i < NumElems/2; ++i)
3162 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3165 for (unsigned i = NumElems/2; i < NumElems; ++i)
3166 if (!isUndefOrEqual(N->getMaskElt(i), i))
3172 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3173 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3174 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3175 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3177 if ((NumElems != 2 && NumElems != 4)
3178 || N->getValueType(0).getSizeInBits() > 128)
3181 for (unsigned i = 0; i < NumElems/2; ++i)
3182 if (!isUndefOrEqual(N->getMaskElt(i), i))
3185 for (unsigned i = 0; i < NumElems/2; ++i)
3186 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3192 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3193 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3194 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3195 bool V2IsSplat = false) {
3196 int NumElts = VT.getVectorNumElements();
3197 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3200 // Handle vector lengths > 128 bits. Define a "section" as a set of
3201 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3203 unsigned NumSections = VT.getSizeInBits() / 128;
3204 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3205 unsigned NumSectionElts = NumElts / NumSections;
3208 unsigned End = NumSectionElts;
3209 for (unsigned s = 0; s < NumSections; ++s) {
3210 for (unsigned i = Start, j = s * NumSectionElts;
3214 int BitI1 = Mask[i+1];
3215 if (!isUndefOrEqual(BitI, j))
3218 if (!isUndefOrEqual(BitI1, NumElts))
3221 if (!isUndefOrEqual(BitI1, j + NumElts))
3225 // Process the next 128 bits.
3226 Start += NumSectionElts;
3227 End += NumSectionElts;
3233 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3234 SmallVector<int, 8> M;
3236 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3239 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3240 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3241 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3242 bool V2IsSplat = false) {
3243 int NumElts = VT.getVectorNumElements();
3244 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3247 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3249 int BitI1 = Mask[i+1];
3250 if (!isUndefOrEqual(BitI, j + NumElts/2))
3253 if (isUndefOrEqual(BitI1, NumElts))
3256 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3263 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3264 SmallVector<int, 8> M;
3266 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3269 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3270 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3272 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3273 int NumElems = VT.getVectorNumElements();
3274 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3277 // Handle vector lengths > 128 bits. Define a "section" as a set of
3278 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3280 unsigned NumSections = VT.getSizeInBits() / 128;
3281 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3282 unsigned NumSectionElts = NumElems / NumSections;
3284 for (unsigned s = 0; s < NumSections; ++s) {
3285 for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3286 i != NumSectionElts * (s + 1);
3289 int BitI1 = Mask[i+1];
3291 if (!isUndefOrEqual(BitI, j))
3293 if (!isUndefOrEqual(BitI1, j))
3301 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3302 SmallVector<int, 8> M;
3304 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3307 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3308 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3310 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3311 int NumElems = VT.getVectorNumElements();
3312 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3315 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3317 int BitI1 = Mask[i+1];
3318 if (!isUndefOrEqual(BitI, j))
3320 if (!isUndefOrEqual(BitI1, j))
3326 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3327 SmallVector<int, 8> M;
3329 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3332 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3333 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3334 /// MOVSD, and MOVD, i.e. setting the lowest element.
3335 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3336 if (VT.getVectorElementType().getSizeInBits() < 32)
3339 int NumElts = VT.getVectorNumElements();
3341 if (!isUndefOrEqual(Mask[0], NumElts))
3344 for (int i = 1; i < NumElts; ++i)
3345 if (!isUndefOrEqual(Mask[i], i))
3351 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3352 SmallVector<int, 8> M;
3354 return ::isMOVLMask(M, N->getValueType(0));
3357 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3358 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3359 /// element of vector 2 and the other elements to come from vector 1 in order.
3360 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3361 bool V2IsSplat = false, bool V2IsUndef = false) {
3362 int NumOps = VT.getVectorNumElements();
3363 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3366 if (!isUndefOrEqual(Mask[0], 0))
3369 for (int i = 1; i < NumOps; ++i)
3370 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3371 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3372 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3378 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3379 bool V2IsUndef = false) {
3380 SmallVector<int, 8> M;
3382 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3385 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3386 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3387 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3388 if (N->getValueType(0).getVectorNumElements() != 4)
3391 // Expect 1, 1, 3, 3
3392 for (unsigned i = 0; i < 2; ++i) {
3393 int Elt = N->getMaskElt(i);
3394 if (Elt >= 0 && Elt != 1)
3399 for (unsigned i = 2; i < 4; ++i) {
3400 int Elt = N->getMaskElt(i);
3401 if (Elt >= 0 && Elt != 3)
3406 // Don't use movshdup if it can be done with a shufps.
3407 // FIXME: verify that matching u, u, 3, 3 is what we want.
3411 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3412 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3413 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3414 if (N->getValueType(0).getVectorNumElements() != 4)
3417 // Expect 0, 0, 2, 2
3418 for (unsigned i = 0; i < 2; ++i)
3419 if (N->getMaskElt(i) > 0)
3423 for (unsigned i = 2; i < 4; ++i) {
3424 int Elt = N->getMaskElt(i);
3425 if (Elt >= 0 && Elt != 2)
3430 // Don't use movsldup if it can be done with a shufps.
3434 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3435 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3436 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3437 int e = N->getValueType(0).getVectorNumElements() / 2;
3439 for (int i = 0; i < e; ++i)
3440 if (!isUndefOrEqual(N->getMaskElt(i), i))
3442 for (int i = 0; i < e; ++i)
3443 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3448 /// isVEXTRACTF128Index - Return true if the specified
3449 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3450 /// suitable for input to VEXTRACTF128.
3451 bool X86::isVEXTRACTF128Index(SDNode *N) {
3452 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3455 // The index should be aligned on a 128-bit boundary.
3457 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3459 unsigned VL = N->getValueType(0).getVectorNumElements();
3460 unsigned VBits = N->getValueType(0).getSizeInBits();
3461 unsigned ElSize = VBits / VL;
3462 bool Result = (Index * ElSize) % 128 == 0;
3467 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3468 /// operand specifies a subvector insert that is suitable for input to
3470 bool X86::isVINSERTF128Index(SDNode *N) {
3471 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3474 // The index should be aligned on a 128-bit boundary.
3476 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3478 unsigned VL = N->getValueType(0).getVectorNumElements();
3479 unsigned VBits = N->getValueType(0).getSizeInBits();
3480 unsigned ElSize = VBits / VL;
3481 bool Result = (Index * ElSize) % 128 == 0;
3486 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3487 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3488 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3489 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3490 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3492 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3494 for (int i = 0; i < NumOperands; ++i) {
3495 int Val = SVOp->getMaskElt(NumOperands-i-1);
3496 if (Val < 0) Val = 0;
3497 if (Val >= NumOperands) Val -= NumOperands;
3499 if (i != NumOperands - 1)
3505 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3506 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3507 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3508 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3510 // 8 nodes, but we only care about the last 4.
3511 for (unsigned i = 7; i >= 4; --i) {
3512 int Val = SVOp->getMaskElt(i);
3521 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3522 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3523 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3524 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3526 // 8 nodes, but we only care about the first 4.
3527 for (int i = 3; i >= 0; --i) {
3528 int Val = SVOp->getMaskElt(i);
3537 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3538 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3539 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3540 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3541 EVT VVT = N->getValueType(0);
3542 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3546 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3547 Val = SVOp->getMaskElt(i);
3551 return (Val - i) * EltSize;
3554 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3555 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3557 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3558 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3559 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3562 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3564 EVT VecVT = N->getOperand(0).getValueType();
3565 EVT ElVT = VecVT.getVectorElementType();
3567 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3569 return Index / NumElemsPerChunk;
3572 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3573 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3575 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3576 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3577 llvm_unreachable("Illegal insert subvector for VINSERTF128");
3580 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3582 EVT VecVT = N->getValueType(0);
3583 EVT ElVT = VecVT.getVectorElementType();
3585 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3587 return Index / NumElemsPerChunk;
3590 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3592 bool X86::isZeroNode(SDValue Elt) {
3593 return ((isa<ConstantSDNode>(Elt) &&
3594 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3595 (isa<ConstantFPSDNode>(Elt) &&
3596 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3599 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3600 /// their permute mask.
3601 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3602 SelectionDAG &DAG) {
3603 EVT VT = SVOp->getValueType(0);
3604 unsigned NumElems = VT.getVectorNumElements();
3605 SmallVector<int, 8> MaskVec;
3607 for (unsigned i = 0; i != NumElems; ++i) {
3608 int idx = SVOp->getMaskElt(i);
3610 MaskVec.push_back(idx);
3611 else if (idx < (int)NumElems)
3612 MaskVec.push_back(idx + NumElems);
3614 MaskVec.push_back(idx - NumElems);
3616 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3617 SVOp->getOperand(0), &MaskVec[0]);
3620 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3621 /// the two vector operands have swapped position.
3622 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3623 unsigned NumElems = VT.getVectorNumElements();
3624 for (unsigned i = 0; i != NumElems; ++i) {
3628 else if (idx < (int)NumElems)
3629 Mask[i] = idx + NumElems;
3631 Mask[i] = idx - NumElems;
3635 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3636 /// match movhlps. The lower half elements should come from upper half of
3637 /// V1 (and in order), and the upper half elements should come from the upper
3638 /// half of V2 (and in order).
3639 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3640 if (Op->getValueType(0).getVectorNumElements() != 4)
3642 for (unsigned i = 0, e = 2; i != e; ++i)
3643 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3645 for (unsigned i = 2; i != 4; ++i)
3646 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3651 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3652 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3654 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3655 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3657 N = N->getOperand(0).getNode();
3658 if (!ISD::isNON_EXTLoad(N))
3661 *LD = cast<LoadSDNode>(N);
3665 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3666 /// match movlp{s|d}. The lower half elements should come from lower half of
3667 /// V1 (and in order), and the upper half elements should come from the upper
3668 /// half of V2 (and in order). And since V1 will become the source of the
3669 /// MOVLP, it must be either a vector load or a scalar load to vector.
3670 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3671 ShuffleVectorSDNode *Op) {
3672 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3674 // Is V2 is a vector load, don't do this transformation. We will try to use
3675 // load folding shufps op.
3676 if (ISD::isNON_EXTLoad(V2))
3679 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3681 if (NumElems != 2 && NumElems != 4)
3683 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3684 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3686 for (unsigned i = NumElems/2; i != NumElems; ++i)
3687 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3692 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3694 static bool isSplatVector(SDNode *N) {
3695 if (N->getOpcode() != ISD::BUILD_VECTOR)
3698 SDValue SplatValue = N->getOperand(0);
3699 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3700 if (N->getOperand(i) != SplatValue)
3705 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3706 /// to an zero vector.
3707 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3708 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3709 SDValue V1 = N->getOperand(0);
3710 SDValue V2 = N->getOperand(1);
3711 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3712 for (unsigned i = 0; i != NumElems; ++i) {
3713 int Idx = N->getMaskElt(i);
3714 if (Idx >= (int)NumElems) {
3715 unsigned Opc = V2.getOpcode();
3716 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3718 if (Opc != ISD::BUILD_VECTOR ||
3719 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3721 } else if (Idx >= 0) {
3722 unsigned Opc = V1.getOpcode();
3723 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3725 if (Opc != ISD::BUILD_VECTOR ||
3726 !X86::isZeroNode(V1.getOperand(Idx)))
3733 /// getZeroVector - Returns a vector of specified type with all zero elements.
3735 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3737 assert(VT.isVector() && "Expected a vector type");
3739 // Always build SSE zero vectors as <4 x i32> bitcasted
3740 // to their dest type. This ensures they get CSE'd.
3742 if (VT.getSizeInBits() == 128) { // SSE
3743 if (HasSSE2) { // SSE2
3744 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3745 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3747 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3748 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3750 } else if (VT.getSizeInBits() == 256) { // AVX
3751 // 256-bit logic and arithmetic instructions in AVX are
3752 // all floating-point, no support for integer ops. Default
3753 // to emitting fp zeroed vectors then.
3754 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3755 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3756 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3758 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3761 /// getOnesVector - Returns a vector of specified type with all bits set.
3763 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3764 assert(VT.isVector() && "Expected a vector type");
3766 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3767 // type. This ensures they get CSE'd.
3768 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3770 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3771 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3775 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3776 /// that point to V2 points to its first element.
3777 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3778 EVT VT = SVOp->getValueType(0);
3779 unsigned NumElems = VT.getVectorNumElements();
3781 bool Changed = false;
3782 SmallVector<int, 8> MaskVec;
3783 SVOp->getMask(MaskVec);
3785 for (unsigned i = 0; i != NumElems; ++i) {
3786 if (MaskVec[i] > (int)NumElems) {
3787 MaskVec[i] = NumElems;
3792 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3793 SVOp->getOperand(1), &MaskVec[0]);
3794 return SDValue(SVOp, 0);
3797 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3798 /// operation of specified width.
3799 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3801 unsigned NumElems = VT.getVectorNumElements();
3802 SmallVector<int, 8> Mask;
3803 Mask.push_back(NumElems);
3804 for (unsigned i = 1; i != NumElems; ++i)
3806 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3809 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3810 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3812 unsigned NumElems = VT.getVectorNumElements();
3813 SmallVector<int, 8> Mask;
3814 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3816 Mask.push_back(i + NumElems);
3818 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3821 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3822 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3824 unsigned NumElems = VT.getVectorNumElements();
3825 unsigned Half = NumElems/2;
3826 SmallVector<int, 8> Mask;
3827 for (unsigned i = 0; i != Half; ++i) {
3828 Mask.push_back(i + Half);
3829 Mask.push_back(i + NumElems + Half);
3831 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3834 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3835 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3836 EVT PVT = MVT::v4f32;
3837 EVT VT = SV->getValueType(0);
3838 DebugLoc dl = SV->getDebugLoc();
3839 SDValue V1 = SV->getOperand(0);
3840 int NumElems = VT.getVectorNumElements();
3841 int EltNo = SV->getSplatIndex();
3843 // unpack elements to the correct location
3844 while (NumElems > 4) {
3845 if (EltNo < NumElems/2) {
3846 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3848 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3849 EltNo -= NumElems/2;
3854 // Perform the splat.
3855 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3856 V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3857 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3858 return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3861 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3862 /// vector of zero or undef vector. This produces a shuffle where the low
3863 /// element of V2 is swizzled into the zero/undef vector, landing at element
3864 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3865 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3866 bool isZero, bool HasSSE2,
3867 SelectionDAG &DAG) {
3868 EVT VT = V2.getValueType();
3870 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3871 unsigned NumElems = VT.getVectorNumElements();
3872 SmallVector<int, 16> MaskVec;
3873 for (unsigned i = 0; i != NumElems; ++i)
3874 // If this is the insertion idx, put the low elt of V2 here.
3875 MaskVec.push_back(i == Idx ? NumElems : i);
3876 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3879 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3880 /// element of the result of the vector shuffle.
3881 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3884 return SDValue(); // Limit search depth.
3886 SDValue V = SDValue(N, 0);
3887 EVT VT = V.getValueType();
3888 unsigned Opcode = V.getOpcode();
3890 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3891 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3892 Index = SV->getMaskElt(Index);
3895 return DAG.getUNDEF(VT.getVectorElementType());
3897 int NumElems = VT.getVectorNumElements();
3898 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3899 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3902 // Recurse into target specific vector shuffles to find scalars.
3903 if (isTargetShuffle(Opcode)) {
3904 int NumElems = VT.getVectorNumElements();
3905 SmallVector<unsigned, 16> ShuffleMask;
3909 case X86ISD::SHUFPS:
3910 case X86ISD::SHUFPD:
3911 ImmN = N->getOperand(N->getNumOperands()-1);
3912 DecodeSHUFPSMask(NumElems,
3913 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3916 case X86ISD::PUNPCKHBW:
3917 case X86ISD::PUNPCKHWD:
3918 case X86ISD::PUNPCKHDQ:
3919 case X86ISD::PUNPCKHQDQ:
3920 DecodePUNPCKHMask(NumElems, ShuffleMask);
3922 case X86ISD::UNPCKHPS:
3923 case X86ISD::UNPCKHPD:
3924 DecodeUNPCKHPMask(NumElems, ShuffleMask);
3926 case X86ISD::PUNPCKLBW:
3927 case X86ISD::PUNPCKLWD:
3928 case X86ISD::PUNPCKLDQ:
3929 case X86ISD::PUNPCKLQDQ:
3930 DecodePUNPCKLMask(VT, ShuffleMask);
3932 case X86ISD::UNPCKLPS:
3933 case X86ISD::UNPCKLPD:
3934 case X86ISD::VUNPCKLPS:
3935 case X86ISD::VUNPCKLPD:
3936 case X86ISD::VUNPCKLPSY:
3937 case X86ISD::VUNPCKLPDY:
3938 DecodeUNPCKLPMask(VT, ShuffleMask);
3940 case X86ISD::MOVHLPS:
3941 DecodeMOVHLPSMask(NumElems, ShuffleMask);
3943 case X86ISD::MOVLHPS:
3944 DecodeMOVLHPSMask(NumElems, ShuffleMask);
3946 case X86ISD::PSHUFD:
3947 ImmN = N->getOperand(N->getNumOperands()-1);
3948 DecodePSHUFMask(NumElems,
3949 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3952 case X86ISD::PSHUFHW:
3953 ImmN = N->getOperand(N->getNumOperands()-1);
3954 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3957 case X86ISD::PSHUFLW:
3958 ImmN = N->getOperand(N->getNumOperands()-1);
3959 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3963 case X86ISD::MOVSD: {
3964 // The index 0 always comes from the first element of the second source,
3965 // this is why MOVSS and MOVSD are used in the first place. The other
3966 // elements come from the other positions of the first source vector.
3967 unsigned OpNum = (Index == 0) ? 1 : 0;
3968 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3972 assert("not implemented for target shuffle node");
3976 Index = ShuffleMask[Index];
3978 return DAG.getUNDEF(VT.getVectorElementType());
3980 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3981 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3985 // Actual nodes that may contain scalar elements
3986 if (Opcode == ISD::BITCAST) {
3987 V = V.getOperand(0);
3988 EVT SrcVT = V.getValueType();
3989 unsigned NumElems = VT.getVectorNumElements();
3991 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3995 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3996 return (Index == 0) ? V.getOperand(0)
3997 : DAG.getUNDEF(VT.getVectorElementType());
3999 if (V.getOpcode() == ISD::BUILD_VECTOR)
4000 return V.getOperand(Index);
4005 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4006 /// shuffle operation which come from a consecutively from a zero. The
4007 /// search can start in two diferent directions, from left or right.
4009 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4010 bool ZerosFromLeft, SelectionDAG &DAG) {
4013 while (i < NumElems) {
4014 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4015 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4016 if (!(Elt.getNode() &&
4017 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4025 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4026 /// MaskE correspond consecutively to elements from one of the vector operands,
4027 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4029 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4030 int OpIdx, int NumElems, unsigned &OpNum) {
4031 bool SeenV1 = false;
4032 bool SeenV2 = false;
4034 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4035 int Idx = SVOp->getMaskElt(i);
4036 // Ignore undef indicies
4045 // Only accept consecutive elements from the same vector
4046 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4050 OpNum = SeenV1 ? 0 : 1;
4054 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4055 /// logical left shift of a vector.
4056 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4057 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4058 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4059 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4060 false /* check zeros from right */, DAG);
4066 // Considering the elements in the mask that are not consecutive zeros,
4067 // check if they consecutively come from only one of the source vectors.
4069 // V1 = {X, A, B, C} 0
4071 // vector_shuffle V1, V2 <1, 2, 3, X>
4073 if (!isShuffleMaskConsecutive(SVOp,
4074 0, // Mask Start Index
4075 NumElems-NumZeros-1, // Mask End Index
4076 NumZeros, // Where to start looking in the src vector
4077 NumElems, // Number of elements in vector
4078 OpSrc)) // Which source operand ?
4083 ShVal = SVOp->getOperand(OpSrc);
4087 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4088 /// logical left shift of a vector.
4089 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4090 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4091 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4092 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4093 true /* check zeros from left */, DAG);
4099 // Considering the elements in the mask that are not consecutive zeros,
4100 // check if they consecutively come from only one of the source vectors.
4102 // 0 { A, B, X, X } = V2
4104 // vector_shuffle V1, V2 <X, X, 4, 5>
4106 if (!isShuffleMaskConsecutive(SVOp,
4107 NumZeros, // Mask Start Index
4108 NumElems-1, // Mask End Index
4109 0, // Where to start looking in the src vector
4110 NumElems, // Number of elements in vector
4111 OpSrc)) // Which source operand ?
4116 ShVal = SVOp->getOperand(OpSrc);
4120 /// isVectorShift - Returns true if the shuffle can be implemented as a
4121 /// logical left or right shift of a vector.
4122 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4123 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4124 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4125 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4131 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4133 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4134 unsigned NumNonZero, unsigned NumZero,
4136 const TargetLowering &TLI) {
4140 DebugLoc dl = Op.getDebugLoc();
4143 for (unsigned i = 0; i < 16; ++i) {
4144 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4145 if (ThisIsNonZero && First) {
4147 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4149 V = DAG.getUNDEF(MVT::v8i16);
4154 SDValue ThisElt(0, 0), LastElt(0, 0);
4155 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4156 if (LastIsNonZero) {
4157 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4158 MVT::i16, Op.getOperand(i-1));
4160 if (ThisIsNonZero) {
4161 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4162 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4163 ThisElt, DAG.getConstant(8, MVT::i8));
4165 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4169 if (ThisElt.getNode())
4170 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4171 DAG.getIntPtrConstant(i/2));
4175 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4178 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4180 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4181 unsigned NumNonZero, unsigned NumZero,
4183 const TargetLowering &TLI) {
4187 DebugLoc dl = Op.getDebugLoc();
4190 for (unsigned i = 0; i < 8; ++i) {
4191 bool isNonZero = (NonZeros & (1 << i)) != 0;
4195 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4197 V = DAG.getUNDEF(MVT::v8i16);
4200 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4201 MVT::v8i16, V, Op.getOperand(i),
4202 DAG.getIntPtrConstant(i));
4209 /// getVShift - Return a vector logical shift node.
4211 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4212 unsigned NumBits, SelectionDAG &DAG,
4213 const TargetLowering &TLI, DebugLoc dl) {
4214 EVT ShVT = MVT::v2i64;
4215 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4216 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4217 return DAG.getNode(ISD::BITCAST, dl, VT,
4218 DAG.getNode(Opc, dl, ShVT, SrcOp,
4219 DAG.getConstant(NumBits,
4220 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4224 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4225 SelectionDAG &DAG) const {
4227 // Check if the scalar load can be widened into a vector load. And if
4228 // the address is "base + cst" see if the cst can be "absorbed" into
4229 // the shuffle mask.
4230 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4231 SDValue Ptr = LD->getBasePtr();
4232 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4234 EVT PVT = LD->getValueType(0);
4235 if (PVT != MVT::i32 && PVT != MVT::f32)
4240 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4241 FI = FINode->getIndex();
4243 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4244 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4245 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4246 Offset = Ptr.getConstantOperandVal(1);
4247 Ptr = Ptr.getOperand(0);
4252 SDValue Chain = LD->getChain();
4253 // Make sure the stack object alignment is at least 16.
4254 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4255 if (DAG.InferPtrAlignment(Ptr) < 16) {
4256 if (MFI->isFixedObjectIndex(FI)) {
4257 // Can't change the alignment. FIXME: It's possible to compute
4258 // the exact stack offset and reference FI + adjust offset instead.
4259 // If someone *really* cares about this. That's the way to implement it.
4262 MFI->setObjectAlignment(FI, 16);
4266 // (Offset % 16) must be multiple of 4. Then address is then
4267 // Ptr + (Offset & ~15).
4270 if ((Offset % 16) & 3)
4272 int64_t StartOffset = Offset & ~15;
4274 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4275 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4277 int EltNo = (Offset - StartOffset) >> 2;
4278 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4279 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4280 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4281 LD->getPointerInfo().getWithOffset(StartOffset),
4283 // Canonicalize it to a v4i32 shuffle.
4284 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4285 return DAG.getNode(ISD::BITCAST, dl, VT,
4286 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4287 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4293 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4294 /// vector of type 'VT', see if the elements can be replaced by a single large
4295 /// load which has the same value as a build_vector whose operands are 'elts'.
4297 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4299 /// FIXME: we'd also like to handle the case where the last elements are zero
4300 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4301 /// There's even a handy isZeroNode for that purpose.
4302 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4303 DebugLoc &DL, SelectionDAG &DAG) {
4304 EVT EltVT = VT.getVectorElementType();
4305 unsigned NumElems = Elts.size();
4307 LoadSDNode *LDBase = NULL;
4308 unsigned LastLoadedElt = -1U;
4310 // For each element in the initializer, see if we've found a load or an undef.
4311 // If we don't find an initial load element, or later load elements are
4312 // non-consecutive, bail out.
4313 for (unsigned i = 0; i < NumElems; ++i) {
4314 SDValue Elt = Elts[i];
4316 if (!Elt.getNode() ||
4317 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4320 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4322 LDBase = cast<LoadSDNode>(Elt.getNode());
4326 if (Elt.getOpcode() == ISD::UNDEF)
4329 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4330 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4335 // If we have found an entire vector of loads and undefs, then return a large
4336 // load of the entire vector width starting at the base pointer. If we found
4337 // consecutive loads for the low half, generate a vzext_load node.
4338 if (LastLoadedElt == NumElems - 1) {
4339 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4340 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4341 LDBase->getPointerInfo(),
4342 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4343 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4344 LDBase->getPointerInfo(),
4345 LDBase->isVolatile(), LDBase->isNonTemporal(),
4346 LDBase->getAlignment());
4347 } else if (NumElems == 4 && LastLoadedElt == 1) {
4348 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4349 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4350 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4352 LDBase->getMemOperand());
4353 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4359 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4360 DebugLoc dl = Op.getDebugLoc();
4362 EVT VT = Op.getValueType();
4363 EVT ExtVT = VT.getVectorElementType();
4365 unsigned NumElems = Op.getNumOperands();
4367 // For AVX-length vectors, build the individual 128-bit pieces and
4368 // use shuffles to put them in place.
4369 if (VT.getSizeInBits() > 256 &&
4370 Subtarget->hasAVX() &&
4371 !ISD::isBuildVectorAllZeros(Op.getNode())) {
4372 SmallVector<SDValue, 8> V;
4374 for (unsigned i = 0; i < NumElems; ++i) {
4375 V[i] = Op.getOperand(i);
4378 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4380 // Build the lower subvector.
4381 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4382 // Build the upper subvector.
4383 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4386 return ConcatVectors(Lower, Upper, DAG);
4389 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4390 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4391 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4392 // is present, so AllOnes is ignored.
4393 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4394 (Op.getValueType().getSizeInBits() != 256 &&
4395 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4396 // Canonicalize this to <4 x i32> (SSE) to
4397 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4398 // eliminated on x86-32 hosts.
4399 if (Op.getValueType() == MVT::v4i32)
4402 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4403 return getOnesVector(Op.getValueType(), DAG, dl);
4404 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4407 unsigned EVTBits = ExtVT.getSizeInBits();
4409 unsigned NumZero = 0;
4410 unsigned NumNonZero = 0;
4411 unsigned NonZeros = 0;
4412 bool IsAllConstants = true;
4413 SmallSet<SDValue, 8> Values;
4414 for (unsigned i = 0; i < NumElems; ++i) {
4415 SDValue Elt = Op.getOperand(i);
4416 if (Elt.getOpcode() == ISD::UNDEF)
4419 if (Elt.getOpcode() != ISD::Constant &&
4420 Elt.getOpcode() != ISD::ConstantFP)
4421 IsAllConstants = false;
4422 if (X86::isZeroNode(Elt))
4425 NonZeros |= (1 << i);
4430 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4431 if (NumNonZero == 0)
4432 return DAG.getUNDEF(VT);
4434 // Special case for single non-zero, non-undef, element.
4435 if (NumNonZero == 1) {
4436 unsigned Idx = CountTrailingZeros_32(NonZeros);
4437 SDValue Item = Op.getOperand(Idx);
4439 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4440 // the value are obviously zero, truncate the value to i32 and do the
4441 // insertion that way. Only do this if the value is non-constant or if the
4442 // value is a constant being inserted into element 0. It is cheaper to do
4443 // a constant pool load than it is to do a movd + shuffle.
4444 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4445 (!IsAllConstants || Idx == 0)) {
4446 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4448 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4449 EVT VecVT = MVT::v4i32;
4450 unsigned VecElts = 4;
4452 // Truncate the value (which may itself be a constant) to i32, and
4453 // convert it to a vector with movd (S2V+shuffle to zero extend).
4454 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4455 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4456 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4457 Subtarget->hasSSE2(), DAG);
4459 // Now we have our 32-bit value zero extended in the low element of
4460 // a vector. If Idx != 0, swizzle it into place.
4462 SmallVector<int, 4> Mask;
4463 Mask.push_back(Idx);
4464 for (unsigned i = 1; i != VecElts; ++i)
4466 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4467 DAG.getUNDEF(Item.getValueType()),
4470 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4474 // If we have a constant or non-constant insertion into the low element of
4475 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4476 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4477 // depending on what the source datatype is.
4480 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4481 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4482 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4483 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4484 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4485 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4487 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4488 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4489 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4490 EVT MiddleVT = MVT::v4i32;
4491 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4492 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4493 Subtarget->hasSSE2(), DAG);
4494 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4498 // Is it a vector logical left shift?
4499 if (NumElems == 2 && Idx == 1 &&
4500 X86::isZeroNode(Op.getOperand(0)) &&
4501 !X86::isZeroNode(Op.getOperand(1))) {
4502 unsigned NumBits = VT.getSizeInBits();
4503 return getVShift(true, VT,
4504 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4505 VT, Op.getOperand(1)),
4506 NumBits/2, DAG, *this, dl);
4509 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4512 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4513 // is a non-constant being inserted into an element other than the low one,
4514 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4515 // movd/movss) to move this into the low element, then shuffle it into
4517 if (EVTBits == 32) {
4518 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4520 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4521 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4522 Subtarget->hasSSE2(), DAG);
4523 SmallVector<int, 8> MaskVec;
4524 for (unsigned i = 0; i < NumElems; i++)
4525 MaskVec.push_back(i == Idx ? 0 : 1);
4526 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4530 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4531 if (Values.size() == 1) {
4532 if (EVTBits == 32) {
4533 // Instead of a shuffle like this:
4534 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4535 // Check if it's possible to issue this instead.
4536 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4537 unsigned Idx = CountTrailingZeros_32(NonZeros);
4538 SDValue Item = Op.getOperand(Idx);
4539 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4540 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4545 // A vector full of immediates; various special cases are already
4546 // handled, so this is best done with a single constant-pool load.
4550 // Let legalizer expand 2-wide build_vectors.
4551 if (EVTBits == 64) {
4552 if (NumNonZero == 1) {
4553 // One half is zero or undef.
4554 unsigned Idx = CountTrailingZeros_32(NonZeros);
4555 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4556 Op.getOperand(Idx));
4557 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4558 Subtarget->hasSSE2(), DAG);
4563 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4564 if (EVTBits == 8 && NumElems == 16) {
4565 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4567 if (V.getNode()) return V;
4570 if (EVTBits == 16 && NumElems == 8) {
4571 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4573 if (V.getNode()) return V;
4576 // If element VT is == 32 bits, turn it into a number of shuffles.
4577 SmallVector<SDValue, 8> V;
4579 if (NumElems == 4 && NumZero > 0) {
4580 for (unsigned i = 0; i < 4; ++i) {
4581 bool isZero = !(NonZeros & (1 << i));
4583 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4585 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4588 for (unsigned i = 0; i < 2; ++i) {
4589 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4592 V[i] = V[i*2]; // Must be a zero vector.
4595 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4598 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4601 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4606 SmallVector<int, 8> MaskVec;
4607 bool Reverse = (NonZeros & 0x3) == 2;
4608 for (unsigned i = 0; i < 2; ++i)
4609 MaskVec.push_back(Reverse ? 1-i : i);
4610 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4611 for (unsigned i = 0; i < 2; ++i)
4612 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4613 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4616 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4617 // Check for a build vector of consecutive loads.
4618 for (unsigned i = 0; i < NumElems; ++i)
4619 V[i] = Op.getOperand(i);
4621 // Check for elements which are consecutive loads.
4622 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4626 // For SSE 4.1, use insertps to put the high elements into the low element.
4627 if (getSubtarget()->hasSSE41()) {
4629 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4630 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4632 Result = DAG.getUNDEF(VT);
4634 for (unsigned i = 1; i < NumElems; ++i) {
4635 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4636 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4637 Op.getOperand(i), DAG.getIntPtrConstant(i));
4642 // Otherwise, expand into a number of unpckl*, start by extending each of
4643 // our (non-undef) elements to the full vector width with the element in the
4644 // bottom slot of the vector (which generates no code for SSE).
4645 for (unsigned i = 0; i < NumElems; ++i) {
4646 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4647 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4649 V[i] = DAG.getUNDEF(VT);
4652 // Next, we iteratively mix elements, e.g. for v4f32:
4653 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4654 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4655 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4656 unsigned EltStride = NumElems >> 1;
4657 while (EltStride != 0) {
4658 for (unsigned i = 0; i < EltStride; ++i) {
4659 // If V[i+EltStride] is undef and this is the first round of mixing,
4660 // then it is safe to just drop this shuffle: V[i] is already in the
4661 // right place, the one element (since it's the first round) being
4662 // inserted as undef can be dropped. This isn't safe for successive
4663 // rounds because they will permute elements within both vectors.
4664 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4665 EltStride == NumElems/2)
4668 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4678 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4679 // We support concatenate two MMX registers and place them in a MMX
4680 // register. This is better than doing a stack convert.
4681 DebugLoc dl = Op.getDebugLoc();
4682 EVT ResVT = Op.getValueType();
4683 assert(Op.getNumOperands() == 2);
4684 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4685 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4687 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4688 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4689 InVec = Op.getOperand(1);
4690 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4691 unsigned NumElts = ResVT.getVectorNumElements();
4692 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4693 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4694 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4696 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4697 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4698 Mask[0] = 0; Mask[1] = 2;
4699 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4701 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4704 // v8i16 shuffles - Prefer shuffles in the following order:
4705 // 1. [all] pshuflw, pshufhw, optional move
4706 // 2. [ssse3] 1 x pshufb
4707 // 3. [ssse3] 2 x pshufb + 1 x por
4708 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4710 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4711 SelectionDAG &DAG) const {
4712 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4713 SDValue V1 = SVOp->getOperand(0);
4714 SDValue V2 = SVOp->getOperand(1);
4715 DebugLoc dl = SVOp->getDebugLoc();
4716 SmallVector<int, 8> MaskVals;
4718 // Determine if more than 1 of the words in each of the low and high quadwords
4719 // of the result come from the same quadword of one of the two inputs. Undef
4720 // mask values count as coming from any quadword, for better codegen.
4721 SmallVector<unsigned, 4> LoQuad(4);
4722 SmallVector<unsigned, 4> HiQuad(4);
4723 BitVector InputQuads(4);
4724 for (unsigned i = 0; i < 8; ++i) {
4725 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4726 int EltIdx = SVOp->getMaskElt(i);
4727 MaskVals.push_back(EltIdx);
4736 InputQuads.set(EltIdx / 4);
4739 int BestLoQuad = -1;
4740 unsigned MaxQuad = 1;
4741 for (unsigned i = 0; i < 4; ++i) {
4742 if (LoQuad[i] > MaxQuad) {
4744 MaxQuad = LoQuad[i];
4748 int BestHiQuad = -1;
4750 for (unsigned i = 0; i < 4; ++i) {
4751 if (HiQuad[i] > MaxQuad) {
4753 MaxQuad = HiQuad[i];
4757 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4758 // of the two input vectors, shuffle them into one input vector so only a
4759 // single pshufb instruction is necessary. If There are more than 2 input
4760 // quads, disable the next transformation since it does not help SSSE3.
4761 bool V1Used = InputQuads[0] || InputQuads[1];
4762 bool V2Used = InputQuads[2] || InputQuads[3];
4763 if (Subtarget->hasSSSE3()) {
4764 if (InputQuads.count() == 2 && V1Used && V2Used) {
4765 BestLoQuad = InputQuads.find_first();
4766 BestHiQuad = InputQuads.find_next(BestLoQuad);
4768 if (InputQuads.count() > 2) {
4774 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4775 // the shuffle mask. If a quad is scored as -1, that means that it contains
4776 // words from all 4 input quadwords.
4778 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4779 SmallVector<int, 8> MaskV;
4780 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4781 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4782 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4783 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4784 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4785 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4787 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4788 // source words for the shuffle, to aid later transformations.
4789 bool AllWordsInNewV = true;
4790 bool InOrder[2] = { true, true };
4791 for (unsigned i = 0; i != 8; ++i) {
4792 int idx = MaskVals[i];
4794 InOrder[i/4] = false;
4795 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4797 AllWordsInNewV = false;
4801 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4802 if (AllWordsInNewV) {
4803 for (int i = 0; i != 8; ++i) {
4804 int idx = MaskVals[i];
4807 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4808 if ((idx != i) && idx < 4)
4810 if ((idx != i) && idx > 3)
4819 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4820 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4821 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4822 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4823 unsigned TargetMask = 0;
4824 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4825 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4826 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4827 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4828 V1 = NewV.getOperand(0);
4829 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4833 // If we have SSSE3, and all words of the result are from 1 input vector,
4834 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4835 // is present, fall back to case 4.
4836 if (Subtarget->hasSSSE3()) {
4837 SmallVector<SDValue,16> pshufbMask;
4839 // If we have elements from both input vectors, set the high bit of the
4840 // shuffle mask element to zero out elements that come from V2 in the V1
4841 // mask, and elements that come from V1 in the V2 mask, so that the two
4842 // results can be OR'd together.
4843 bool TwoInputs = V1Used && V2Used;
4844 for (unsigned i = 0; i != 8; ++i) {
4845 int EltIdx = MaskVals[i] * 2;
4846 if (TwoInputs && (EltIdx >= 16)) {
4847 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4848 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4851 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4852 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4854 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4855 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4856 DAG.getNode(ISD::BUILD_VECTOR, dl,
4857 MVT::v16i8, &pshufbMask[0], 16));
4859 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4861 // Calculate the shuffle mask for the second input, shuffle it, and
4862 // OR it with the first shuffled input.
4864 for (unsigned i = 0; i != 8; ++i) {
4865 int EltIdx = MaskVals[i] * 2;
4867 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4868 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4871 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4872 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4874 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4875 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4876 DAG.getNode(ISD::BUILD_VECTOR, dl,
4877 MVT::v16i8, &pshufbMask[0], 16));
4878 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4879 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4882 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4883 // and update MaskVals with new element order.
4884 BitVector InOrder(8);
4885 if (BestLoQuad >= 0) {
4886 SmallVector<int, 8> MaskV;
4887 for (int i = 0; i != 4; ++i) {
4888 int idx = MaskVals[i];
4890 MaskV.push_back(-1);
4892 } else if ((idx / 4) == BestLoQuad) {
4893 MaskV.push_back(idx & 3);
4896 MaskV.push_back(-1);
4899 for (unsigned i = 4; i != 8; ++i)
4901 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4904 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4905 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4907 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4911 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4912 // and update MaskVals with the new element order.
4913 if (BestHiQuad >= 0) {
4914 SmallVector<int, 8> MaskV;
4915 for (unsigned i = 0; i != 4; ++i)
4917 for (unsigned i = 4; i != 8; ++i) {
4918 int idx = MaskVals[i];
4920 MaskV.push_back(-1);
4922 } else if ((idx / 4) == BestHiQuad) {
4923 MaskV.push_back((idx & 3) + 4);
4926 MaskV.push_back(-1);
4929 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4932 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4933 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4935 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4939 // In case BestHi & BestLo were both -1, which means each quadword has a word
4940 // from each of the four input quadwords, calculate the InOrder bitvector now
4941 // before falling through to the insert/extract cleanup.
4942 if (BestLoQuad == -1 && BestHiQuad == -1) {
4944 for (int i = 0; i != 8; ++i)
4945 if (MaskVals[i] < 0 || MaskVals[i] == i)
4949 // The other elements are put in the right place using pextrw and pinsrw.
4950 for (unsigned i = 0; i != 8; ++i) {
4953 int EltIdx = MaskVals[i];
4956 SDValue ExtOp = (EltIdx < 8)
4957 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4958 DAG.getIntPtrConstant(EltIdx))
4959 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4960 DAG.getIntPtrConstant(EltIdx - 8));
4961 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4962 DAG.getIntPtrConstant(i));
4967 // v16i8 shuffles - Prefer shuffles in the following order:
4968 // 1. [ssse3] 1 x pshufb
4969 // 2. [ssse3] 2 x pshufb + 1 x por
4970 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4972 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4974 const X86TargetLowering &TLI) {
4975 SDValue V1 = SVOp->getOperand(0);
4976 SDValue V2 = SVOp->getOperand(1);
4977 DebugLoc dl = SVOp->getDebugLoc();
4978 SmallVector<int, 16> MaskVals;
4979 SVOp->getMask(MaskVals);
4981 // If we have SSSE3, case 1 is generated when all result bytes come from
4982 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4983 // present, fall back to case 3.
4984 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4987 for (unsigned i = 0; i < 16; ++i) {
4988 int EltIdx = MaskVals[i];
4997 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4998 if (TLI.getSubtarget()->hasSSSE3()) {
4999 SmallVector<SDValue,16> pshufbMask;
5001 // If all result elements are from one input vector, then only translate
5002 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5004 // Otherwise, we have elements from both input vectors, and must zero out
5005 // elements that come from V2 in the first mask, and V1 in the second mask
5006 // so that we can OR them together.
5007 bool TwoInputs = !(V1Only || V2Only);
5008 for (unsigned i = 0; i != 16; ++i) {
5009 int EltIdx = MaskVals[i];
5010 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5011 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5014 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5016 // If all the elements are from V2, assign it to V1 and return after
5017 // building the first pshufb.
5020 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5021 DAG.getNode(ISD::BUILD_VECTOR, dl,
5022 MVT::v16i8, &pshufbMask[0], 16));
5026 // Calculate the shuffle mask for the second input, shuffle it, and
5027 // OR it with the first shuffled input.
5029 for (unsigned i = 0; i != 16; ++i) {
5030 int EltIdx = MaskVals[i];
5032 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5035 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5037 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5038 DAG.getNode(ISD::BUILD_VECTOR, dl,
5039 MVT::v16i8, &pshufbMask[0], 16));
5040 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5043 // No SSSE3 - Calculate in place words and then fix all out of place words
5044 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5045 // the 16 different words that comprise the two doublequadword input vectors.
5046 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5047 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5048 SDValue NewV = V2Only ? V2 : V1;
5049 for (int i = 0; i != 8; ++i) {
5050 int Elt0 = MaskVals[i*2];
5051 int Elt1 = MaskVals[i*2+1];
5053 // This word of the result is all undef, skip it.
5054 if (Elt0 < 0 && Elt1 < 0)
5057 // This word of the result is already in the correct place, skip it.
5058 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5060 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5063 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5064 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5067 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5068 // using a single extract together, load it and store it.
5069 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5070 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5071 DAG.getIntPtrConstant(Elt1 / 2));
5072 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5073 DAG.getIntPtrConstant(i));
5077 // If Elt1 is defined, extract it from the appropriate source. If the
5078 // source byte is not also odd, shift the extracted word left 8 bits
5079 // otherwise clear the bottom 8 bits if we need to do an or.
5081 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5082 DAG.getIntPtrConstant(Elt1 / 2));
5083 if ((Elt1 & 1) == 0)
5084 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5086 TLI.getShiftAmountTy(InsElt.getValueType())));
5088 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5089 DAG.getConstant(0xFF00, MVT::i16));
5091 // If Elt0 is defined, extract it from the appropriate source. If the
5092 // source byte is not also even, shift the extracted word right 8 bits. If
5093 // Elt1 was also defined, OR the extracted values together before
5094 // inserting them in the result.
5096 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5097 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5098 if ((Elt0 & 1) != 0)
5099 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5101 TLI.getShiftAmountTy(InsElt0.getValueType())));
5103 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5104 DAG.getConstant(0x00FF, MVT::i16));
5105 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5108 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5109 DAG.getIntPtrConstant(i));
5111 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5114 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5115 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5116 /// done when every pair / quad of shuffle mask elements point to elements in
5117 /// the right sequence. e.g.
5118 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5120 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5121 SelectionDAG &DAG, DebugLoc dl) {
5122 EVT VT = SVOp->getValueType(0);
5123 SDValue V1 = SVOp->getOperand(0);
5124 SDValue V2 = SVOp->getOperand(1);
5125 unsigned NumElems = VT.getVectorNumElements();
5126 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5128 switch (VT.getSimpleVT().SimpleTy) {
5129 default: assert(false && "Unexpected!");
5130 case MVT::v4f32: NewVT = MVT::v2f64; break;
5131 case MVT::v4i32: NewVT = MVT::v2i64; break;
5132 case MVT::v8i16: NewVT = MVT::v4i32; break;
5133 case MVT::v16i8: NewVT = MVT::v4i32; break;
5136 int Scale = NumElems / NewWidth;
5137 SmallVector<int, 8> MaskVec;
5138 for (unsigned i = 0; i < NumElems; i += Scale) {
5140 for (int j = 0; j < Scale; ++j) {
5141 int EltIdx = SVOp->getMaskElt(i+j);
5145 StartIdx = EltIdx - (EltIdx % Scale);
5146 if (EltIdx != StartIdx + j)
5150 MaskVec.push_back(-1);
5152 MaskVec.push_back(StartIdx / Scale);
5155 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5156 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5157 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5160 /// getVZextMovL - Return a zero-extending vector move low node.
5162 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5163 SDValue SrcOp, SelectionDAG &DAG,
5164 const X86Subtarget *Subtarget, DebugLoc dl) {
5165 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5166 LoadSDNode *LD = NULL;
5167 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5168 LD = dyn_cast<LoadSDNode>(SrcOp);
5170 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5172 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5173 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5174 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5175 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5176 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5178 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5179 return DAG.getNode(ISD::BITCAST, dl, VT,
5180 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5181 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5189 return DAG.getNode(ISD::BITCAST, dl, VT,
5190 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5191 DAG.getNode(ISD::BITCAST, dl,
5195 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5198 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5199 SDValue V1 = SVOp->getOperand(0);
5200 SDValue V2 = SVOp->getOperand(1);
5201 DebugLoc dl = SVOp->getDebugLoc();
5202 EVT VT = SVOp->getValueType(0);
5204 SmallVector<std::pair<int, int>, 8> Locs;
5206 SmallVector<int, 8> Mask1(4U, -1);
5207 SmallVector<int, 8> PermMask;
5208 SVOp->getMask(PermMask);
5212 for (unsigned i = 0; i != 4; ++i) {
5213 int Idx = PermMask[i];
5215 Locs[i] = std::make_pair(-1, -1);
5217 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5219 Locs[i] = std::make_pair(0, NumLo);
5223 Locs[i] = std::make_pair(1, NumHi);
5225 Mask1[2+NumHi] = Idx;
5231 if (NumLo <= 2 && NumHi <= 2) {
5232 // If no more than two elements come from either vector. This can be
5233 // implemented with two shuffles. First shuffle gather the elements.
5234 // The second shuffle, which takes the first shuffle as both of its
5235 // vector operands, put the elements into the right order.
5236 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5238 SmallVector<int, 8> Mask2(4U, -1);
5240 for (unsigned i = 0; i != 4; ++i) {
5241 if (Locs[i].first == -1)
5244 unsigned Idx = (i < 2) ? 0 : 4;
5245 Idx += Locs[i].first * 2 + Locs[i].second;
5250 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5251 } else if (NumLo == 3 || NumHi == 3) {
5252 // Otherwise, we must have three elements from one vector, call it X, and
5253 // one element from the other, call it Y. First, use a shufps to build an
5254 // intermediate vector with the one element from Y and the element from X
5255 // that will be in the same half in the final destination (the indexes don't
5256 // matter). Then, use a shufps to build the final vector, taking the half
5257 // containing the element from Y from the intermediate, and the other half
5260 // Normalize it so the 3 elements come from V1.
5261 CommuteVectorShuffleMask(PermMask, VT);
5265 // Find the element from V2.
5267 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5268 int Val = PermMask[HiIndex];
5275 Mask1[0] = PermMask[HiIndex];
5277 Mask1[2] = PermMask[HiIndex^1];
5279 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5282 Mask1[0] = PermMask[0];
5283 Mask1[1] = PermMask[1];
5284 Mask1[2] = HiIndex & 1 ? 6 : 4;
5285 Mask1[3] = HiIndex & 1 ? 4 : 6;
5286 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5288 Mask1[0] = HiIndex & 1 ? 2 : 0;
5289 Mask1[1] = HiIndex & 1 ? 0 : 2;
5290 Mask1[2] = PermMask[2];
5291 Mask1[3] = PermMask[3];
5296 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5300 // Break it into (shuffle shuffle_hi, shuffle_lo).
5303 SmallVector<int,8> LoMask(4U, -1);
5304 SmallVector<int,8> HiMask(4U, -1);
5306 SmallVector<int,8> *MaskPtr = &LoMask;
5307 unsigned MaskIdx = 0;
5310 for (unsigned i = 0; i != 4; ++i) {
5317 int Idx = PermMask[i];
5319 Locs[i] = std::make_pair(-1, -1);
5320 } else if (Idx < 4) {
5321 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5322 (*MaskPtr)[LoIdx] = Idx;
5325 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5326 (*MaskPtr)[HiIdx] = Idx;
5331 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5332 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5333 SmallVector<int, 8> MaskOps;
5334 for (unsigned i = 0; i != 4; ++i) {
5335 if (Locs[i].first == -1) {
5336 MaskOps.push_back(-1);
5338 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5339 MaskOps.push_back(Idx);
5342 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5345 static bool MayFoldVectorLoad(SDValue V) {
5346 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5347 V = V.getOperand(0);
5348 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5349 V = V.getOperand(0);
5355 // FIXME: the version above should always be used. Since there's
5356 // a bug where several vector shuffles can't be folded because the
5357 // DAG is not updated during lowering and a node claims to have two
5358 // uses while it only has one, use this version, and let isel match
5359 // another instruction if the load really happens to have more than
5360 // one use. Remove this version after this bug get fixed.
5361 // rdar://8434668, PR8156
5362 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5363 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5364 V = V.getOperand(0);
5365 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5366 V = V.getOperand(0);
5367 if (ISD::isNormalLoad(V.getNode()))
5372 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5373 /// a vector extract, and if both can be later optimized into a single load.
5374 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5375 /// here because otherwise a target specific shuffle node is going to be
5376 /// emitted for this shuffle, and the optimization not done.
5377 /// FIXME: This is probably not the best approach, but fix the problem
5378 /// until the right path is decided.
5380 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5381 const TargetLowering &TLI) {
5382 EVT VT = V.getValueType();
5383 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5385 // Be sure that the vector shuffle is present in a pattern like this:
5386 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5390 SDNode *N = *V.getNode()->use_begin();
5391 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5394 SDValue EltNo = N->getOperand(1);
5395 if (!isa<ConstantSDNode>(EltNo))
5398 // If the bit convert changed the number of elements, it is unsafe
5399 // to examine the mask.
5400 bool HasShuffleIntoBitcast = false;
5401 if (V.getOpcode() == ISD::BITCAST) {
5402 EVT SrcVT = V.getOperand(0).getValueType();
5403 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5405 V = V.getOperand(0);
5406 HasShuffleIntoBitcast = true;
5409 // Select the input vector, guarding against out of range extract vector.
5410 unsigned NumElems = VT.getVectorNumElements();
5411 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5412 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5413 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5415 // Skip one more bit_convert if necessary
5416 if (V.getOpcode() == ISD::BITCAST)
5417 V = V.getOperand(0);
5419 if (ISD::isNormalLoad(V.getNode())) {
5420 // Is the original load suitable?
5421 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5423 // FIXME: avoid the multi-use bug that is preventing lots of
5424 // of foldings to be detected, this is still wrong of course, but
5425 // give the temporary desired behavior, and if it happens that
5426 // the load has real more uses, during isel it will not fold, and
5427 // will generate poor code.
5428 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5431 if (!HasShuffleIntoBitcast)
5434 // If there's a bitcast before the shuffle, check if the load type and
5435 // alignment is valid.
5436 unsigned Align = LN0->getAlignment();
5438 TLI.getTargetData()->getABITypeAlignment(
5439 VT.getTypeForEVT(*DAG.getContext()));
5441 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5449 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5450 EVT VT = Op.getValueType();
5452 // Canonizalize to v2f64.
5453 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5454 return DAG.getNode(ISD::BITCAST, dl, VT,
5455 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5460 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5462 SDValue V1 = Op.getOperand(0);
5463 SDValue V2 = Op.getOperand(1);
5464 EVT VT = Op.getValueType();
5466 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5468 if (HasSSE2 && VT == MVT::v2f64)
5469 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5472 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5476 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5477 SDValue V1 = Op.getOperand(0);
5478 SDValue V2 = Op.getOperand(1);
5479 EVT VT = Op.getValueType();
5481 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5482 "unsupported shuffle type");
5484 if (V2.getOpcode() == ISD::UNDEF)
5488 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5492 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5493 SDValue V1 = Op.getOperand(0);
5494 SDValue V2 = Op.getOperand(1);
5495 EVT VT = Op.getValueType();
5496 unsigned NumElems = VT.getVectorNumElements();
5498 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5499 // operand of these instructions is only memory, so check if there's a
5500 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5502 bool CanFoldLoad = false;
5504 // Trivial case, when V2 comes from a load.
5505 if (MayFoldVectorLoad(V2))
5508 // When V1 is a load, it can be folded later into a store in isel, example:
5509 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5511 // (MOVLPSmr addr:$src1, VR128:$src2)
5512 // So, recognize this potential and also use MOVLPS or MOVLPD
5513 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5516 // Both of them can't be memory operations though.
5517 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5518 CanFoldLoad = false;
5521 if (HasSSE2 && NumElems == 2)
5522 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5525 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5528 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5529 // movl and movlp will both match v2i64, but v2i64 is never matched by
5530 // movl earlier because we make it strict to avoid messing with the movlp load
5531 // folding logic (see the code above getMOVLP call). Match it here then,
5532 // this is horrible, but will stay like this until we move all shuffle
5533 // matching to x86 specific nodes. Note that for the 1st condition all
5534 // types are matched with movsd.
5535 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5536 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5538 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5541 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5543 // Invert the operand order and use SHUFPS to match it.
5544 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5545 X86::getShuffleSHUFImmediate(SVOp), DAG);
5548 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5549 switch(VT.getSimpleVT().SimpleTy) {
5550 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5551 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5553 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5555 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5556 case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5557 case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5558 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5559 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5561 llvm_unreachable("Unknown type for unpckl");
5566 static inline unsigned getUNPCKHOpcode(EVT VT) {
5567 switch(VT.getSimpleVT().SimpleTy) {
5568 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5569 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5570 case MVT::v4f32: return X86ISD::UNPCKHPS;
5571 case MVT::v2f64: return X86ISD::UNPCKHPD;
5572 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5573 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5575 llvm_unreachable("Unknown type for unpckh");
5581 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5582 const TargetLowering &TLI,
5583 const X86Subtarget *Subtarget) {
5584 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5585 EVT VT = Op.getValueType();
5586 DebugLoc dl = Op.getDebugLoc();
5587 SDValue V1 = Op.getOperand(0);
5588 SDValue V2 = Op.getOperand(1);
5590 if (isZeroShuffle(SVOp))
5591 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5593 // Handle splat operations
5594 if (SVOp->isSplat()) {
5595 // Special case, this is the only place now where it's
5596 // allowed to return a vector_shuffle operation without
5597 // using a target specific node, because *hopefully* it
5598 // will be optimized away by the dag combiner.
5599 if (VT.getVectorNumElements() <= 4 &&
5600 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5603 // Handle splats by matching through known masks
5604 if (VT.getVectorNumElements() <= 4)
5607 // Canonicalize all of the remaining to v4f32.
5608 return PromoteSplat(SVOp, DAG);
5611 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5613 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5614 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5615 if (NewOp.getNode())
5616 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5617 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5618 // FIXME: Figure out a cleaner way to do this.
5619 // Try to make use of movq to zero out the top part.
5620 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5621 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5622 if (NewOp.getNode()) {
5623 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5624 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5625 DAG, Subtarget, dl);
5627 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5628 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5629 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5630 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5631 DAG, Subtarget, dl);
5638 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5639 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5640 SDValue V1 = Op.getOperand(0);
5641 SDValue V2 = Op.getOperand(1);
5642 EVT VT = Op.getValueType();
5643 DebugLoc dl = Op.getDebugLoc();
5644 unsigned NumElems = VT.getVectorNumElements();
5645 bool isMMX = VT.getSizeInBits() == 64;
5646 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5647 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5648 bool V1IsSplat = false;
5649 bool V2IsSplat = false;
5650 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5651 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5652 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5653 MachineFunction &MF = DAG.getMachineFunction();
5654 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5656 // Shuffle operations on MMX not supported.
5660 // Vector shuffle lowering takes 3 steps:
5662 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5663 // narrowing and commutation of operands should be handled.
5664 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5666 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5667 // so the shuffle can be broken into other shuffles and the legalizer can
5668 // try the lowering again.
5670 // The general ideia is that no vector_shuffle operation should be left to
5671 // be matched during isel, all of them must be converted to a target specific
5674 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5675 // narrowing and commutation of operands should be handled. The actual code
5676 // doesn't include all of those, work in progress...
5677 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5678 if (NewOp.getNode())
5681 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5682 // unpckh_undef). Only use pshufd if speed is more important than size.
5683 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5684 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5685 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5686 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5687 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5688 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5690 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5691 RelaxedMayFoldVectorLoad(V1))
5692 return getMOVDDup(Op, dl, V1, DAG);
5694 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5695 return getMOVHighToLow(Op, dl, DAG);
5697 // Use to match splats
5698 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5699 (VT == MVT::v2f64 || VT == MVT::v2i64))
5700 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5702 if (X86::isPSHUFDMask(SVOp)) {
5703 // The actual implementation will match the mask in the if above and then
5704 // during isel it can match several different instructions, not only pshufd
5705 // as its name says, sad but true, emulate the behavior for now...
5706 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5707 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5709 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5711 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5712 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5714 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5715 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5718 if (VT == MVT::v4f32)
5719 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5723 // Check if this can be converted into a logical shift.
5724 bool isLeft = false;
5727 bool isShift = getSubtarget()->hasSSE2() &&
5728 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5729 if (isShift && ShVal.hasOneUse()) {
5730 // If the shifted value has multiple uses, it may be cheaper to use
5731 // v_set0 + movlhps or movhlps, etc.
5732 EVT EltVT = VT.getVectorElementType();
5733 ShAmt *= EltVT.getSizeInBits();
5734 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5737 if (X86::isMOVLMask(SVOp)) {
5740 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5741 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5742 if (!X86::isMOVLPMask(SVOp)) {
5743 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5744 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5746 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5747 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5751 // FIXME: fold these into legal mask.
5752 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5753 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5755 if (X86::isMOVHLPSMask(SVOp))
5756 return getMOVHighToLow(Op, dl, DAG);
5758 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5759 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5761 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5762 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5764 if (X86::isMOVLPMask(SVOp))
5765 return getMOVLP(Op, dl, DAG, HasSSE2);
5767 if (ShouldXformToMOVHLPS(SVOp) ||
5768 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5769 return CommuteVectorShuffle(SVOp, DAG);
5772 // No better options. Use a vshl / vsrl.
5773 EVT EltVT = VT.getVectorElementType();
5774 ShAmt *= EltVT.getSizeInBits();
5775 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5778 bool Commuted = false;
5779 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5780 // 1,1,1,1 -> v8i16 though.
5781 V1IsSplat = isSplatVector(V1.getNode());
5782 V2IsSplat = isSplatVector(V2.getNode());
5784 // Canonicalize the splat or undef, if present, to be on the RHS.
5785 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5786 Op = CommuteVectorShuffle(SVOp, DAG);
5787 SVOp = cast<ShuffleVectorSDNode>(Op);
5788 V1 = SVOp->getOperand(0);
5789 V2 = SVOp->getOperand(1);
5790 std::swap(V1IsSplat, V2IsSplat);
5791 std::swap(V1IsUndef, V2IsUndef);
5795 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5796 // Shuffling low element of v1 into undef, just return v1.
5799 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5800 // the instruction selector will not match, so get a canonical MOVL with
5801 // swapped operands to undo the commute.
5802 return getMOVL(DAG, dl, VT, V2, V1);
5805 if (X86::isUNPCKLMask(SVOp))
5806 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5807 dl, VT, V1, V2, DAG);
5809 if (X86::isUNPCKHMask(SVOp))
5810 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5813 // Normalize mask so all entries that point to V2 points to its first
5814 // element then try to match unpck{h|l} again. If match, return a
5815 // new vector_shuffle with the corrected mask.
5816 SDValue NewMask = NormalizeMask(SVOp, DAG);
5817 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5818 if (NSVOp != SVOp) {
5819 if (X86::isUNPCKLMask(NSVOp, true)) {
5821 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5828 // Commute is back and try unpck* again.
5829 // FIXME: this seems wrong.
5830 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5831 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5833 if (X86::isUNPCKLMask(NewSVOp))
5834 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5835 dl, VT, V2, V1, DAG);
5837 if (X86::isUNPCKHMask(NewSVOp))
5838 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5841 // Normalize the node to match x86 shuffle ops if needed
5842 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5843 return CommuteVectorShuffle(SVOp, DAG);
5845 // The checks below are all present in isShuffleMaskLegal, but they are
5846 // inlined here right now to enable us to directly emit target specific
5847 // nodes, and remove one by one until they don't return Op anymore.
5848 SmallVector<int, 16> M;
5851 if (isPALIGNRMask(M, VT, HasSSSE3))
5852 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5853 X86::getShufflePALIGNRImmediate(SVOp),
5856 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5857 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5858 if (VT == MVT::v2f64) {
5859 X86ISD::NodeType Opcode =
5860 getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5861 return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5863 if (VT == MVT::v2i64)
5864 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5867 if (isPSHUFHWMask(M, VT))
5868 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5869 X86::getShufflePSHUFHWImmediate(SVOp),
5872 if (isPSHUFLWMask(M, VT))
5873 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5874 X86::getShufflePSHUFLWImmediate(SVOp),
5877 if (isSHUFPMask(M, VT)) {
5878 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5879 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5880 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5882 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5883 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5887 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5888 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5889 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5890 dl, VT, V1, V1, DAG);
5891 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5892 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5893 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5895 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5896 if (VT == MVT::v8i16) {
5897 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5898 if (NewOp.getNode())
5902 if (VT == MVT::v16i8) {
5903 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5904 if (NewOp.getNode())
5908 // Handle all 4 wide cases with a number of shuffles.
5910 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5916 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5917 SelectionDAG &DAG) const {
5918 EVT VT = Op.getValueType();
5919 DebugLoc dl = Op.getDebugLoc();
5920 if (VT.getSizeInBits() == 8) {
5921 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5922 Op.getOperand(0), Op.getOperand(1));
5923 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5924 DAG.getValueType(VT));
5925 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5926 } else if (VT.getSizeInBits() == 16) {
5927 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5928 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5930 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5931 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5932 DAG.getNode(ISD::BITCAST, dl,
5936 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5937 Op.getOperand(0), Op.getOperand(1));
5938 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5939 DAG.getValueType(VT));
5940 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5941 } else if (VT == MVT::f32) {
5942 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5943 // the result back to FR32 register. It's only worth matching if the
5944 // result has a single use which is a store or a bitcast to i32. And in
5945 // the case of a store, it's not worth it if the index is a constant 0,
5946 // because a MOVSSmr can be used instead, which is smaller and faster.
5947 if (!Op.hasOneUse())
5949 SDNode *User = *Op.getNode()->use_begin();
5950 if ((User->getOpcode() != ISD::STORE ||
5951 (isa<ConstantSDNode>(Op.getOperand(1)) &&
5952 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5953 (User->getOpcode() != ISD::BITCAST ||
5954 User->getValueType(0) != MVT::i32))
5956 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5957 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5960 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5961 } else if (VT == MVT::i32) {
5962 // ExtractPS works with constant index.
5963 if (isa<ConstantSDNode>(Op.getOperand(1)))
5971 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5972 SelectionDAG &DAG) const {
5973 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5976 SDValue Vec = Op.getOperand(0);
5977 EVT VecVT = Vec.getValueType();
5979 // If this is a 256-bit vector result, first extract the 128-bit
5980 // vector and then extract from the 128-bit vector.
5981 if (VecVT.getSizeInBits() > 128) {
5982 DebugLoc dl = Op.getNode()->getDebugLoc();
5983 unsigned NumElems = VecVT.getVectorNumElements();
5984 SDValue Idx = Op.getOperand(1);
5986 if (!isa<ConstantSDNode>(Idx))
5989 unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
5990 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5992 // Get the 128-bit vector.
5993 bool Upper = IdxVal >= ExtractNumElems;
5994 Vec = Extract128BitVector(Vec, Idx, DAG, dl);
5997 SDValue ScaledIdx = Idx;
5999 ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6000 DAG.getConstant(ExtractNumElems,
6001 Idx.getValueType()));
6002 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6006 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6008 if (Subtarget->hasSSE41()) {
6009 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6014 EVT VT = Op.getValueType();
6015 DebugLoc dl = Op.getDebugLoc();
6016 // TODO: handle v16i8.
6017 if (VT.getSizeInBits() == 16) {
6018 SDValue Vec = Op.getOperand(0);
6019 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6021 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6022 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6023 DAG.getNode(ISD::BITCAST, dl,
6026 // Transform it so it match pextrw which produces a 32-bit result.
6027 EVT EltVT = MVT::i32;
6028 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6029 Op.getOperand(0), Op.getOperand(1));
6030 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6031 DAG.getValueType(VT));
6032 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6033 } else if (VT.getSizeInBits() == 32) {
6034 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6038 // SHUFPS the element to the lowest double word, then movss.
6039 int Mask[4] = { Idx, -1, -1, -1 };
6040 EVT VVT = Op.getOperand(0).getValueType();
6041 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6042 DAG.getUNDEF(VVT), Mask);
6043 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6044 DAG.getIntPtrConstant(0));
6045 } else if (VT.getSizeInBits() == 64) {
6046 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6047 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6048 // to match extract_elt for f64.
6049 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6053 // UNPCKHPD the element to the lowest double word, then movsd.
6054 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6055 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6056 int Mask[2] = { 1, -1 };
6057 EVT VVT = Op.getOperand(0).getValueType();
6058 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6059 DAG.getUNDEF(VVT), Mask);
6060 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6061 DAG.getIntPtrConstant(0));
6068 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6069 SelectionDAG &DAG) const {
6070 EVT VT = Op.getValueType();
6071 EVT EltVT = VT.getVectorElementType();
6072 DebugLoc dl = Op.getDebugLoc();
6074 SDValue N0 = Op.getOperand(0);
6075 SDValue N1 = Op.getOperand(1);
6076 SDValue N2 = Op.getOperand(2);
6078 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6079 isa<ConstantSDNode>(N2)) {
6081 if (VT == MVT::v8i16)
6082 Opc = X86ISD::PINSRW;
6083 else if (VT == MVT::v16i8)
6084 Opc = X86ISD::PINSRB;
6086 Opc = X86ISD::PINSRB;
6088 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6090 if (N1.getValueType() != MVT::i32)
6091 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6092 if (N2.getValueType() != MVT::i32)
6093 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6094 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6095 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6096 // Bits [7:6] of the constant are the source select. This will always be
6097 // zero here. The DAG Combiner may combine an extract_elt index into these
6098 // bits. For example (insert (extract, 3), 2) could be matched by putting
6099 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6100 // Bits [5:4] of the constant are the destination select. This is the
6101 // value of the incoming immediate.
6102 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6103 // combine either bitwise AND or insert of float 0.0 to set these bits.
6104 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6105 // Create this as a scalar to vector..
6106 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6107 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6108 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6109 // PINSR* works with constant index.
6116 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6117 EVT VT = Op.getValueType();
6118 EVT EltVT = VT.getVectorElementType();
6120 DebugLoc dl = Op.getDebugLoc();
6121 SDValue N0 = Op.getOperand(0);
6122 SDValue N1 = Op.getOperand(1);
6123 SDValue N2 = Op.getOperand(2);
6125 // If this is a 256-bit vector result, first insert into a 128-bit
6126 // vector and then insert into the 256-bit vector.
6127 if (VT.getSizeInBits() > 128) {
6128 if (!isa<ConstantSDNode>(N2))
6131 // Get the 128-bit vector.
6132 unsigned NumElems = VT.getVectorNumElements();
6133 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6134 bool Upper = IdxVal >= NumElems / 2;
6136 SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6139 SDValue ScaledN2 = N2;
6141 ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6142 DAG.getConstant(NumElems /
6143 (VT.getSizeInBits() / 128),
6144 N2.getValueType()));
6145 Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6148 // Insert the 128-bit vector
6149 // FIXME: Why UNDEF?
6150 return Insert128BitVector(N0, Op, N2, DAG, dl);
6153 if (Subtarget->hasSSE41())
6154 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6156 if (EltVT == MVT::i8)
6159 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6160 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6161 // as its second argument.
6162 if (N1.getValueType() != MVT::i32)
6163 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6164 if (N2.getValueType() != MVT::i32)
6165 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6166 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6172 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6173 LLVMContext *Context = DAG.getContext();
6174 DebugLoc dl = Op.getDebugLoc();
6175 EVT OpVT = Op.getValueType();
6177 // If this is a 256-bit vector result, first insert into a 128-bit
6178 // vector and then insert into the 256-bit vector.
6179 if (OpVT.getSizeInBits() > 128) {
6180 // Insert into a 128-bit vector.
6181 EVT VT128 = EVT::getVectorVT(*Context,
6182 OpVT.getVectorElementType(),
6183 OpVT.getVectorNumElements() / 2);
6185 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6187 // Insert the 128-bit vector.
6188 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6189 DAG.getConstant(0, MVT::i32),
6193 if (Op.getValueType() == MVT::v1i64 &&
6194 Op.getOperand(0).getValueType() == MVT::i64)
6195 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6197 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6198 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6199 "Expected an SSE type!");
6200 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6201 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6204 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
6205 // a simple subregister reference or explicit instructions to grab
6206 // upper bits of a vector.
6208 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6209 if (Subtarget->hasAVX()) {
6210 DebugLoc dl = Op.getNode()->getDebugLoc();
6211 SDValue Vec = Op.getNode()->getOperand(0);
6212 SDValue Idx = Op.getNode()->getOperand(1);
6214 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6215 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6216 return Extract128BitVector(Vec, Idx, DAG, dl);
6222 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
6223 // simple superregister reference or explicit instructions to insert
6224 // the upper bits of a vector.
6226 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6227 if (Subtarget->hasAVX()) {
6228 DebugLoc dl = Op.getNode()->getDebugLoc();
6229 SDValue Vec = Op.getNode()->getOperand(0);
6230 SDValue SubVec = Op.getNode()->getOperand(1);
6231 SDValue Idx = Op.getNode()->getOperand(2);
6233 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6234 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6235 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6241 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6242 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6243 // one of the above mentioned nodes. It has to be wrapped because otherwise
6244 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6245 // be used to form addressing mode. These wrapped nodes will be selected
6248 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6249 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6251 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6253 unsigned char OpFlag = 0;
6254 unsigned WrapperKind = X86ISD::Wrapper;
6255 CodeModel::Model M = getTargetMachine().getCodeModel();
6257 if (Subtarget->isPICStyleRIPRel() &&
6258 (M == CodeModel::Small || M == CodeModel::Kernel))
6259 WrapperKind = X86ISD::WrapperRIP;
6260 else if (Subtarget->isPICStyleGOT())
6261 OpFlag = X86II::MO_GOTOFF;
6262 else if (Subtarget->isPICStyleStubPIC())
6263 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6265 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6267 CP->getOffset(), OpFlag);
6268 DebugLoc DL = CP->getDebugLoc();
6269 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6270 // With PIC, the address is actually $g + Offset.
6272 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6273 DAG.getNode(X86ISD::GlobalBaseReg,
6274 DebugLoc(), getPointerTy()),
6281 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6282 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6284 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6286 unsigned char OpFlag = 0;
6287 unsigned WrapperKind = X86ISD::Wrapper;
6288 CodeModel::Model M = getTargetMachine().getCodeModel();
6290 if (Subtarget->isPICStyleRIPRel() &&
6291 (M == CodeModel::Small || M == CodeModel::Kernel))
6292 WrapperKind = X86ISD::WrapperRIP;
6293 else if (Subtarget->isPICStyleGOT())
6294 OpFlag = X86II::MO_GOTOFF;
6295 else if (Subtarget->isPICStyleStubPIC())
6296 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6298 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6300 DebugLoc DL = JT->getDebugLoc();
6301 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6303 // With PIC, the address is actually $g + Offset.
6305 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6306 DAG.getNode(X86ISD::GlobalBaseReg,
6307 DebugLoc(), getPointerTy()),
6314 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6315 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6317 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6319 unsigned char OpFlag = 0;
6320 unsigned WrapperKind = X86ISD::Wrapper;
6321 CodeModel::Model M = getTargetMachine().getCodeModel();
6323 if (Subtarget->isPICStyleRIPRel() &&
6324 (M == CodeModel::Small || M == CodeModel::Kernel))
6325 WrapperKind = X86ISD::WrapperRIP;
6326 else if (Subtarget->isPICStyleGOT())
6327 OpFlag = X86II::MO_GOTOFF;
6328 else if (Subtarget->isPICStyleStubPIC())
6329 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6331 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6333 DebugLoc DL = Op.getDebugLoc();
6334 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6337 // With PIC, the address is actually $g + Offset.
6338 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6339 !Subtarget->is64Bit()) {
6340 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6341 DAG.getNode(X86ISD::GlobalBaseReg,
6342 DebugLoc(), getPointerTy()),
6350 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6351 // Create the TargetBlockAddressAddress node.
6352 unsigned char OpFlags =
6353 Subtarget->ClassifyBlockAddressReference();
6354 CodeModel::Model M = getTargetMachine().getCodeModel();
6355 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6356 DebugLoc dl = Op.getDebugLoc();
6357 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6358 /*isTarget=*/true, OpFlags);
6360 if (Subtarget->isPICStyleRIPRel() &&
6361 (M == CodeModel::Small || M == CodeModel::Kernel))
6362 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6364 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6366 // With PIC, the address is actually $g + Offset.
6367 if (isGlobalRelativeToPICBase(OpFlags)) {
6368 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6369 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6377 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6379 SelectionDAG &DAG) const {
6380 // Create the TargetGlobalAddress node, folding in the constant
6381 // offset if it is legal.
6382 unsigned char OpFlags =
6383 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6384 CodeModel::Model M = getTargetMachine().getCodeModel();
6386 if (OpFlags == X86II::MO_NO_FLAG &&
6387 X86::isOffsetSuitableForCodeModel(Offset, M)) {
6388 // A direct static reference to a global.
6389 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6392 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6395 if (Subtarget->isPICStyleRIPRel() &&
6396 (M == CodeModel::Small || M == CodeModel::Kernel))
6397 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6399 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6401 // With PIC, the address is actually $g + Offset.
6402 if (isGlobalRelativeToPICBase(OpFlags)) {
6403 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6404 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6408 // For globals that require a load from a stub to get the address, emit the
6410 if (isGlobalStubReference(OpFlags))
6411 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6412 MachinePointerInfo::getGOT(), false, false, 0);
6414 // If there was a non-zero offset that we didn't fold, create an explicit
6417 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6418 DAG.getConstant(Offset, getPointerTy()));
6424 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6425 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6426 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6427 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6431 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6432 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6433 unsigned char OperandFlags) {
6434 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6435 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6436 DebugLoc dl = GA->getDebugLoc();
6437 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6438 GA->getValueType(0),
6442 SDValue Ops[] = { Chain, TGA, *InFlag };
6443 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6445 SDValue Ops[] = { Chain, TGA };
6446 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6449 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6450 MFI->setAdjustsStack(true);
6452 SDValue Flag = Chain.getValue(1);
6453 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6456 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6458 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6461 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6462 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6463 DAG.getNode(X86ISD::GlobalBaseReg,
6464 DebugLoc(), PtrVT), InFlag);
6465 InFlag = Chain.getValue(1);
6467 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6470 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6472 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6474 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6475 X86::RAX, X86II::MO_TLSGD);
6478 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6479 // "local exec" model.
6480 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6481 const EVT PtrVT, TLSModel::Model model,
6483 DebugLoc dl = GA->getDebugLoc();
6485 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6486 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6487 is64Bit ? 257 : 256));
6489 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6490 DAG.getIntPtrConstant(0),
6491 MachinePointerInfo(Ptr), false, false, 0);
6493 unsigned char OperandFlags = 0;
6494 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6496 unsigned WrapperKind = X86ISD::Wrapper;
6497 if (model == TLSModel::LocalExec) {
6498 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6499 } else if (is64Bit) {
6500 assert(model == TLSModel::InitialExec);
6501 OperandFlags = X86II::MO_GOTTPOFF;
6502 WrapperKind = X86ISD::WrapperRIP;
6504 assert(model == TLSModel::InitialExec);
6505 OperandFlags = X86II::MO_INDNTPOFF;
6508 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6510 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6511 GA->getValueType(0),
6512 GA->getOffset(), OperandFlags);
6513 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6515 if (model == TLSModel::InitialExec)
6516 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6517 MachinePointerInfo::getGOT(), false, false, 0);
6519 // The address of the thread local variable is the add of the thread
6520 // pointer with the offset of the variable.
6521 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6525 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6527 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6528 const GlobalValue *GV = GA->getGlobal();
6530 if (Subtarget->isTargetELF()) {
6531 // TODO: implement the "local dynamic" model
6532 // TODO: implement the "initial exec"model for pic executables
6534 // If GV is an alias then use the aliasee for determining
6535 // thread-localness.
6536 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6537 GV = GA->resolveAliasedGlobal(false);
6539 TLSModel::Model model
6540 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6543 case TLSModel::GeneralDynamic:
6544 case TLSModel::LocalDynamic: // not implemented
6545 if (Subtarget->is64Bit())
6546 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6547 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6549 case TLSModel::InitialExec:
6550 case TLSModel::LocalExec:
6551 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6552 Subtarget->is64Bit());
6554 } else if (Subtarget->isTargetDarwin()) {
6555 // Darwin only has one model of TLS. Lower to that.
6556 unsigned char OpFlag = 0;
6557 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6558 X86ISD::WrapperRIP : X86ISD::Wrapper;
6560 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6562 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6563 !Subtarget->is64Bit();
6565 OpFlag = X86II::MO_TLVP_PIC_BASE;
6567 OpFlag = X86II::MO_TLVP;
6568 DebugLoc DL = Op.getDebugLoc();
6569 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6570 GA->getValueType(0),
6571 GA->getOffset(), OpFlag);
6572 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6574 // With PIC32, the address is actually $g + Offset.
6576 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6577 DAG.getNode(X86ISD::GlobalBaseReg,
6578 DebugLoc(), getPointerTy()),
6581 // Lowering the machine isd will make sure everything is in the right
6583 SDValue Chain = DAG.getEntryNode();
6584 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6585 SDValue Args[] = { Chain, Offset };
6586 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6588 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6589 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6590 MFI->setAdjustsStack(true);
6592 // And our return value (tls address) is in the standard call return value
6594 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6595 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6599 "TLS not implemented for this target.");
6601 llvm_unreachable("Unreachable");
6606 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6607 /// take a 2 x i32 value to shift plus a shift amount.
6608 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6609 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6610 EVT VT = Op.getValueType();
6611 unsigned VTBits = VT.getSizeInBits();
6612 DebugLoc dl = Op.getDebugLoc();
6613 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6614 SDValue ShOpLo = Op.getOperand(0);
6615 SDValue ShOpHi = Op.getOperand(1);
6616 SDValue ShAmt = Op.getOperand(2);
6617 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6618 DAG.getConstant(VTBits - 1, MVT::i8))
6619 : DAG.getConstant(0, VT);
6622 if (Op.getOpcode() == ISD::SHL_PARTS) {
6623 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6624 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6626 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6627 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6630 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6631 DAG.getConstant(VTBits, MVT::i8));
6632 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6633 AndNode, DAG.getConstant(0, MVT::i8));
6636 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6637 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6638 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6640 if (Op.getOpcode() == ISD::SHL_PARTS) {
6641 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6642 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6644 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6645 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6648 SDValue Ops[2] = { Lo, Hi };
6649 return DAG.getMergeValues(Ops, 2, dl);
6652 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6653 SelectionDAG &DAG) const {
6654 EVT SrcVT = Op.getOperand(0).getValueType();
6656 if (SrcVT.isVector())
6659 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6660 "Unknown SINT_TO_FP to lower!");
6662 // These are really Legal; return the operand so the caller accepts it as
6664 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6666 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6667 Subtarget->is64Bit()) {
6671 DebugLoc dl = Op.getDebugLoc();
6672 unsigned Size = SrcVT.getSizeInBits()/8;
6673 MachineFunction &MF = DAG.getMachineFunction();
6674 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6675 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6676 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6678 MachinePointerInfo::getFixedStack(SSFI),
6680 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6683 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6685 SelectionDAG &DAG) const {
6687 DebugLoc DL = Op.getDebugLoc();
6689 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6691 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6693 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6695 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6697 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6698 MachineMemOperand *MMO =
6699 DAG.getMachineFunction()
6700 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6701 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6703 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6704 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6706 Tys, Ops, array_lengthof(Ops),
6710 Chain = Result.getValue(1);
6711 SDValue InFlag = Result.getValue(2);
6713 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6714 // shouldn't be necessary except that RFP cannot be live across
6715 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6716 MachineFunction &MF = DAG.getMachineFunction();
6717 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6718 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6719 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6720 Tys = DAG.getVTList(MVT::Other);
6722 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6724 MachineMemOperand *MMO =
6725 DAG.getMachineFunction()
6726 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6727 MachineMemOperand::MOStore, SSFISize, SSFISize);
6729 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6730 Ops, array_lengthof(Ops),
6731 Op.getValueType(), MMO);
6732 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6733 MachinePointerInfo::getFixedStack(SSFI),
6740 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6741 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6742 SelectionDAG &DAG) const {
6743 // This algorithm is not obvious. Here it is in C code, more or less:
6745 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6746 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6747 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6749 // Copy ints to xmm registers.
6750 __m128i xh = _mm_cvtsi32_si128( hi );
6751 __m128i xl = _mm_cvtsi32_si128( lo );
6753 // Combine into low half of a single xmm register.
6754 __m128i x = _mm_unpacklo_epi32( xh, xl );
6758 // Merge in appropriate exponents to give the integer bits the right
6760 x = _mm_unpacklo_epi32( x, exp );
6762 // Subtract away the biases to deal with the IEEE-754 double precision
6764 d = _mm_sub_pd( (__m128d) x, bias );
6766 // All conversions up to here are exact. The correctly rounded result is
6767 // calculated using the current rounding mode using the following
6769 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6770 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6771 // store doesn't really need to be here (except
6772 // maybe to zero the other double)
6777 DebugLoc dl = Op.getDebugLoc();
6778 LLVMContext *Context = DAG.getContext();
6780 // Build some magic constants.
6781 std::vector<Constant*> CV0;
6782 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6783 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6784 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6785 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6786 Constant *C0 = ConstantVector::get(CV0);
6787 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6789 std::vector<Constant*> CV1;
6791 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6793 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6794 Constant *C1 = ConstantVector::get(CV1);
6795 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6797 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6798 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6800 DAG.getIntPtrConstant(1)));
6801 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6802 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6804 DAG.getIntPtrConstant(0)));
6805 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6806 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6807 MachinePointerInfo::getConstantPool(),
6809 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6810 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6811 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6812 MachinePointerInfo::getConstantPool(),
6814 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6816 // Add the halves; easiest way is to swap them into another reg first.
6817 int ShufMask[2] = { 1, -1 };
6818 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6819 DAG.getUNDEF(MVT::v2f64), ShufMask);
6820 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6821 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6822 DAG.getIntPtrConstant(0));
6825 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6826 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6827 SelectionDAG &DAG) const {
6828 DebugLoc dl = Op.getDebugLoc();
6829 // FP constant to bias correct the final result.
6830 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6833 // Load the 32-bit value into an XMM register.
6834 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6835 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6837 DAG.getIntPtrConstant(0)));
6839 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6840 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6841 DAG.getIntPtrConstant(0));
6843 // Or the load with the bias.
6844 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6845 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6846 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6848 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6849 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6850 MVT::v2f64, Bias)));
6851 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6852 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6853 DAG.getIntPtrConstant(0));
6855 // Subtract the bias.
6856 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6858 // Handle final rounding.
6859 EVT DestVT = Op.getValueType();
6861 if (DestVT.bitsLT(MVT::f64)) {
6862 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6863 DAG.getIntPtrConstant(0));
6864 } else if (DestVT.bitsGT(MVT::f64)) {
6865 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6868 // Handle final rounding.
6872 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6873 SelectionDAG &DAG) const {
6874 SDValue N0 = Op.getOperand(0);
6875 DebugLoc dl = Op.getDebugLoc();
6877 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6878 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6879 // the optimization here.
6880 if (DAG.SignBitIsZero(N0))
6881 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6883 EVT SrcVT = N0.getValueType();
6884 EVT DstVT = Op.getValueType();
6885 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6886 return LowerUINT_TO_FP_i64(Op, DAG);
6887 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6888 return LowerUINT_TO_FP_i32(Op, DAG);
6890 // Make a 64-bit buffer, and use it to build an FILD.
6891 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6892 if (SrcVT == MVT::i32) {
6893 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6894 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6895 getPointerTy(), StackSlot, WordOff);
6896 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6897 StackSlot, MachinePointerInfo(),
6899 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6900 OffsetSlot, MachinePointerInfo(),
6902 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6906 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6907 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6908 StackSlot, MachinePointerInfo(),
6910 // For i64 source, we need to add the appropriate power of 2 if the input
6911 // was negative. This is the same as the optimization in
6912 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6913 // we must be careful to do the computation in x87 extended precision, not
6914 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6915 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6916 MachineMemOperand *MMO =
6917 DAG.getMachineFunction()
6918 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6919 MachineMemOperand::MOLoad, 8, 8);
6921 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6922 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6923 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6926 APInt FF(32, 0x5F800000ULL);
6928 // Check whether the sign bit is set.
6929 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6930 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6933 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6934 SDValue FudgePtr = DAG.getConstantPool(
6935 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6938 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6939 SDValue Zero = DAG.getIntPtrConstant(0);
6940 SDValue Four = DAG.getIntPtrConstant(4);
6941 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6943 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6945 // Load the value out, extending it from f32 to f80.
6946 // FIXME: Avoid the extend by constructing the right constant pool?
6947 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
6948 FudgePtr, MachinePointerInfo::getConstantPool(),
6949 MVT::f32, false, false, 4);
6950 // Extend everything to 80 bits to force it to be done on x87.
6951 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6952 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6955 std::pair<SDValue,SDValue> X86TargetLowering::
6956 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6957 DebugLoc DL = Op.getDebugLoc();
6959 EVT DstTy = Op.getValueType();
6962 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6966 assert(DstTy.getSimpleVT() <= MVT::i64 &&
6967 DstTy.getSimpleVT() >= MVT::i16 &&
6968 "Unknown FP_TO_SINT to lower!");
6970 // These are really Legal.
6971 if (DstTy == MVT::i32 &&
6972 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6973 return std::make_pair(SDValue(), SDValue());
6974 if (Subtarget->is64Bit() &&
6975 DstTy == MVT::i64 &&
6976 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6977 return std::make_pair(SDValue(), SDValue());
6979 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6981 MachineFunction &MF = DAG.getMachineFunction();
6982 unsigned MemSize = DstTy.getSizeInBits()/8;
6983 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6984 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6989 switch (DstTy.getSimpleVT().SimpleTy) {
6990 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6991 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6992 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6993 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6996 SDValue Chain = DAG.getEntryNode();
6997 SDValue Value = Op.getOperand(0);
6998 EVT TheVT = Op.getOperand(0).getValueType();
6999 if (isScalarFPTypeInSSEReg(TheVT)) {
7000 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7001 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7002 MachinePointerInfo::getFixedStack(SSFI),
7004 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7006 Chain, StackSlot, DAG.getValueType(TheVT)
7009 MachineMemOperand *MMO =
7010 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7011 MachineMemOperand::MOLoad, MemSize, MemSize);
7012 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7014 Chain = Value.getValue(1);
7015 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7016 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7019 MachineMemOperand *MMO =
7020 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7021 MachineMemOperand::MOStore, MemSize, MemSize);
7023 // Build the FP_TO_INT*_IN_MEM
7024 SDValue Ops[] = { Chain, Value, StackSlot };
7025 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7026 Ops, 3, DstTy, MMO);
7028 return std::make_pair(FIST, StackSlot);
7031 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7032 SelectionDAG &DAG) const {
7033 if (Op.getValueType().isVector())
7036 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7037 SDValue FIST = Vals.first, StackSlot = Vals.second;
7038 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7039 if (FIST.getNode() == 0) return Op;
7042 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7043 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7046 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7047 SelectionDAG &DAG) const {
7048 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7049 SDValue FIST = Vals.first, StackSlot = Vals.second;
7050 assert(FIST.getNode() && "Unexpected failure");
7053 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7054 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7057 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7058 SelectionDAG &DAG) const {
7059 LLVMContext *Context = DAG.getContext();
7060 DebugLoc dl = Op.getDebugLoc();
7061 EVT VT = Op.getValueType();
7064 EltVT = VT.getVectorElementType();
7065 std::vector<Constant*> CV;
7066 if (EltVT == MVT::f64) {
7067 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7071 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7077 Constant *C = ConstantVector::get(CV);
7078 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7079 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7080 MachinePointerInfo::getConstantPool(),
7082 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7085 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7086 LLVMContext *Context = DAG.getContext();
7087 DebugLoc dl = Op.getDebugLoc();
7088 EVT VT = Op.getValueType();
7091 EltVT = VT.getVectorElementType();
7092 std::vector<Constant*> CV;
7093 if (EltVT == MVT::f64) {
7094 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7098 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7104 Constant *C = ConstantVector::get(CV);
7105 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7106 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7107 MachinePointerInfo::getConstantPool(),
7109 if (VT.isVector()) {
7110 return DAG.getNode(ISD::BITCAST, dl, VT,
7111 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7112 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7114 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7116 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7120 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7121 LLVMContext *Context = DAG.getContext();
7122 SDValue Op0 = Op.getOperand(0);
7123 SDValue Op1 = Op.getOperand(1);
7124 DebugLoc dl = Op.getDebugLoc();
7125 EVT VT = Op.getValueType();
7126 EVT SrcVT = Op1.getValueType();
7128 // If second operand is smaller, extend it first.
7129 if (SrcVT.bitsLT(VT)) {
7130 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7133 // And if it is bigger, shrink it first.
7134 if (SrcVT.bitsGT(VT)) {
7135 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7139 // At this point the operands and the result should have the same
7140 // type, and that won't be f80 since that is not custom lowered.
7142 // First get the sign bit of second operand.
7143 std::vector<Constant*> CV;
7144 if (SrcVT == MVT::f64) {
7145 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7146 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7148 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7149 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7150 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7151 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7153 Constant *C = ConstantVector::get(CV);
7154 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7155 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7156 MachinePointerInfo::getConstantPool(),
7158 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7160 // Shift sign bit right or left if the two operands have different types.
7161 if (SrcVT.bitsGT(VT)) {
7162 // Op0 is MVT::f32, Op1 is MVT::f64.
7163 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7164 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7165 DAG.getConstant(32, MVT::i32));
7166 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7167 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7168 DAG.getIntPtrConstant(0));
7171 // Clear first operand sign bit.
7173 if (VT == MVT::f64) {
7174 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7175 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7177 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7178 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7179 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7180 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7182 C = ConstantVector::get(CV);
7183 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7184 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7185 MachinePointerInfo::getConstantPool(),
7187 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7189 // Or the value with the sign bit.
7190 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7193 /// Emit nodes that will be selected as "test Op0,Op0", or something
7195 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7196 SelectionDAG &DAG) const {
7197 DebugLoc dl = Op.getDebugLoc();
7199 // CF and OF aren't always set the way we want. Determine which
7200 // of these we need.
7201 bool NeedCF = false;
7202 bool NeedOF = false;
7205 case X86::COND_A: case X86::COND_AE:
7206 case X86::COND_B: case X86::COND_BE:
7209 case X86::COND_G: case X86::COND_GE:
7210 case X86::COND_L: case X86::COND_LE:
7211 case X86::COND_O: case X86::COND_NO:
7216 // See if we can use the EFLAGS value from the operand instead of
7217 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7218 // we prove that the arithmetic won't overflow, we can't use OF or CF.
7219 if (Op.getResNo() != 0 || NeedOF || NeedCF)
7220 // Emit a CMP with 0, which is the TEST pattern.
7221 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7222 DAG.getConstant(0, Op.getValueType()));
7224 unsigned Opcode = 0;
7225 unsigned NumOperands = 0;
7226 switch (Op.getNode()->getOpcode()) {
7228 // Due to an isel shortcoming, be conservative if this add is likely to be
7229 // selected as part of a load-modify-store instruction. When the root node
7230 // in a match is a store, isel doesn't know how to remap non-chain non-flag
7231 // uses of other nodes in the match, such as the ADD in this case. This
7232 // leads to the ADD being left around and reselected, with the result being
7233 // two adds in the output. Alas, even if none our users are stores, that
7234 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
7235 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
7236 // climbing the DAG back to the root, and it doesn't seem to be worth the
7238 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7239 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7240 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7243 if (ConstantSDNode *C =
7244 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7245 // An add of one will be selected as an INC.
7246 if (C->getAPIntValue() == 1) {
7247 Opcode = X86ISD::INC;
7252 // An add of negative one (subtract of one) will be selected as a DEC.
7253 if (C->getAPIntValue().isAllOnesValue()) {
7254 Opcode = X86ISD::DEC;
7260 // Otherwise use a regular EFLAGS-setting add.
7261 Opcode = X86ISD::ADD;
7265 // If the primary and result isn't used, don't bother using X86ISD::AND,
7266 // because a TEST instruction will be better.
7267 bool NonFlagUse = false;
7268 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7269 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7271 unsigned UOpNo = UI.getOperandNo();
7272 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7273 // Look pass truncate.
7274 UOpNo = User->use_begin().getOperandNo();
7275 User = *User->use_begin();
7278 if (User->getOpcode() != ISD::BRCOND &&
7279 User->getOpcode() != ISD::SETCC &&
7280 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7293 // Due to the ISEL shortcoming noted above, be conservative if this op is
7294 // likely to be selected as part of a load-modify-store instruction.
7295 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7296 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7297 if (UI->getOpcode() == ISD::STORE)
7300 // Otherwise use a regular EFLAGS-setting instruction.
7301 switch (Op.getNode()->getOpcode()) {
7302 default: llvm_unreachable("unexpected operator!");
7303 case ISD::SUB: Opcode = X86ISD::SUB; break;
7304 case ISD::OR: Opcode = X86ISD::OR; break;
7305 case ISD::XOR: Opcode = X86ISD::XOR; break;
7306 case ISD::AND: Opcode = X86ISD::AND; break;
7318 return SDValue(Op.getNode(), 1);
7325 // Emit a CMP with 0, which is the TEST pattern.
7326 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7327 DAG.getConstant(0, Op.getValueType()));
7329 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7330 SmallVector<SDValue, 4> Ops;
7331 for (unsigned i = 0; i != NumOperands; ++i)
7332 Ops.push_back(Op.getOperand(i));
7334 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7335 DAG.ReplaceAllUsesWith(Op, New);
7336 return SDValue(New.getNode(), 1);
7339 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7341 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7342 SelectionDAG &DAG) const {
7343 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7344 if (C->getAPIntValue() == 0)
7345 return EmitTest(Op0, X86CC, DAG);
7347 DebugLoc dl = Op0.getDebugLoc();
7348 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7351 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7352 /// if it's possible.
7353 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7354 DebugLoc dl, SelectionDAG &DAG) const {
7355 SDValue Op0 = And.getOperand(0);
7356 SDValue Op1 = And.getOperand(1);
7357 if (Op0.getOpcode() == ISD::TRUNCATE)
7358 Op0 = Op0.getOperand(0);
7359 if (Op1.getOpcode() == ISD::TRUNCATE)
7360 Op1 = Op1.getOperand(0);
7363 if (Op1.getOpcode() == ISD::SHL)
7364 std::swap(Op0, Op1);
7365 if (Op0.getOpcode() == ISD::SHL) {
7366 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7367 if (And00C->getZExtValue() == 1) {
7368 // If we looked past a truncate, check that it's only truncating away
7370 unsigned BitWidth = Op0.getValueSizeInBits();
7371 unsigned AndBitWidth = And.getValueSizeInBits();
7372 if (BitWidth > AndBitWidth) {
7373 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7374 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7375 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7379 RHS = Op0.getOperand(1);
7381 } else if (Op1.getOpcode() == ISD::Constant) {
7382 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7383 SDValue AndLHS = Op0;
7384 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7385 LHS = AndLHS.getOperand(0);
7386 RHS = AndLHS.getOperand(1);
7390 if (LHS.getNode()) {
7391 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
7392 // instruction. Since the shift amount is in-range-or-undefined, we know
7393 // that doing a bittest on the i32 value is ok. We extend to i32 because
7394 // the encoding for the i16 version is larger than the i32 version.
7395 // Also promote i16 to i32 for performance / code size reason.
7396 if (LHS.getValueType() == MVT::i8 ||
7397 LHS.getValueType() == MVT::i16)
7398 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7400 // If the operand types disagree, extend the shift amount to match. Since
7401 // BT ignores high bits (like shifts) we can use anyextend.
7402 if (LHS.getValueType() != RHS.getValueType())
7403 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7405 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7406 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7407 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7408 DAG.getConstant(Cond, MVT::i8), BT);
7414 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7415 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7416 SDValue Op0 = Op.getOperand(0);
7417 SDValue Op1 = Op.getOperand(1);
7418 DebugLoc dl = Op.getDebugLoc();
7419 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7421 // Optimize to BT if possible.
7422 // Lower (X & (1 << N)) == 0 to BT(X, N).
7423 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7424 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7425 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7426 Op1.getOpcode() == ISD::Constant &&
7427 cast<ConstantSDNode>(Op1)->isNullValue() &&
7428 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7429 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7430 if (NewSetCC.getNode())
7434 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
7436 if (Op1.getOpcode() == ISD::Constant &&
7437 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7438 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7439 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7441 // If the input is a setcc, then reuse the input setcc or use a new one with
7442 // the inverted condition.
7443 if (Op0.getOpcode() == X86ISD::SETCC) {
7444 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7445 bool Invert = (CC == ISD::SETNE) ^
7446 cast<ConstantSDNode>(Op1)->isNullValue();
7447 if (!Invert) return Op0;
7449 CCode = X86::GetOppositeBranchCondition(CCode);
7450 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7451 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7455 bool isFP = Op1.getValueType().isFloatingPoint();
7456 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7457 if (X86CC == X86::COND_INVALID)
7460 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7461 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7462 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7465 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7467 SDValue Op0 = Op.getOperand(0);
7468 SDValue Op1 = Op.getOperand(1);
7469 SDValue CC = Op.getOperand(2);
7470 EVT VT = Op.getValueType();
7471 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7472 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7473 DebugLoc dl = Op.getDebugLoc();
7477 EVT VT0 = Op0.getValueType();
7478 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7479 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7482 switch (SetCCOpcode) {
7485 case ISD::SETEQ: SSECC = 0; break;
7487 case ISD::SETGT: Swap = true; // Fallthrough
7489 case ISD::SETOLT: SSECC = 1; break;
7491 case ISD::SETGE: Swap = true; // Fallthrough
7493 case ISD::SETOLE: SSECC = 2; break;
7494 case ISD::SETUO: SSECC = 3; break;
7496 case ISD::SETNE: SSECC = 4; break;
7497 case ISD::SETULE: Swap = true;
7498 case ISD::SETUGE: SSECC = 5; break;
7499 case ISD::SETULT: Swap = true;
7500 case ISD::SETUGT: SSECC = 6; break;
7501 case ISD::SETO: SSECC = 7; break;
7504 std::swap(Op0, Op1);
7506 // In the two special cases we can't handle, emit two comparisons.
7508 if (SetCCOpcode == ISD::SETUEQ) {
7510 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7511 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7512 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7514 else if (SetCCOpcode == ISD::SETONE) {
7516 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7517 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7518 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7520 llvm_unreachable("Illegal FP comparison");
7522 // Handle all other FP comparisons here.
7523 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7526 // We are handling one of the integer comparisons here. Since SSE only has
7527 // GT and EQ comparisons for integer, swapping operands and multiple
7528 // operations may be required for some comparisons.
7529 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7530 bool Swap = false, Invert = false, FlipSigns = false;
7532 switch (VT.getSimpleVT().SimpleTy) {
7534 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7535 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7536 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7537 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7540 switch (SetCCOpcode) {
7542 case ISD::SETNE: Invert = true;
7543 case ISD::SETEQ: Opc = EQOpc; break;
7544 case ISD::SETLT: Swap = true;
7545 case ISD::SETGT: Opc = GTOpc; break;
7546 case ISD::SETGE: Swap = true;
7547 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7548 case ISD::SETULT: Swap = true;
7549 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7550 case ISD::SETUGE: Swap = true;
7551 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7554 std::swap(Op0, Op1);
7556 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7557 // bits of the inputs before performing those operations.
7559 EVT EltVT = VT.getVectorElementType();
7560 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7562 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7563 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7565 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7566 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7569 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7571 // If the logical-not of the result is required, perform that now.
7573 Result = DAG.getNOT(dl, Result, VT);
7578 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7579 static bool isX86LogicalCmp(SDValue Op) {
7580 unsigned Opc = Op.getNode()->getOpcode();
7581 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7583 if (Op.getResNo() == 1 &&
7584 (Opc == X86ISD::ADD ||
7585 Opc == X86ISD::SUB ||
7586 Opc == X86ISD::ADC ||
7587 Opc == X86ISD::SBB ||
7588 Opc == X86ISD::SMUL ||
7589 Opc == X86ISD::UMUL ||
7590 Opc == X86ISD::INC ||
7591 Opc == X86ISD::DEC ||
7592 Opc == X86ISD::OR ||
7593 Opc == X86ISD::XOR ||
7594 Opc == X86ISD::AND))
7597 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7603 static bool isZero(SDValue V) {
7604 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7605 return C && C->isNullValue();
7608 static bool isAllOnes(SDValue V) {
7609 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7610 return C && C->isAllOnesValue();
7613 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7614 bool addTest = true;
7615 SDValue Cond = Op.getOperand(0);
7616 SDValue Op1 = Op.getOperand(1);
7617 SDValue Op2 = Op.getOperand(2);
7618 DebugLoc DL = Op.getDebugLoc();
7621 if (Cond.getOpcode() == ISD::SETCC) {
7622 SDValue NewCond = LowerSETCC(Cond, DAG);
7623 if (NewCond.getNode())
7627 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7628 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7629 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7630 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7631 if (Cond.getOpcode() == X86ISD::SETCC &&
7632 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7633 isZero(Cond.getOperand(1).getOperand(1))) {
7634 SDValue Cmp = Cond.getOperand(1);
7636 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7638 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7639 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7640 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7642 SDValue CmpOp0 = Cmp.getOperand(0);
7643 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7644 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7646 SDValue Res = // Res = 0 or -1.
7647 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7648 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7650 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7651 Res = DAG.getNOT(DL, Res, Res.getValueType());
7653 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7654 if (N2C == 0 || !N2C->isNullValue())
7655 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7660 // Look past (and (setcc_carry (cmp ...)), 1).
7661 if (Cond.getOpcode() == ISD::AND &&
7662 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7663 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7664 if (C && C->getAPIntValue() == 1)
7665 Cond = Cond.getOperand(0);
7668 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7669 // setting operand in place of the X86ISD::SETCC.
7670 if (Cond.getOpcode() == X86ISD::SETCC ||
7671 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7672 CC = Cond.getOperand(0);
7674 SDValue Cmp = Cond.getOperand(1);
7675 unsigned Opc = Cmp.getOpcode();
7676 EVT VT = Op.getValueType();
7678 bool IllegalFPCMov = false;
7679 if (VT.isFloatingPoint() && !VT.isVector() &&
7680 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7681 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7683 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7684 Opc == X86ISD::BT) { // FIXME
7691 // Look pass the truncate.
7692 if (Cond.getOpcode() == ISD::TRUNCATE)
7693 Cond = Cond.getOperand(0);
7695 // We know the result of AND is compared against zero. Try to match
7697 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7698 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7699 if (NewSetCC.getNode()) {
7700 CC = NewSetCC.getOperand(0);
7701 Cond = NewSetCC.getOperand(1);
7708 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7709 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7712 // a < b ? -1 : 0 -> RES = ~setcc_carry
7713 // a < b ? 0 : -1 -> RES = setcc_carry
7714 // a >= b ? -1 : 0 -> RES = setcc_carry
7715 // a >= b ? 0 : -1 -> RES = ~setcc_carry
7716 if (Cond.getOpcode() == X86ISD::CMP) {
7717 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7719 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7720 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7721 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7722 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7723 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7724 return DAG.getNOT(DL, Res, Res.getValueType());
7729 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7730 // condition is true.
7731 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7732 SDValue Ops[] = { Op2, Op1, CC, Cond };
7733 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7736 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7737 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7738 // from the AND / OR.
7739 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7740 Opc = Op.getOpcode();
7741 if (Opc != ISD::OR && Opc != ISD::AND)
7743 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7744 Op.getOperand(0).hasOneUse() &&
7745 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7746 Op.getOperand(1).hasOneUse());
7749 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7750 // 1 and that the SETCC node has a single use.
7751 static bool isXor1OfSetCC(SDValue Op) {
7752 if (Op.getOpcode() != ISD::XOR)
7754 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7755 if (N1C && N1C->getAPIntValue() == 1) {
7756 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7757 Op.getOperand(0).hasOneUse();
7762 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7763 bool addTest = true;
7764 SDValue Chain = Op.getOperand(0);
7765 SDValue Cond = Op.getOperand(1);
7766 SDValue Dest = Op.getOperand(2);
7767 DebugLoc dl = Op.getDebugLoc();
7770 if (Cond.getOpcode() == ISD::SETCC) {
7771 SDValue NewCond = LowerSETCC(Cond, DAG);
7772 if (NewCond.getNode())
7776 // FIXME: LowerXALUO doesn't handle these!!
7777 else if (Cond.getOpcode() == X86ISD::ADD ||
7778 Cond.getOpcode() == X86ISD::SUB ||
7779 Cond.getOpcode() == X86ISD::SMUL ||
7780 Cond.getOpcode() == X86ISD::UMUL)
7781 Cond = LowerXALUO(Cond, DAG);
7784 // Look pass (and (setcc_carry (cmp ...)), 1).
7785 if (Cond.getOpcode() == ISD::AND &&
7786 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7787 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7788 if (C && C->getAPIntValue() == 1)
7789 Cond = Cond.getOperand(0);
7792 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7793 // setting operand in place of the X86ISD::SETCC.
7794 if (Cond.getOpcode() == X86ISD::SETCC ||
7795 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7796 CC = Cond.getOperand(0);
7798 SDValue Cmp = Cond.getOperand(1);
7799 unsigned Opc = Cmp.getOpcode();
7800 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7801 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7805 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7809 // These can only come from an arithmetic instruction with overflow,
7810 // e.g. SADDO, UADDO.
7811 Cond = Cond.getNode()->getOperand(1);
7818 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7819 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7820 if (CondOpc == ISD::OR) {
7821 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7822 // two branches instead of an explicit OR instruction with a
7824 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7825 isX86LogicalCmp(Cmp)) {
7826 CC = Cond.getOperand(0).getOperand(0);
7827 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7828 Chain, Dest, CC, Cmp);
7829 CC = Cond.getOperand(1).getOperand(0);
7833 } else { // ISD::AND
7834 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7835 // two branches instead of an explicit AND instruction with a
7836 // separate test. However, we only do this if this block doesn't
7837 // have a fall-through edge, because this requires an explicit
7838 // jmp when the condition is false.
7839 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7840 isX86LogicalCmp(Cmp) &&
7841 Op.getNode()->hasOneUse()) {
7842 X86::CondCode CCode =
7843 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7844 CCode = X86::GetOppositeBranchCondition(CCode);
7845 CC = DAG.getConstant(CCode, MVT::i8);
7846 SDNode *User = *Op.getNode()->use_begin();
7847 // Look for an unconditional branch following this conditional branch.
7848 // We need this because we need to reverse the successors in order
7849 // to implement FCMP_OEQ.
7850 if (User->getOpcode() == ISD::BR) {
7851 SDValue FalseBB = User->getOperand(1);
7853 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7854 assert(NewBR == User);
7858 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7859 Chain, Dest, CC, Cmp);
7860 X86::CondCode CCode =
7861 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7862 CCode = X86::GetOppositeBranchCondition(CCode);
7863 CC = DAG.getConstant(CCode, MVT::i8);
7869 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7870 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7871 // It should be transformed during dag combiner except when the condition
7872 // is set by a arithmetics with overflow node.
7873 X86::CondCode CCode =
7874 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7875 CCode = X86::GetOppositeBranchCondition(CCode);
7876 CC = DAG.getConstant(CCode, MVT::i8);
7877 Cond = Cond.getOperand(0).getOperand(1);
7883 // Look pass the truncate.
7884 if (Cond.getOpcode() == ISD::TRUNCATE)
7885 Cond = Cond.getOperand(0);
7887 // We know the result of AND is compared against zero. Try to match
7889 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7890 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7891 if (NewSetCC.getNode()) {
7892 CC = NewSetCC.getOperand(0);
7893 Cond = NewSetCC.getOperand(1);
7900 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7901 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7903 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7904 Chain, Dest, CC, Cond);
7908 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7909 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7910 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7911 // that the guard pages used by the OS virtual memory manager are allocated in
7912 // correct sequence.
7914 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7915 SelectionDAG &DAG) const {
7916 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7917 "This should be used only on Windows targets");
7918 DebugLoc dl = Op.getDebugLoc();
7921 SDValue Chain = Op.getOperand(0);
7922 SDValue Size = Op.getOperand(1);
7923 // FIXME: Ensure alignment here
7927 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7929 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7930 Flag = Chain.getValue(1);
7932 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7934 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7935 Flag = Chain.getValue(1);
7937 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7939 SDValue Ops1[2] = { Chain.getValue(0), Chain };
7940 return DAG.getMergeValues(Ops1, 2, dl);
7943 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7944 MachineFunction &MF = DAG.getMachineFunction();
7945 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7947 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7948 DebugLoc DL = Op.getDebugLoc();
7950 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7951 // vastart just stores the address of the VarArgsFrameIndex slot into the
7952 // memory location argument.
7953 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7955 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7956 MachinePointerInfo(SV), false, false, 0);
7960 // gp_offset (0 - 6 * 8)
7961 // fp_offset (48 - 48 + 8 * 16)
7962 // overflow_arg_area (point to parameters coming in memory).
7964 SmallVector<SDValue, 8> MemOps;
7965 SDValue FIN = Op.getOperand(1);
7967 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7968 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7970 FIN, MachinePointerInfo(SV), false, false, 0);
7971 MemOps.push_back(Store);
7974 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7975 FIN, DAG.getIntPtrConstant(4));
7976 Store = DAG.getStore(Op.getOperand(0), DL,
7977 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7979 FIN, MachinePointerInfo(SV, 4), false, false, 0);
7980 MemOps.push_back(Store);
7982 // Store ptr to overflow_arg_area
7983 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7984 FIN, DAG.getIntPtrConstant(4));
7985 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7987 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7988 MachinePointerInfo(SV, 8),
7990 MemOps.push_back(Store);
7992 // Store ptr to reg_save_area.
7993 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7994 FIN, DAG.getIntPtrConstant(8));
7995 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7997 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7998 MachinePointerInfo(SV, 16), false, false, 0);
7999 MemOps.push_back(Store);
8000 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8001 &MemOps[0], MemOps.size());
8004 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8005 assert(Subtarget->is64Bit() &&
8006 "LowerVAARG only handles 64-bit va_arg!");
8007 assert((Subtarget->isTargetLinux() ||
8008 Subtarget->isTargetDarwin()) &&
8009 "Unhandled target in LowerVAARG");
8010 assert(Op.getNode()->getNumOperands() == 4);
8011 SDValue Chain = Op.getOperand(0);
8012 SDValue SrcPtr = Op.getOperand(1);
8013 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8014 unsigned Align = Op.getConstantOperandVal(3);
8015 DebugLoc dl = Op.getDebugLoc();
8017 EVT ArgVT = Op.getNode()->getValueType(0);
8018 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8019 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8022 // Decide which area this value should be read from.
8023 // TODO: Implement the AMD64 ABI in its entirety. This simple
8024 // selection mechanism works only for the basic types.
8025 if (ArgVT == MVT::f80) {
8026 llvm_unreachable("va_arg for f80 not yet implemented");
8027 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8028 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
8029 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8030 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
8032 llvm_unreachable("Unhandled argument type in LowerVAARG");
8036 // Sanity Check: Make sure using fp_offset makes sense.
8037 assert(!UseSoftFloat &&
8038 !(DAG.getMachineFunction()
8039 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8040 Subtarget->hasXMM());
8043 // Insert VAARG_64 node into the DAG
8044 // VAARG_64 returns two values: Variable Argument Address, Chain
8045 SmallVector<SDValue, 11> InstOps;
8046 InstOps.push_back(Chain);
8047 InstOps.push_back(SrcPtr);
8048 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8049 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8050 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8051 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8052 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8053 VTs, &InstOps[0], InstOps.size(),
8055 MachinePointerInfo(SV),
8060 Chain = VAARG.getValue(1);
8062 // Load the next argument and return it
8063 return DAG.getLoad(ArgVT, dl,
8066 MachinePointerInfo(),
8070 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8071 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8072 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8073 SDValue Chain = Op.getOperand(0);
8074 SDValue DstPtr = Op.getOperand(1);
8075 SDValue SrcPtr = Op.getOperand(2);
8076 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8077 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8078 DebugLoc DL = Op.getDebugLoc();
8080 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8081 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8083 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8087 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8088 DebugLoc dl = Op.getDebugLoc();
8089 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8091 default: return SDValue(); // Don't custom lower most intrinsics.
8092 // Comparison intrinsics.
8093 case Intrinsic::x86_sse_comieq_ss:
8094 case Intrinsic::x86_sse_comilt_ss:
8095 case Intrinsic::x86_sse_comile_ss:
8096 case Intrinsic::x86_sse_comigt_ss:
8097 case Intrinsic::x86_sse_comige_ss:
8098 case Intrinsic::x86_sse_comineq_ss:
8099 case Intrinsic::x86_sse_ucomieq_ss:
8100 case Intrinsic::x86_sse_ucomilt_ss:
8101 case Intrinsic::x86_sse_ucomile_ss:
8102 case Intrinsic::x86_sse_ucomigt_ss:
8103 case Intrinsic::x86_sse_ucomige_ss:
8104 case Intrinsic::x86_sse_ucomineq_ss:
8105 case Intrinsic::x86_sse2_comieq_sd:
8106 case Intrinsic::x86_sse2_comilt_sd:
8107 case Intrinsic::x86_sse2_comile_sd:
8108 case Intrinsic::x86_sse2_comigt_sd:
8109 case Intrinsic::x86_sse2_comige_sd:
8110 case Intrinsic::x86_sse2_comineq_sd:
8111 case Intrinsic::x86_sse2_ucomieq_sd:
8112 case Intrinsic::x86_sse2_ucomilt_sd:
8113 case Intrinsic::x86_sse2_ucomile_sd:
8114 case Intrinsic::x86_sse2_ucomigt_sd:
8115 case Intrinsic::x86_sse2_ucomige_sd:
8116 case Intrinsic::x86_sse2_ucomineq_sd: {
8118 ISD::CondCode CC = ISD::SETCC_INVALID;
8121 case Intrinsic::x86_sse_comieq_ss:
8122 case Intrinsic::x86_sse2_comieq_sd:
8126 case Intrinsic::x86_sse_comilt_ss:
8127 case Intrinsic::x86_sse2_comilt_sd:
8131 case Intrinsic::x86_sse_comile_ss:
8132 case Intrinsic::x86_sse2_comile_sd:
8136 case Intrinsic::x86_sse_comigt_ss:
8137 case Intrinsic::x86_sse2_comigt_sd:
8141 case Intrinsic::x86_sse_comige_ss:
8142 case Intrinsic::x86_sse2_comige_sd:
8146 case Intrinsic::x86_sse_comineq_ss:
8147 case Intrinsic::x86_sse2_comineq_sd:
8151 case Intrinsic::x86_sse_ucomieq_ss:
8152 case Intrinsic::x86_sse2_ucomieq_sd:
8153 Opc = X86ISD::UCOMI;
8156 case Intrinsic::x86_sse_ucomilt_ss:
8157 case Intrinsic::x86_sse2_ucomilt_sd:
8158 Opc = X86ISD::UCOMI;
8161 case Intrinsic::x86_sse_ucomile_ss:
8162 case Intrinsic::x86_sse2_ucomile_sd:
8163 Opc = X86ISD::UCOMI;
8166 case Intrinsic::x86_sse_ucomigt_ss:
8167 case Intrinsic::x86_sse2_ucomigt_sd:
8168 Opc = X86ISD::UCOMI;
8171 case Intrinsic::x86_sse_ucomige_ss:
8172 case Intrinsic::x86_sse2_ucomige_sd:
8173 Opc = X86ISD::UCOMI;
8176 case Intrinsic::x86_sse_ucomineq_ss:
8177 case Intrinsic::x86_sse2_ucomineq_sd:
8178 Opc = X86ISD::UCOMI;
8183 SDValue LHS = Op.getOperand(1);
8184 SDValue RHS = Op.getOperand(2);
8185 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8186 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8187 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8188 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8189 DAG.getConstant(X86CC, MVT::i8), Cond);
8190 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8192 // ptest and testp intrinsics. The intrinsic these come from are designed to
8193 // return an integer value, not just an instruction so lower it to the ptest
8194 // or testp pattern and a setcc for the result.
8195 case Intrinsic::x86_sse41_ptestz:
8196 case Intrinsic::x86_sse41_ptestc:
8197 case Intrinsic::x86_sse41_ptestnzc:
8198 case Intrinsic::x86_avx_ptestz_256:
8199 case Intrinsic::x86_avx_ptestc_256:
8200 case Intrinsic::x86_avx_ptestnzc_256:
8201 case Intrinsic::x86_avx_vtestz_ps:
8202 case Intrinsic::x86_avx_vtestc_ps:
8203 case Intrinsic::x86_avx_vtestnzc_ps:
8204 case Intrinsic::x86_avx_vtestz_pd:
8205 case Intrinsic::x86_avx_vtestc_pd:
8206 case Intrinsic::x86_avx_vtestnzc_pd:
8207 case Intrinsic::x86_avx_vtestz_ps_256:
8208 case Intrinsic::x86_avx_vtestc_ps_256:
8209 case Intrinsic::x86_avx_vtestnzc_ps_256:
8210 case Intrinsic::x86_avx_vtestz_pd_256:
8211 case Intrinsic::x86_avx_vtestc_pd_256:
8212 case Intrinsic::x86_avx_vtestnzc_pd_256: {
8213 bool IsTestPacked = false;
8216 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8217 case Intrinsic::x86_avx_vtestz_ps:
8218 case Intrinsic::x86_avx_vtestz_pd:
8219 case Intrinsic::x86_avx_vtestz_ps_256:
8220 case Intrinsic::x86_avx_vtestz_pd_256:
8221 IsTestPacked = true; // Fallthrough
8222 case Intrinsic::x86_sse41_ptestz:
8223 case Intrinsic::x86_avx_ptestz_256:
8225 X86CC = X86::COND_E;
8227 case Intrinsic::x86_avx_vtestc_ps:
8228 case Intrinsic::x86_avx_vtestc_pd:
8229 case Intrinsic::x86_avx_vtestc_ps_256:
8230 case Intrinsic::x86_avx_vtestc_pd_256:
8231 IsTestPacked = true; // Fallthrough
8232 case Intrinsic::x86_sse41_ptestc:
8233 case Intrinsic::x86_avx_ptestc_256:
8235 X86CC = X86::COND_B;
8237 case Intrinsic::x86_avx_vtestnzc_ps:
8238 case Intrinsic::x86_avx_vtestnzc_pd:
8239 case Intrinsic::x86_avx_vtestnzc_ps_256:
8240 case Intrinsic::x86_avx_vtestnzc_pd_256:
8241 IsTestPacked = true; // Fallthrough
8242 case Intrinsic::x86_sse41_ptestnzc:
8243 case Intrinsic::x86_avx_ptestnzc_256:
8245 X86CC = X86::COND_A;
8249 SDValue LHS = Op.getOperand(1);
8250 SDValue RHS = Op.getOperand(2);
8251 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8252 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8253 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8254 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8255 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8258 // Fix vector shift instructions where the last operand is a non-immediate
8260 case Intrinsic::x86_sse2_pslli_w:
8261 case Intrinsic::x86_sse2_pslli_d:
8262 case Intrinsic::x86_sse2_pslli_q:
8263 case Intrinsic::x86_sse2_psrli_w:
8264 case Intrinsic::x86_sse2_psrli_d:
8265 case Intrinsic::x86_sse2_psrli_q:
8266 case Intrinsic::x86_sse2_psrai_w:
8267 case Intrinsic::x86_sse2_psrai_d:
8268 case Intrinsic::x86_mmx_pslli_w:
8269 case Intrinsic::x86_mmx_pslli_d:
8270 case Intrinsic::x86_mmx_pslli_q:
8271 case Intrinsic::x86_mmx_psrli_w:
8272 case Intrinsic::x86_mmx_psrli_d:
8273 case Intrinsic::x86_mmx_psrli_q:
8274 case Intrinsic::x86_mmx_psrai_w:
8275 case Intrinsic::x86_mmx_psrai_d: {
8276 SDValue ShAmt = Op.getOperand(2);
8277 if (isa<ConstantSDNode>(ShAmt))
8280 unsigned NewIntNo = 0;
8281 EVT ShAmtVT = MVT::v4i32;
8283 case Intrinsic::x86_sse2_pslli_w:
8284 NewIntNo = Intrinsic::x86_sse2_psll_w;
8286 case Intrinsic::x86_sse2_pslli_d:
8287 NewIntNo = Intrinsic::x86_sse2_psll_d;
8289 case Intrinsic::x86_sse2_pslli_q:
8290 NewIntNo = Intrinsic::x86_sse2_psll_q;
8292 case Intrinsic::x86_sse2_psrli_w:
8293 NewIntNo = Intrinsic::x86_sse2_psrl_w;
8295 case Intrinsic::x86_sse2_psrli_d:
8296 NewIntNo = Intrinsic::x86_sse2_psrl_d;
8298 case Intrinsic::x86_sse2_psrli_q:
8299 NewIntNo = Intrinsic::x86_sse2_psrl_q;
8301 case Intrinsic::x86_sse2_psrai_w:
8302 NewIntNo = Intrinsic::x86_sse2_psra_w;
8304 case Intrinsic::x86_sse2_psrai_d:
8305 NewIntNo = Intrinsic::x86_sse2_psra_d;
8308 ShAmtVT = MVT::v2i32;
8310 case Intrinsic::x86_mmx_pslli_w:
8311 NewIntNo = Intrinsic::x86_mmx_psll_w;
8313 case Intrinsic::x86_mmx_pslli_d:
8314 NewIntNo = Intrinsic::x86_mmx_psll_d;
8316 case Intrinsic::x86_mmx_pslli_q:
8317 NewIntNo = Intrinsic::x86_mmx_psll_q;
8319 case Intrinsic::x86_mmx_psrli_w:
8320 NewIntNo = Intrinsic::x86_mmx_psrl_w;
8322 case Intrinsic::x86_mmx_psrli_d:
8323 NewIntNo = Intrinsic::x86_mmx_psrl_d;
8325 case Intrinsic::x86_mmx_psrli_q:
8326 NewIntNo = Intrinsic::x86_mmx_psrl_q;
8328 case Intrinsic::x86_mmx_psrai_w:
8329 NewIntNo = Intrinsic::x86_mmx_psra_w;
8331 case Intrinsic::x86_mmx_psrai_d:
8332 NewIntNo = Intrinsic::x86_mmx_psra_d;
8334 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8340 // The vector shift intrinsics with scalars uses 32b shift amounts but
8341 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8345 ShOps[1] = DAG.getConstant(0, MVT::i32);
8346 if (ShAmtVT == MVT::v4i32) {
8347 ShOps[2] = DAG.getUNDEF(MVT::i32);
8348 ShOps[3] = DAG.getUNDEF(MVT::i32);
8349 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8351 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8352 // FIXME this must be lowered to get rid of the invalid type.
8355 EVT VT = Op.getValueType();
8356 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8357 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8358 DAG.getConstant(NewIntNo, MVT::i32),
8359 Op.getOperand(1), ShAmt);
8364 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8365 SelectionDAG &DAG) const {
8366 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8367 MFI->setReturnAddressIsTaken(true);
8369 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8370 DebugLoc dl = Op.getDebugLoc();
8373 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8375 DAG.getConstant(TD->getPointerSize(),
8376 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8377 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8378 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8380 MachinePointerInfo(), false, false, 0);
8383 // Just load the return address.
8384 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8385 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8386 RetAddrFI, MachinePointerInfo(), false, false, 0);
8389 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8390 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8391 MFI->setFrameAddressIsTaken(true);
8393 EVT VT = Op.getValueType();
8394 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
8395 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8396 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8397 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8399 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8400 MachinePointerInfo(),
8405 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8406 SelectionDAG &DAG) const {
8407 return DAG.getIntPtrConstant(2*TD->getPointerSize());
8410 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8411 MachineFunction &MF = DAG.getMachineFunction();
8412 SDValue Chain = Op.getOperand(0);
8413 SDValue Offset = Op.getOperand(1);
8414 SDValue Handler = Op.getOperand(2);
8415 DebugLoc dl = Op.getDebugLoc();
8417 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8418 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8420 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8422 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8423 DAG.getIntPtrConstant(TD->getPointerSize()));
8424 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8425 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8427 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8428 MF.getRegInfo().addLiveOut(StoreAddrReg);
8430 return DAG.getNode(X86ISD::EH_RETURN, dl,
8432 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8435 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8436 SelectionDAG &DAG) const {
8437 SDValue Root = Op.getOperand(0);
8438 SDValue Trmp = Op.getOperand(1); // trampoline
8439 SDValue FPtr = Op.getOperand(2); // nested function
8440 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8441 DebugLoc dl = Op.getDebugLoc();
8443 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8445 if (Subtarget->is64Bit()) {
8446 SDValue OutChains[6];
8448 // Large code-model.
8449 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8450 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8452 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8453 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8455 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8457 // Load the pointer to the nested function into R11.
8458 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8459 SDValue Addr = Trmp;
8460 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8461 Addr, MachinePointerInfo(TrmpAddr),
8464 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8465 DAG.getConstant(2, MVT::i64));
8466 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8467 MachinePointerInfo(TrmpAddr, 2),
8470 // Load the 'nest' parameter value into R10.
8471 // R10 is specified in X86CallingConv.td
8472 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8473 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8474 DAG.getConstant(10, MVT::i64));
8475 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8476 Addr, MachinePointerInfo(TrmpAddr, 10),
8479 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8480 DAG.getConstant(12, MVT::i64));
8481 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8482 MachinePointerInfo(TrmpAddr, 12),
8485 // Jump to the nested function.
8486 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8487 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8488 DAG.getConstant(20, MVT::i64));
8489 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8490 Addr, MachinePointerInfo(TrmpAddr, 20),
8493 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8494 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8495 DAG.getConstant(22, MVT::i64));
8496 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8497 MachinePointerInfo(TrmpAddr, 22),
8501 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8502 return DAG.getMergeValues(Ops, 2, dl);
8504 const Function *Func =
8505 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8506 CallingConv::ID CC = Func->getCallingConv();
8511 llvm_unreachable("Unsupported calling convention");
8512 case CallingConv::C:
8513 case CallingConv::X86_StdCall: {
8514 // Pass 'nest' parameter in ECX.
8515 // Must be kept in sync with X86CallingConv.td
8518 // Check that ECX wasn't needed by an 'inreg' parameter.
8519 const FunctionType *FTy = Func->getFunctionType();
8520 const AttrListPtr &Attrs = Func->getAttributes();
8522 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8523 unsigned InRegCount = 0;
8526 for (FunctionType::param_iterator I = FTy->param_begin(),
8527 E = FTy->param_end(); I != E; ++I, ++Idx)
8528 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8529 // FIXME: should only count parameters that are lowered to integers.
8530 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8532 if (InRegCount > 2) {
8533 report_fatal_error("Nest register in use - reduce number of inreg"
8539 case CallingConv::X86_FastCall:
8540 case CallingConv::X86_ThisCall:
8541 case CallingConv::Fast:
8542 // Pass 'nest' parameter in EAX.
8543 // Must be kept in sync with X86CallingConv.td
8548 SDValue OutChains[4];
8551 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8552 DAG.getConstant(10, MVT::i32));
8553 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8555 // This is storing the opcode for MOV32ri.
8556 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8557 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8558 OutChains[0] = DAG.getStore(Root, dl,
8559 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8560 Trmp, MachinePointerInfo(TrmpAddr),
8563 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8564 DAG.getConstant(1, MVT::i32));
8565 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8566 MachinePointerInfo(TrmpAddr, 1),
8569 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8570 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8571 DAG.getConstant(5, MVT::i32));
8572 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8573 MachinePointerInfo(TrmpAddr, 5),
8576 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8577 DAG.getConstant(6, MVT::i32));
8578 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8579 MachinePointerInfo(TrmpAddr, 6),
8583 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8584 return DAG.getMergeValues(Ops, 2, dl);
8588 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8589 SelectionDAG &DAG) const {
8591 The rounding mode is in bits 11:10 of FPSR, and has the following
8598 FLT_ROUNDS, on the other hand, expects the following:
8605 To perform the conversion, we do:
8606 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8609 MachineFunction &MF = DAG.getMachineFunction();
8610 const TargetMachine &TM = MF.getTarget();
8611 const TargetFrameLowering &TFI = *TM.getFrameLowering();
8612 unsigned StackAlignment = TFI.getStackAlignment();
8613 EVT VT = Op.getValueType();
8614 DebugLoc DL = Op.getDebugLoc();
8616 // Save FP Control Word to stack slot
8617 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8618 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8621 MachineMemOperand *MMO =
8622 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8623 MachineMemOperand::MOStore, 2, 2);
8625 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8626 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8627 DAG.getVTList(MVT::Other),
8628 Ops, 2, MVT::i16, MMO);
8630 // Load FP Control Word from stack slot
8631 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8632 MachinePointerInfo(), false, false, 0);
8634 // Transform as necessary
8636 DAG.getNode(ISD::SRL, DL, MVT::i16,
8637 DAG.getNode(ISD::AND, DL, MVT::i16,
8638 CWD, DAG.getConstant(0x800, MVT::i16)),
8639 DAG.getConstant(11, MVT::i8));
8641 DAG.getNode(ISD::SRL, DL, MVT::i16,
8642 DAG.getNode(ISD::AND, DL, MVT::i16,
8643 CWD, DAG.getConstant(0x400, MVT::i16)),
8644 DAG.getConstant(9, MVT::i8));
8647 DAG.getNode(ISD::AND, DL, MVT::i16,
8648 DAG.getNode(ISD::ADD, DL, MVT::i16,
8649 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8650 DAG.getConstant(1, MVT::i16)),
8651 DAG.getConstant(3, MVT::i16));
8654 return DAG.getNode((VT.getSizeInBits() < 16 ?
8655 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8658 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8659 EVT VT = Op.getValueType();
8661 unsigned NumBits = VT.getSizeInBits();
8662 DebugLoc dl = Op.getDebugLoc();
8664 Op = Op.getOperand(0);
8665 if (VT == MVT::i8) {
8666 // Zero extend to i32 since there is not an i8 bsr.
8668 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8671 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8672 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8673 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8675 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8678 DAG.getConstant(NumBits+NumBits-1, OpVT),
8679 DAG.getConstant(X86::COND_E, MVT::i8),
8682 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8684 // Finally xor with NumBits-1.
8685 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8688 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8692 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8693 EVT VT = Op.getValueType();
8695 unsigned NumBits = VT.getSizeInBits();
8696 DebugLoc dl = Op.getDebugLoc();
8698 Op = Op.getOperand(0);
8699 if (VT == MVT::i8) {
8701 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8704 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8705 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8706 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8708 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8711 DAG.getConstant(NumBits, OpVT),
8712 DAG.getConstant(X86::COND_E, MVT::i8),
8715 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8718 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8722 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8723 EVT VT = Op.getValueType();
8724 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8725 DebugLoc dl = Op.getDebugLoc();
8727 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8728 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8729 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8730 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8731 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8733 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8734 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8735 // return AloBlo + AloBhi + AhiBlo;
8737 SDValue A = Op.getOperand(0);
8738 SDValue B = Op.getOperand(1);
8740 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8741 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8742 A, DAG.getConstant(32, MVT::i32));
8743 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8744 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8745 B, DAG.getConstant(32, MVT::i32));
8746 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8747 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8749 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8750 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8752 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8753 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8755 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8756 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8757 AloBhi, DAG.getConstant(32, MVT::i32));
8758 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8759 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8760 AhiBlo, DAG.getConstant(32, MVT::i32));
8761 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8762 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8766 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8767 EVT VT = Op.getValueType();
8768 DebugLoc dl = Op.getDebugLoc();
8769 SDValue R = Op.getOperand(0);
8771 LLVMContext *Context = DAG.getContext();
8773 assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8775 if (VT == MVT::v4i32) {
8776 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8777 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8778 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8780 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8782 std::vector<Constant*> CV(4, CI);
8783 Constant *C = ConstantVector::get(CV);
8784 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8785 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8786 MachinePointerInfo::getConstantPool(),
8789 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8790 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8791 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8792 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8794 if (VT == MVT::v16i8) {
8796 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8797 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8798 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8800 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8801 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8803 std::vector<Constant*> CVM1(16, CM1);
8804 std::vector<Constant*> CVM2(16, CM2);
8805 Constant *C = ConstantVector::get(CVM1);
8806 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8807 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8808 MachinePointerInfo::getConstantPool(),
8811 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8812 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8813 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8814 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8815 DAG.getConstant(4, MVT::i32));
8816 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8818 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8820 C = ConstantVector::get(CVM2);
8821 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8822 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8823 MachinePointerInfo::getConstantPool(),
8826 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8827 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8828 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8829 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8830 DAG.getConstant(2, MVT::i32));
8831 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8833 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8835 // return pblendv(r, r+r, a);
8836 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8837 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8843 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8844 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8845 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8846 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8847 // has only one use.
8848 SDNode *N = Op.getNode();
8849 SDValue LHS = N->getOperand(0);
8850 SDValue RHS = N->getOperand(1);
8851 unsigned BaseOp = 0;
8853 DebugLoc DL = Op.getDebugLoc();
8854 switch (Op.getOpcode()) {
8855 default: llvm_unreachable("Unknown ovf instruction!");
8857 // A subtract of one will be selected as a INC. Note that INC doesn't
8858 // set CF, so we can't do this for UADDO.
8859 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8861 BaseOp = X86ISD::INC;
8865 BaseOp = X86ISD::ADD;
8869 BaseOp = X86ISD::ADD;
8873 // A subtract of one will be selected as a DEC. Note that DEC doesn't
8874 // set CF, so we can't do this for USUBO.
8875 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8877 BaseOp = X86ISD::DEC;
8881 BaseOp = X86ISD::SUB;
8885 BaseOp = X86ISD::SUB;
8889 BaseOp = X86ISD::SMUL;
8892 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8893 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8895 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8898 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8899 DAG.getConstant(X86::COND_O, MVT::i32),
8900 SDValue(Sum.getNode(), 2));
8902 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8907 // Also sets EFLAGS.
8908 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8909 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8912 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8913 DAG.getConstant(Cond, MVT::i32),
8914 SDValue(Sum.getNode(), 1));
8916 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8920 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8921 DebugLoc dl = Op.getDebugLoc();
8923 if (!Subtarget->hasSSE2()) {
8924 SDValue Chain = Op.getOperand(0);
8925 SDValue Zero = DAG.getConstant(0,
8926 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8928 DAG.getRegister(X86::ESP, MVT::i32), // Base
8929 DAG.getTargetConstant(1, MVT::i8), // Scale
8930 DAG.getRegister(0, MVT::i32), // Index
8931 DAG.getTargetConstant(0, MVT::i32), // Disp
8932 DAG.getRegister(0, MVT::i32), // Segment.
8937 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8938 array_lengthof(Ops));
8939 return SDValue(Res, 0);
8942 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8944 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8946 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8947 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8948 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8949 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8951 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8952 if (!Op1 && !Op2 && !Op3 && Op4)
8953 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8955 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8956 if (Op1 && !Op2 && !Op3 && !Op4)
8957 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8959 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8961 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8964 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8965 EVT T = Op.getValueType();
8966 DebugLoc DL = Op.getDebugLoc();
8969 switch(T.getSimpleVT().SimpleTy) {
8971 assert(false && "Invalid value type!");
8972 case MVT::i8: Reg = X86::AL; size = 1; break;
8973 case MVT::i16: Reg = X86::AX; size = 2; break;
8974 case MVT::i32: Reg = X86::EAX; size = 4; break;
8976 assert(Subtarget->is64Bit() && "Node not type legal!");
8977 Reg = X86::RAX; size = 8;
8980 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8981 Op.getOperand(2), SDValue());
8982 SDValue Ops[] = { cpIn.getValue(0),
8985 DAG.getTargetConstant(size, MVT::i8),
8987 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8988 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8989 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8992 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8996 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8997 SelectionDAG &DAG) const {
8998 assert(Subtarget->is64Bit() && "Result not type legalized?");
8999 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9000 SDValue TheChain = Op.getOperand(0);
9001 DebugLoc dl = Op.getDebugLoc();
9002 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9003 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9004 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9006 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9007 DAG.getConstant(32, MVT::i8));
9009 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9012 return DAG.getMergeValues(Ops, 2, dl);
9015 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9016 SelectionDAG &DAG) const {
9017 EVT SrcVT = Op.getOperand(0).getValueType();
9018 EVT DstVT = Op.getValueType();
9019 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9020 Subtarget->hasMMX() && "Unexpected custom BITCAST");
9021 assert((DstVT == MVT::i64 ||
9022 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9023 "Unexpected custom BITCAST");
9024 // i64 <=> MMX conversions are Legal.
9025 if (SrcVT==MVT::i64 && DstVT.isVector())
9027 if (DstVT==MVT::i64 && SrcVT.isVector())
9029 // MMX <=> MMX conversions are Legal.
9030 if (SrcVT.isVector() && DstVT.isVector())
9032 // All other conversions need to be expanded.
9036 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9037 SDNode *Node = Op.getNode();
9038 DebugLoc dl = Node->getDebugLoc();
9039 EVT T = Node->getValueType(0);
9040 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9041 DAG.getConstant(0, T), Node->getOperand(2));
9042 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9043 cast<AtomicSDNode>(Node)->getMemoryVT(),
9044 Node->getOperand(0),
9045 Node->getOperand(1), negOp,
9046 cast<AtomicSDNode>(Node)->getSrcValue(),
9047 cast<AtomicSDNode>(Node)->getAlignment());
9050 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9051 EVT VT = Op.getNode()->getValueType(0);
9053 // Let legalize expand this if it isn't a legal type yet.
9054 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9057 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9060 bool ExtraOp = false;
9061 switch (Op.getOpcode()) {
9062 default: assert(0 && "Invalid code");
9063 case ISD::ADDC: Opc = X86ISD::ADD; break;
9064 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9065 case ISD::SUBC: Opc = X86ISD::SUB; break;
9066 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9070 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9072 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9073 Op.getOperand(1), Op.getOperand(2));
9076 /// LowerOperation - Provide custom lowering hooks for some operations.
9078 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9079 switch (Op.getOpcode()) {
9080 default: llvm_unreachable("Should not custom lower this!");
9081 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
9082 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
9083 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
9084 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
9085 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
9086 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
9087 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9088 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9089 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
9090 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
9091 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
9092 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9093 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9094 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9095 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
9096 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
9097 case ISD::SHL_PARTS:
9098 case ISD::SRA_PARTS:
9099 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
9100 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
9101 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
9102 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
9103 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
9104 case ISD::FABS: return LowerFABS(Op, DAG);
9105 case ISD::FNEG: return LowerFNEG(Op, DAG);
9106 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
9107 case ISD::SETCC: return LowerSETCC(Op, DAG);
9108 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
9109 case ISD::SELECT: return LowerSELECT(Op, DAG);
9110 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
9111 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
9112 case ISD::VASTART: return LowerVASTART(Op, DAG);
9113 case ISD::VAARG: return LowerVAARG(Op, DAG);
9114 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
9115 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9116 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9117 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9118 case ISD::FRAME_TO_ARGS_OFFSET:
9119 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9120 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9121 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
9122 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
9123 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9124 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
9125 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
9126 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
9127 case ISD::SHL: return LowerSHL(Op, DAG);
9133 case ISD::UMULO: return LowerXALUO(Op, DAG);
9134 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
9135 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
9139 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9143 void X86TargetLowering::
9144 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9145 SelectionDAG &DAG, unsigned NewOp) const {
9146 EVT T = Node->getValueType(0);
9147 DebugLoc dl = Node->getDebugLoc();
9148 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9150 SDValue Chain = Node->getOperand(0);
9151 SDValue In1 = Node->getOperand(1);
9152 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9153 Node->getOperand(2), DAG.getIntPtrConstant(0));
9154 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9155 Node->getOperand(2), DAG.getIntPtrConstant(1));
9156 SDValue Ops[] = { Chain, In1, In2L, In2H };
9157 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9159 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9160 cast<MemSDNode>(Node)->getMemOperand());
9161 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9162 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9163 Results.push_back(Result.getValue(2));
9166 /// ReplaceNodeResults - Replace a node with an illegal result type
9167 /// with a new node built out of custom code.
9168 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9169 SmallVectorImpl<SDValue>&Results,
9170 SelectionDAG &DAG) const {
9171 DebugLoc dl = N->getDebugLoc();
9172 switch (N->getOpcode()) {
9174 assert(false && "Do not know how to custom type legalize this operation!");
9180 // We don't want to expand or promote these.
9182 case ISD::FP_TO_SINT: {
9183 std::pair<SDValue,SDValue> Vals =
9184 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9185 SDValue FIST = Vals.first, StackSlot = Vals.second;
9186 if (FIST.getNode() != 0) {
9187 EVT VT = N->getValueType(0);
9188 // Return a load from the stack slot.
9189 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9190 MachinePointerInfo(), false, false, 0));
9194 case ISD::READCYCLECOUNTER: {
9195 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9196 SDValue TheChain = N->getOperand(0);
9197 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9198 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9200 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9202 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9203 SDValue Ops[] = { eax, edx };
9204 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9205 Results.push_back(edx.getValue(1));
9208 case ISD::ATOMIC_CMP_SWAP: {
9209 EVT T = N->getValueType(0);
9210 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9211 SDValue cpInL, cpInH;
9212 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9213 DAG.getConstant(0, MVT::i32));
9214 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9215 DAG.getConstant(1, MVT::i32));
9216 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9217 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9219 SDValue swapInL, swapInH;
9220 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9221 DAG.getConstant(0, MVT::i32));
9222 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9223 DAG.getConstant(1, MVT::i32));
9224 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9226 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9227 swapInL.getValue(1));
9228 SDValue Ops[] = { swapInH.getValue(0),
9230 swapInH.getValue(1) };
9231 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9232 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9233 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9235 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9236 MVT::i32, Result.getValue(1));
9237 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9238 MVT::i32, cpOutL.getValue(2));
9239 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9240 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9241 Results.push_back(cpOutH.getValue(1));
9244 case ISD::ATOMIC_LOAD_ADD:
9245 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9247 case ISD::ATOMIC_LOAD_AND:
9248 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9250 case ISD::ATOMIC_LOAD_NAND:
9251 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9253 case ISD::ATOMIC_LOAD_OR:
9254 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9256 case ISD::ATOMIC_LOAD_SUB:
9257 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9259 case ISD::ATOMIC_LOAD_XOR:
9260 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9262 case ISD::ATOMIC_SWAP:
9263 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9268 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9270 default: return NULL;
9271 case X86ISD::BSF: return "X86ISD::BSF";
9272 case X86ISD::BSR: return "X86ISD::BSR";
9273 case X86ISD::SHLD: return "X86ISD::SHLD";
9274 case X86ISD::SHRD: return "X86ISD::SHRD";
9275 case X86ISD::FAND: return "X86ISD::FAND";
9276 case X86ISD::FOR: return "X86ISD::FOR";
9277 case X86ISD::FXOR: return "X86ISD::FXOR";
9278 case X86ISD::FSRL: return "X86ISD::FSRL";
9279 case X86ISD::FILD: return "X86ISD::FILD";
9280 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
9281 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9282 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9283 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9284 case X86ISD::FLD: return "X86ISD::FLD";
9285 case X86ISD::FST: return "X86ISD::FST";
9286 case X86ISD::CALL: return "X86ISD::CALL";
9287 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
9288 case X86ISD::BT: return "X86ISD::BT";
9289 case X86ISD::CMP: return "X86ISD::CMP";
9290 case X86ISD::COMI: return "X86ISD::COMI";
9291 case X86ISD::UCOMI: return "X86ISD::UCOMI";
9292 case X86ISD::SETCC: return "X86ISD::SETCC";
9293 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
9294 case X86ISD::CMOV: return "X86ISD::CMOV";
9295 case X86ISD::BRCOND: return "X86ISD::BRCOND";
9296 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
9297 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
9298 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
9299 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
9300 case X86ISD::Wrapper: return "X86ISD::Wrapper";
9301 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
9302 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
9303 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
9304 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
9305 case X86ISD::PINSRB: return "X86ISD::PINSRB";
9306 case X86ISD::PINSRW: return "X86ISD::PINSRW";
9307 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
9308 case X86ISD::PANDN: return "X86ISD::PANDN";
9309 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
9310 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
9311 case X86ISD::PSIGND: return "X86ISD::PSIGND";
9312 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB";
9313 case X86ISD::FMAX: return "X86ISD::FMAX";
9314 case X86ISD::FMIN: return "X86ISD::FMIN";
9315 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
9316 case X86ISD::FRCP: return "X86ISD::FRCP";
9317 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
9318 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
9319 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
9320 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
9321 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
9322 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
9323 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
9324 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
9325 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
9326 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
9327 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
9328 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
9329 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
9330 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
9331 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
9332 case X86ISD::VSHL: return "X86ISD::VSHL";
9333 case X86ISD::VSRL: return "X86ISD::VSRL";
9334 case X86ISD::CMPPD: return "X86ISD::CMPPD";
9335 case X86ISD::CMPPS: return "X86ISD::CMPPS";
9336 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
9337 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
9338 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
9339 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
9340 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
9341 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
9342 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
9343 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
9344 case X86ISD::ADD: return "X86ISD::ADD";
9345 case X86ISD::SUB: return "X86ISD::SUB";
9346 case X86ISD::ADC: return "X86ISD::ADC";
9347 case X86ISD::SBB: return "X86ISD::SBB";
9348 case X86ISD::SMUL: return "X86ISD::SMUL";
9349 case X86ISD::UMUL: return "X86ISD::UMUL";
9350 case X86ISD::INC: return "X86ISD::INC";
9351 case X86ISD::DEC: return "X86ISD::DEC";
9352 case X86ISD::OR: return "X86ISD::OR";
9353 case X86ISD::XOR: return "X86ISD::XOR";
9354 case X86ISD::AND: return "X86ISD::AND";
9355 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
9356 case X86ISD::PTEST: return "X86ISD::PTEST";
9357 case X86ISD::TESTP: return "X86ISD::TESTP";
9358 case X86ISD::PALIGN: return "X86ISD::PALIGN";
9359 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
9360 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
9361 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
9362 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
9363 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
9364 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
9365 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
9366 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
9367 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
9368 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
9369 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
9370 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
9371 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
9372 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
9373 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
9374 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
9375 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
9376 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
9377 case X86ISD::MOVSD: return "X86ISD::MOVSD";
9378 case X86ISD::MOVSS: return "X86ISD::MOVSS";
9379 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
9380 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
9381 case X86ISD::VUNPCKLPS: return "X86ISD::VUNPCKLPS";
9382 case X86ISD::VUNPCKLPD: return "X86ISD::VUNPCKLPD";
9383 case X86ISD::VUNPCKLPSY: return "X86ISD::VUNPCKLPSY";
9384 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
9385 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
9386 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
9387 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
9388 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
9389 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
9390 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
9391 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
9392 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
9393 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
9394 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
9395 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9396 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
9397 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
9401 // isLegalAddressingMode - Return true if the addressing mode represented
9402 // by AM is legal for this target, for a load/store of the specified type.
9403 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9404 const Type *Ty) const {
9405 // X86 supports extremely general addressing modes.
9406 CodeModel::Model M = getTargetMachine().getCodeModel();
9407 Reloc::Model R = getTargetMachine().getRelocationModel();
9409 // X86 allows a sign-extended 32-bit immediate field as a displacement.
9410 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9415 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9417 // If a reference to this global requires an extra load, we can't fold it.
9418 if (isGlobalStubReference(GVFlags))
9421 // If BaseGV requires a register for the PIC base, we cannot also have a
9422 // BaseReg specified.
9423 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9426 // If lower 4G is not available, then we must use rip-relative addressing.
9427 if ((M != CodeModel::Small || R != Reloc::Static) &&
9428 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9438 // These scales always work.
9443 // These scales are formed with basereg+scalereg. Only accept if there is
9448 default: // Other stuff never works.
9456 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9457 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9459 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9460 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9461 if (NumBits1 <= NumBits2)
9466 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9467 if (!VT1.isInteger() || !VT2.isInteger())
9469 unsigned NumBits1 = VT1.getSizeInBits();
9470 unsigned NumBits2 = VT2.getSizeInBits();
9471 if (NumBits1 <= NumBits2)
9476 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9477 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9478 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9481 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9482 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9483 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9486 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9487 // i16 instructions are longer (0x66 prefix) and potentially slower.
9488 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9491 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9492 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9493 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9494 /// are assumed to be legal.
9496 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9498 // Very little shuffling can be done for 64-bit vectors right now.
9499 if (VT.getSizeInBits() == 64)
9500 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9502 // FIXME: pshufb, blends, shifts.
9503 return (VT.getVectorNumElements() == 2 ||
9504 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9505 isMOVLMask(M, VT) ||
9506 isSHUFPMask(M, VT) ||
9507 isPSHUFDMask(M, VT) ||
9508 isPSHUFHWMask(M, VT) ||
9509 isPSHUFLWMask(M, VT) ||
9510 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9511 isUNPCKLMask(M, VT) ||
9512 isUNPCKHMask(M, VT) ||
9513 isUNPCKL_v_undef_Mask(M, VT) ||
9514 isUNPCKH_v_undef_Mask(M, VT));
9518 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9520 unsigned NumElts = VT.getVectorNumElements();
9521 // FIXME: This collection of masks seems suspect.
9524 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9525 return (isMOVLMask(Mask, VT) ||
9526 isCommutedMOVLMask(Mask, VT, true) ||
9527 isSHUFPMask(Mask, VT) ||
9528 isCommutedSHUFPMask(Mask, VT));
9533 //===----------------------------------------------------------------------===//
9534 // X86 Scheduler Hooks
9535 //===----------------------------------------------------------------------===//
9537 // private utility function
9539 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9540 MachineBasicBlock *MBB,
9547 TargetRegisterClass *RC,
9548 bool invSrc) const {
9549 // For the atomic bitwise operator, we generate
9552 // ld t1 = [bitinstr.addr]
9553 // op t2 = t1, [bitinstr.val]
9555 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9557 // fallthrough -->nextMBB
9558 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9559 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9560 MachineFunction::iterator MBBIter = MBB;
9563 /// First build the CFG
9564 MachineFunction *F = MBB->getParent();
9565 MachineBasicBlock *thisMBB = MBB;
9566 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9567 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9568 F->insert(MBBIter, newMBB);
9569 F->insert(MBBIter, nextMBB);
9571 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9572 nextMBB->splice(nextMBB->begin(), thisMBB,
9573 llvm::next(MachineBasicBlock::iterator(bInstr)),
9575 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9577 // Update thisMBB to fall through to newMBB
9578 thisMBB->addSuccessor(newMBB);
9580 // newMBB jumps to itself and fall through to nextMBB
9581 newMBB->addSuccessor(nextMBB);
9582 newMBB->addSuccessor(newMBB);
9584 // Insert instructions into newMBB based on incoming instruction
9585 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9586 "unexpected number of operands");
9587 DebugLoc dl = bInstr->getDebugLoc();
9588 MachineOperand& destOper = bInstr->getOperand(0);
9589 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9590 int numArgs = bInstr->getNumOperands() - 1;
9591 for (int i=0; i < numArgs; ++i)
9592 argOpers[i] = &bInstr->getOperand(i+1);
9594 // x86 address has 4 operands: base, index, scale, and displacement
9595 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9596 int valArgIndx = lastAddrIndx + 1;
9598 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9599 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9600 for (int i=0; i <= lastAddrIndx; ++i)
9601 (*MIB).addOperand(*argOpers[i]);
9603 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9605 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9610 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9611 assert((argOpers[valArgIndx]->isReg() ||
9612 argOpers[valArgIndx]->isImm()) &&
9614 if (argOpers[valArgIndx]->isReg())
9615 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9617 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9619 (*MIB).addOperand(*argOpers[valArgIndx]);
9621 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9624 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9625 for (int i=0; i <= lastAddrIndx; ++i)
9626 (*MIB).addOperand(*argOpers[i]);
9628 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9629 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9630 bInstr->memoperands_end());
9632 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9636 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9638 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9642 // private utility function: 64 bit atomics on 32 bit host.
9644 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9645 MachineBasicBlock *MBB,
9650 bool invSrc) const {
9651 // For the atomic bitwise operator, we generate
9652 // thisMBB (instructions are in pairs, except cmpxchg8b)
9653 // ld t1,t2 = [bitinstr.addr]
9655 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9656 // op t5, t6 <- out1, out2, [bitinstr.val]
9657 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9658 // mov ECX, EBX <- t5, t6
9659 // mov EAX, EDX <- t1, t2
9660 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9661 // mov t3, t4 <- EAX, EDX
9663 // result in out1, out2
9664 // fallthrough -->nextMBB
9666 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9667 const unsigned LoadOpc = X86::MOV32rm;
9668 const unsigned NotOpc = X86::NOT32r;
9669 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9670 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9671 MachineFunction::iterator MBBIter = MBB;
9674 /// First build the CFG
9675 MachineFunction *F = MBB->getParent();
9676 MachineBasicBlock *thisMBB = MBB;
9677 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9678 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9679 F->insert(MBBIter, newMBB);
9680 F->insert(MBBIter, nextMBB);
9682 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9683 nextMBB->splice(nextMBB->begin(), thisMBB,
9684 llvm::next(MachineBasicBlock::iterator(bInstr)),
9686 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9688 // Update thisMBB to fall through to newMBB
9689 thisMBB->addSuccessor(newMBB);
9691 // newMBB jumps to itself and fall through to nextMBB
9692 newMBB->addSuccessor(nextMBB);
9693 newMBB->addSuccessor(newMBB);
9695 DebugLoc dl = bInstr->getDebugLoc();
9696 // Insert instructions into newMBB based on incoming instruction
9697 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9698 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9699 "unexpected number of operands");
9700 MachineOperand& dest1Oper = bInstr->getOperand(0);
9701 MachineOperand& dest2Oper = bInstr->getOperand(1);
9702 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9703 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9704 argOpers[i] = &bInstr->getOperand(i+2);
9706 // We use some of the operands multiple times, so conservatively just
9707 // clear any kill flags that might be present.
9708 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9709 argOpers[i]->setIsKill(false);
9712 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9713 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9715 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9716 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9717 for (int i=0; i <= lastAddrIndx; ++i)
9718 (*MIB).addOperand(*argOpers[i]);
9719 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9720 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9721 // add 4 to displacement.
9722 for (int i=0; i <= lastAddrIndx-2; ++i)
9723 (*MIB).addOperand(*argOpers[i]);
9724 MachineOperand newOp3 = *(argOpers[3]);
9726 newOp3.setImm(newOp3.getImm()+4);
9728 newOp3.setOffset(newOp3.getOffset()+4);
9729 (*MIB).addOperand(newOp3);
9730 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9732 // t3/4 are defined later, at the bottom of the loop
9733 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9734 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9735 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9736 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9737 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9738 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9740 // The subsequent operations should be using the destination registers of
9741 //the PHI instructions.
9743 t1 = F->getRegInfo().createVirtualRegister(RC);
9744 t2 = F->getRegInfo().createVirtualRegister(RC);
9745 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9746 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9748 t1 = dest1Oper.getReg();
9749 t2 = dest2Oper.getReg();
9752 int valArgIndx = lastAddrIndx + 1;
9753 assert((argOpers[valArgIndx]->isReg() ||
9754 argOpers[valArgIndx]->isImm()) &&
9756 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9757 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9758 if (argOpers[valArgIndx]->isReg())
9759 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9761 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9762 if (regOpcL != X86::MOV32rr)
9764 (*MIB).addOperand(*argOpers[valArgIndx]);
9765 assert(argOpers[valArgIndx + 1]->isReg() ==
9766 argOpers[valArgIndx]->isReg());
9767 assert(argOpers[valArgIndx + 1]->isImm() ==
9768 argOpers[valArgIndx]->isImm());
9769 if (argOpers[valArgIndx + 1]->isReg())
9770 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9772 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9773 if (regOpcH != X86::MOV32rr)
9775 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9777 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9779 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9782 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9784 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9787 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9788 for (int i=0; i <= lastAddrIndx; ++i)
9789 (*MIB).addOperand(*argOpers[i]);
9791 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9792 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9793 bInstr->memoperands_end());
9795 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9796 MIB.addReg(X86::EAX);
9797 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9798 MIB.addReg(X86::EDX);
9801 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9803 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9807 // private utility function
9809 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9810 MachineBasicBlock *MBB,
9811 unsigned cmovOpc) const {
9812 // For the atomic min/max operator, we generate
9815 // ld t1 = [min/max.addr]
9816 // mov t2 = [min/max.val]
9818 // cmov[cond] t2 = t1
9820 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9822 // fallthrough -->nextMBB
9824 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9825 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9826 MachineFunction::iterator MBBIter = MBB;
9829 /// First build the CFG
9830 MachineFunction *F = MBB->getParent();
9831 MachineBasicBlock *thisMBB = MBB;
9832 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9833 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9834 F->insert(MBBIter, newMBB);
9835 F->insert(MBBIter, nextMBB);
9837 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9838 nextMBB->splice(nextMBB->begin(), thisMBB,
9839 llvm::next(MachineBasicBlock::iterator(mInstr)),
9841 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9843 // Update thisMBB to fall through to newMBB
9844 thisMBB->addSuccessor(newMBB);
9846 // newMBB jumps to newMBB and fall through to nextMBB
9847 newMBB->addSuccessor(nextMBB);
9848 newMBB->addSuccessor(newMBB);
9850 DebugLoc dl = mInstr->getDebugLoc();
9851 // Insert instructions into newMBB based on incoming instruction
9852 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9853 "unexpected number of operands");
9854 MachineOperand& destOper = mInstr->getOperand(0);
9855 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9856 int numArgs = mInstr->getNumOperands() - 1;
9857 for (int i=0; i < numArgs; ++i)
9858 argOpers[i] = &mInstr->getOperand(i+1);
9860 // x86 address has 4 operands: base, index, scale, and displacement
9861 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9862 int valArgIndx = lastAddrIndx + 1;
9864 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9865 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9866 for (int i=0; i <= lastAddrIndx; ++i)
9867 (*MIB).addOperand(*argOpers[i]);
9869 // We only support register and immediate values
9870 assert((argOpers[valArgIndx]->isReg() ||
9871 argOpers[valArgIndx]->isImm()) &&
9874 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9875 if (argOpers[valArgIndx]->isReg())
9876 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9878 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9879 (*MIB).addOperand(*argOpers[valArgIndx]);
9881 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9884 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9889 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9890 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9894 // Cmp and exchange if none has modified the memory location
9895 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9896 for (int i=0; i <= lastAddrIndx; ++i)
9897 (*MIB).addOperand(*argOpers[i]);
9899 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9900 (*MIB).setMemRefs(mInstr->memoperands_begin(),
9901 mInstr->memoperands_end());
9903 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9904 MIB.addReg(X86::EAX);
9907 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9909 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
9913 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9914 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9917 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9918 unsigned numArgs, bool memArg) const {
9919 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9920 "Target must have SSE4.2 or AVX features enabled");
9922 DebugLoc dl = MI->getDebugLoc();
9923 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9925 if (!Subtarget->hasAVX()) {
9927 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9929 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9932 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9934 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9937 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9938 for (unsigned i = 0; i < numArgs; ++i) {
9939 MachineOperand &Op = MI->getOperand(i+1);
9940 if (!(Op.isReg() && Op.isImplicit()))
9943 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9946 MI->eraseFromParent();
9951 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9952 DebugLoc dl = MI->getDebugLoc();
9953 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9955 // Address into RAX/EAX, other two args into ECX, EDX.
9956 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9957 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9958 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9959 for (int i = 0; i < X86::AddrNumOperands; ++i)
9960 MIB.addOperand(MI->getOperand(i));
9962 unsigned ValOps = X86::AddrNumOperands;
9963 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9964 .addReg(MI->getOperand(ValOps).getReg());
9965 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9966 .addReg(MI->getOperand(ValOps+1).getReg());
9968 // The instruction doesn't actually take any operands though.
9969 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9971 MI->eraseFromParent(); // The pseudo is gone now.
9976 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9977 DebugLoc dl = MI->getDebugLoc();
9978 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9980 // First arg in ECX, the second in EAX.
9981 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9982 .addReg(MI->getOperand(0).getReg());
9983 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9984 .addReg(MI->getOperand(1).getReg());
9986 // The instruction doesn't actually take any operands though.
9987 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9989 MI->eraseFromParent(); // The pseudo is gone now.
9994 X86TargetLowering::EmitVAARG64WithCustomInserter(
9996 MachineBasicBlock *MBB) const {
9997 // Emit va_arg instruction on X86-64.
9999 // Operands to this pseudo-instruction:
10000 // 0 ) Output : destination address (reg)
10001 // 1-5) Input : va_list address (addr, i64mem)
10002 // 6 ) ArgSize : Size (in bytes) of vararg type
10003 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10004 // 8 ) Align : Alignment of type
10005 // 9 ) EFLAGS (implicit-def)
10007 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10008 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10010 unsigned DestReg = MI->getOperand(0).getReg();
10011 MachineOperand &Base = MI->getOperand(1);
10012 MachineOperand &Scale = MI->getOperand(2);
10013 MachineOperand &Index = MI->getOperand(3);
10014 MachineOperand &Disp = MI->getOperand(4);
10015 MachineOperand &Segment = MI->getOperand(5);
10016 unsigned ArgSize = MI->getOperand(6).getImm();
10017 unsigned ArgMode = MI->getOperand(7).getImm();
10018 unsigned Align = MI->getOperand(8).getImm();
10020 // Memory Reference
10021 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10022 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10023 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10025 // Machine Information
10026 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10027 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10028 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10029 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10030 DebugLoc DL = MI->getDebugLoc();
10032 // struct va_list {
10035 // i64 overflow_area (address)
10036 // i64 reg_save_area (address)
10038 // sizeof(va_list) = 24
10039 // alignment(va_list) = 8
10041 unsigned TotalNumIntRegs = 6;
10042 unsigned TotalNumXMMRegs = 8;
10043 bool UseGPOffset = (ArgMode == 1);
10044 bool UseFPOffset = (ArgMode == 2);
10045 unsigned MaxOffset = TotalNumIntRegs * 8 +
10046 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10048 /* Align ArgSize to a multiple of 8 */
10049 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10050 bool NeedsAlign = (Align > 8);
10052 MachineBasicBlock *thisMBB = MBB;
10053 MachineBasicBlock *overflowMBB;
10054 MachineBasicBlock *offsetMBB;
10055 MachineBasicBlock *endMBB;
10057 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
10058 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
10059 unsigned OffsetReg = 0;
10061 if (!UseGPOffset && !UseFPOffset) {
10062 // If we only pull from the overflow region, we don't create a branch.
10063 // We don't need to alter control flow.
10064 OffsetDestReg = 0; // unused
10065 OverflowDestReg = DestReg;
10068 overflowMBB = thisMBB;
10071 // First emit code to check if gp_offset (or fp_offset) is below the bound.
10072 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10073 // If not, pull from overflow_area. (branch to overflowMBB)
10078 // offsetMBB overflowMBB
10083 // Registers for the PHI in endMBB
10084 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10085 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10087 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10088 MachineFunction *MF = MBB->getParent();
10089 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10090 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10091 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10093 MachineFunction::iterator MBBIter = MBB;
10096 // Insert the new basic blocks
10097 MF->insert(MBBIter, offsetMBB);
10098 MF->insert(MBBIter, overflowMBB);
10099 MF->insert(MBBIter, endMBB);
10101 // Transfer the remainder of MBB and its successor edges to endMBB.
10102 endMBB->splice(endMBB->begin(), thisMBB,
10103 llvm::next(MachineBasicBlock::iterator(MI)),
10105 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10107 // Make offsetMBB and overflowMBB successors of thisMBB
10108 thisMBB->addSuccessor(offsetMBB);
10109 thisMBB->addSuccessor(overflowMBB);
10111 // endMBB is a successor of both offsetMBB and overflowMBB
10112 offsetMBB->addSuccessor(endMBB);
10113 overflowMBB->addSuccessor(endMBB);
10115 // Load the offset value into a register
10116 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10117 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10121 .addDisp(Disp, UseFPOffset ? 4 : 0)
10122 .addOperand(Segment)
10123 .setMemRefs(MMOBegin, MMOEnd);
10125 // Check if there is enough room left to pull this argument.
10126 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10128 .addImm(MaxOffset + 8 - ArgSizeA8);
10130 // Branch to "overflowMBB" if offset >= max
10131 // Fall through to "offsetMBB" otherwise
10132 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10133 .addMBB(overflowMBB);
10136 // In offsetMBB, emit code to use the reg_save_area.
10138 assert(OffsetReg != 0);
10140 // Read the reg_save_area address.
10141 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10142 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10147 .addOperand(Segment)
10148 .setMemRefs(MMOBegin, MMOEnd);
10150 // Zero-extend the offset
10151 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10152 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10155 .addImm(X86::sub_32bit);
10157 // Add the offset to the reg_save_area to get the final address.
10158 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10159 .addReg(OffsetReg64)
10160 .addReg(RegSaveReg);
10162 // Compute the offset for the next argument
10163 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10164 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10166 .addImm(UseFPOffset ? 16 : 8);
10168 // Store it back into the va_list.
10169 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10173 .addDisp(Disp, UseFPOffset ? 4 : 0)
10174 .addOperand(Segment)
10175 .addReg(NextOffsetReg)
10176 .setMemRefs(MMOBegin, MMOEnd);
10179 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10184 // Emit code to use overflow area
10187 // Load the overflow_area address into a register.
10188 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10189 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10194 .addOperand(Segment)
10195 .setMemRefs(MMOBegin, MMOEnd);
10197 // If we need to align it, do so. Otherwise, just copy the address
10198 // to OverflowDestReg.
10200 // Align the overflow address
10201 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10202 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10204 // aligned_addr = (addr + (align-1)) & ~(align-1)
10205 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10206 .addReg(OverflowAddrReg)
10209 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10211 .addImm(~(uint64_t)(Align-1));
10213 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10214 .addReg(OverflowAddrReg);
10217 // Compute the next overflow address after this argument.
10218 // (the overflow address should be kept 8-byte aligned)
10219 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10220 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10221 .addReg(OverflowDestReg)
10222 .addImm(ArgSizeA8);
10224 // Store the new overflow address.
10225 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10230 .addOperand(Segment)
10231 .addReg(NextAddrReg)
10232 .setMemRefs(MMOBegin, MMOEnd);
10234 // If we branched, emit the PHI to the front of endMBB.
10236 BuildMI(*endMBB, endMBB->begin(), DL,
10237 TII->get(X86::PHI), DestReg)
10238 .addReg(OffsetDestReg).addMBB(offsetMBB)
10239 .addReg(OverflowDestReg).addMBB(overflowMBB);
10242 // Erase the pseudo instruction
10243 MI->eraseFromParent();
10248 MachineBasicBlock *
10249 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10251 MachineBasicBlock *MBB) const {
10252 // Emit code to save XMM registers to the stack. The ABI says that the
10253 // number of registers to save is given in %al, so it's theoretically
10254 // possible to do an indirect jump trick to avoid saving all of them,
10255 // however this code takes a simpler approach and just executes all
10256 // of the stores if %al is non-zero. It's less code, and it's probably
10257 // easier on the hardware branch predictor, and stores aren't all that
10258 // expensive anyway.
10260 // Create the new basic blocks. One block contains all the XMM stores,
10261 // and one block is the final destination regardless of whether any
10262 // stores were performed.
10263 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10264 MachineFunction *F = MBB->getParent();
10265 MachineFunction::iterator MBBIter = MBB;
10267 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10268 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10269 F->insert(MBBIter, XMMSaveMBB);
10270 F->insert(MBBIter, EndMBB);
10272 // Transfer the remainder of MBB and its successor edges to EndMBB.
10273 EndMBB->splice(EndMBB->begin(), MBB,
10274 llvm::next(MachineBasicBlock::iterator(MI)),
10276 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10278 // The original block will now fall through to the XMM save block.
10279 MBB->addSuccessor(XMMSaveMBB);
10280 // The XMMSaveMBB will fall through to the end block.
10281 XMMSaveMBB->addSuccessor(EndMBB);
10283 // Now add the instructions.
10284 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10285 DebugLoc DL = MI->getDebugLoc();
10287 unsigned CountReg = MI->getOperand(0).getReg();
10288 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10289 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10291 if (!Subtarget->isTargetWin64()) {
10292 // If %al is 0, branch around the XMM save block.
10293 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10294 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10295 MBB->addSuccessor(EndMBB);
10298 // In the XMM save block, save all the XMM argument registers.
10299 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10300 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10301 MachineMemOperand *MMO =
10302 F->getMachineMemOperand(
10303 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10304 MachineMemOperand::MOStore,
10305 /*Size=*/16, /*Align=*/16);
10306 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10307 .addFrameIndex(RegSaveFrameIndex)
10308 .addImm(/*Scale=*/1)
10309 .addReg(/*IndexReg=*/0)
10310 .addImm(/*Disp=*/Offset)
10311 .addReg(/*Segment=*/0)
10312 .addReg(MI->getOperand(i).getReg())
10313 .addMemOperand(MMO);
10316 MI->eraseFromParent(); // The pseudo instruction is gone now.
10321 MachineBasicBlock *
10322 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10323 MachineBasicBlock *BB) const {
10324 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10325 DebugLoc DL = MI->getDebugLoc();
10327 // To "insert" a SELECT_CC instruction, we actually have to insert the
10328 // diamond control-flow pattern. The incoming instruction knows the
10329 // destination vreg to set, the condition code register to branch on, the
10330 // true/false values to select between, and a branch opcode to use.
10331 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10332 MachineFunction::iterator It = BB;
10338 // cmpTY ccX, r1, r2
10340 // fallthrough --> copy0MBB
10341 MachineBasicBlock *thisMBB = BB;
10342 MachineFunction *F = BB->getParent();
10343 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10344 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10345 F->insert(It, copy0MBB);
10346 F->insert(It, sinkMBB);
10348 // If the EFLAGS register isn't dead in the terminator, then claim that it's
10349 // live into the sink and copy blocks.
10350 const MachineFunction *MF = BB->getParent();
10351 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10352 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10354 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10355 const MachineOperand &MO = MI->getOperand(I);
10356 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10357 unsigned Reg = MO.getReg();
10358 if (Reg != X86::EFLAGS) continue;
10359 copy0MBB->addLiveIn(Reg);
10360 sinkMBB->addLiveIn(Reg);
10363 // Transfer the remainder of BB and its successor edges to sinkMBB.
10364 sinkMBB->splice(sinkMBB->begin(), BB,
10365 llvm::next(MachineBasicBlock::iterator(MI)),
10367 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10369 // Add the true and fallthrough blocks as its successors.
10370 BB->addSuccessor(copy0MBB);
10371 BB->addSuccessor(sinkMBB);
10373 // Create the conditional branch instruction.
10375 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10376 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10379 // %FalseValue = ...
10380 // # fallthrough to sinkMBB
10381 copy0MBB->addSuccessor(sinkMBB);
10384 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10386 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10387 TII->get(X86::PHI), MI->getOperand(0).getReg())
10388 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10389 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10391 MI->eraseFromParent(); // The pseudo instruction is gone now.
10395 MachineBasicBlock *
10396 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10397 MachineBasicBlock *BB) const {
10398 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10399 DebugLoc DL = MI->getDebugLoc();
10401 // The lowering is pretty easy: we're just emitting the call to _alloca. The
10402 // non-trivial part is impdef of ESP.
10403 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
10406 const char *StackProbeSymbol =
10407 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10409 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10410 .addExternalSymbol(StackProbeSymbol)
10411 .addReg(X86::EAX, RegState::Implicit)
10412 .addReg(X86::ESP, RegState::Implicit)
10413 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10414 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10415 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10417 MI->eraseFromParent(); // The pseudo instruction is gone now.
10421 MachineBasicBlock *
10422 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10423 MachineBasicBlock *BB) const {
10424 // This is pretty easy. We're taking the value that we received from
10425 // our load from the relocation, sticking it in either RDI (x86-64)
10426 // or EAX and doing an indirect call. The return value will then
10427 // be in the normal return register.
10428 const X86InstrInfo *TII
10429 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10430 DebugLoc DL = MI->getDebugLoc();
10431 MachineFunction *F = BB->getParent();
10433 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10434 assert(MI->getOperand(3).isGlobal() && "This should be a global");
10436 if (Subtarget->is64Bit()) {
10437 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10438 TII->get(X86::MOV64rm), X86::RDI)
10440 .addImm(0).addReg(0)
10441 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10442 MI->getOperand(3).getTargetFlags())
10444 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10445 addDirectMem(MIB, X86::RDI);
10446 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10447 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10448 TII->get(X86::MOV32rm), X86::EAX)
10450 .addImm(0).addReg(0)
10451 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10452 MI->getOperand(3).getTargetFlags())
10454 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10455 addDirectMem(MIB, X86::EAX);
10457 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10458 TII->get(X86::MOV32rm), X86::EAX)
10459 .addReg(TII->getGlobalBaseReg(F))
10460 .addImm(0).addReg(0)
10461 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10462 MI->getOperand(3).getTargetFlags())
10464 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10465 addDirectMem(MIB, X86::EAX);
10468 MI->eraseFromParent(); // The pseudo instruction is gone now.
10472 MachineBasicBlock *
10473 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10474 MachineBasicBlock *BB) const {
10475 switch (MI->getOpcode()) {
10476 default: assert(false && "Unexpected instr type to insert");
10477 case X86::TAILJMPd64:
10478 case X86::TAILJMPr64:
10479 case X86::TAILJMPm64:
10480 assert(!"TAILJMP64 would not be touched here.");
10481 case X86::TCRETURNdi64:
10482 case X86::TCRETURNri64:
10483 case X86::TCRETURNmi64:
10484 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10485 // On AMD64, additional defs should be added before register allocation.
10486 if (!Subtarget->isTargetWin64()) {
10487 MI->addRegisterDefined(X86::RSI);
10488 MI->addRegisterDefined(X86::RDI);
10489 MI->addRegisterDefined(X86::XMM6);
10490 MI->addRegisterDefined(X86::XMM7);
10491 MI->addRegisterDefined(X86::XMM8);
10492 MI->addRegisterDefined(X86::XMM9);
10493 MI->addRegisterDefined(X86::XMM10);
10494 MI->addRegisterDefined(X86::XMM11);
10495 MI->addRegisterDefined(X86::XMM12);
10496 MI->addRegisterDefined(X86::XMM13);
10497 MI->addRegisterDefined(X86::XMM14);
10498 MI->addRegisterDefined(X86::XMM15);
10501 case X86::WIN_ALLOCA:
10502 return EmitLoweredWinAlloca(MI, BB);
10503 case X86::TLSCall_32:
10504 case X86::TLSCall_64:
10505 return EmitLoweredTLSCall(MI, BB);
10506 case X86::CMOV_GR8:
10507 case X86::CMOV_FR32:
10508 case X86::CMOV_FR64:
10509 case X86::CMOV_V4F32:
10510 case X86::CMOV_V2F64:
10511 case X86::CMOV_V2I64:
10512 case X86::CMOV_GR16:
10513 case X86::CMOV_GR32:
10514 case X86::CMOV_RFP32:
10515 case X86::CMOV_RFP64:
10516 case X86::CMOV_RFP80:
10517 return EmitLoweredSelect(MI, BB);
10519 case X86::FP32_TO_INT16_IN_MEM:
10520 case X86::FP32_TO_INT32_IN_MEM:
10521 case X86::FP32_TO_INT64_IN_MEM:
10522 case X86::FP64_TO_INT16_IN_MEM:
10523 case X86::FP64_TO_INT32_IN_MEM:
10524 case X86::FP64_TO_INT64_IN_MEM:
10525 case X86::FP80_TO_INT16_IN_MEM:
10526 case X86::FP80_TO_INT32_IN_MEM:
10527 case X86::FP80_TO_INT64_IN_MEM: {
10528 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10529 DebugLoc DL = MI->getDebugLoc();
10531 // Change the floating point control register to use "round towards zero"
10532 // mode when truncating to an integer value.
10533 MachineFunction *F = BB->getParent();
10534 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10535 addFrameReference(BuildMI(*BB, MI, DL,
10536 TII->get(X86::FNSTCW16m)), CWFrameIdx);
10538 // Load the old value of the high byte of the control word...
10540 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10541 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10544 // Set the high part to be round to zero...
10545 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10548 // Reload the modified control word now...
10549 addFrameReference(BuildMI(*BB, MI, DL,
10550 TII->get(X86::FLDCW16m)), CWFrameIdx);
10552 // Restore the memory image of control word to original value
10553 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10556 // Get the X86 opcode to use.
10558 switch (MI->getOpcode()) {
10559 default: llvm_unreachable("illegal opcode!");
10560 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10561 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10562 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10563 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10564 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10565 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10566 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10567 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10568 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10572 MachineOperand &Op = MI->getOperand(0);
10574 AM.BaseType = X86AddressMode::RegBase;
10575 AM.Base.Reg = Op.getReg();
10577 AM.BaseType = X86AddressMode::FrameIndexBase;
10578 AM.Base.FrameIndex = Op.getIndex();
10580 Op = MI->getOperand(1);
10582 AM.Scale = Op.getImm();
10583 Op = MI->getOperand(2);
10585 AM.IndexReg = Op.getImm();
10586 Op = MI->getOperand(3);
10587 if (Op.isGlobal()) {
10588 AM.GV = Op.getGlobal();
10590 AM.Disp = Op.getImm();
10592 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10593 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10595 // Reload the original control word now.
10596 addFrameReference(BuildMI(*BB, MI, DL,
10597 TII->get(X86::FLDCW16m)), CWFrameIdx);
10599 MI->eraseFromParent(); // The pseudo instruction is gone now.
10602 // String/text processing lowering.
10603 case X86::PCMPISTRM128REG:
10604 case X86::VPCMPISTRM128REG:
10605 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10606 case X86::PCMPISTRM128MEM:
10607 case X86::VPCMPISTRM128MEM:
10608 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10609 case X86::PCMPESTRM128REG:
10610 case X86::VPCMPESTRM128REG:
10611 return EmitPCMP(MI, BB, 5, false /* in mem */);
10612 case X86::PCMPESTRM128MEM:
10613 case X86::VPCMPESTRM128MEM:
10614 return EmitPCMP(MI, BB, 5, true /* in mem */);
10616 // Thread synchronization.
10618 return EmitMonitor(MI, BB);
10620 return EmitMwait(MI, BB);
10622 // Atomic Lowering.
10623 case X86::ATOMAND32:
10624 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10625 X86::AND32ri, X86::MOV32rm,
10627 X86::NOT32r, X86::EAX,
10628 X86::GR32RegisterClass);
10629 case X86::ATOMOR32:
10630 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10631 X86::OR32ri, X86::MOV32rm,
10633 X86::NOT32r, X86::EAX,
10634 X86::GR32RegisterClass);
10635 case X86::ATOMXOR32:
10636 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10637 X86::XOR32ri, X86::MOV32rm,
10639 X86::NOT32r, X86::EAX,
10640 X86::GR32RegisterClass);
10641 case X86::ATOMNAND32:
10642 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10643 X86::AND32ri, X86::MOV32rm,
10645 X86::NOT32r, X86::EAX,
10646 X86::GR32RegisterClass, true);
10647 case X86::ATOMMIN32:
10648 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10649 case X86::ATOMMAX32:
10650 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10651 case X86::ATOMUMIN32:
10652 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10653 case X86::ATOMUMAX32:
10654 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10656 case X86::ATOMAND16:
10657 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10658 X86::AND16ri, X86::MOV16rm,
10660 X86::NOT16r, X86::AX,
10661 X86::GR16RegisterClass);
10662 case X86::ATOMOR16:
10663 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10664 X86::OR16ri, X86::MOV16rm,
10666 X86::NOT16r, X86::AX,
10667 X86::GR16RegisterClass);
10668 case X86::ATOMXOR16:
10669 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10670 X86::XOR16ri, X86::MOV16rm,
10672 X86::NOT16r, X86::AX,
10673 X86::GR16RegisterClass);
10674 case X86::ATOMNAND16:
10675 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10676 X86::AND16ri, X86::MOV16rm,
10678 X86::NOT16r, X86::AX,
10679 X86::GR16RegisterClass, true);
10680 case X86::ATOMMIN16:
10681 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10682 case X86::ATOMMAX16:
10683 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10684 case X86::ATOMUMIN16:
10685 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10686 case X86::ATOMUMAX16:
10687 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10689 case X86::ATOMAND8:
10690 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10691 X86::AND8ri, X86::MOV8rm,
10693 X86::NOT8r, X86::AL,
10694 X86::GR8RegisterClass);
10696 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10697 X86::OR8ri, X86::MOV8rm,
10699 X86::NOT8r, X86::AL,
10700 X86::GR8RegisterClass);
10701 case X86::ATOMXOR8:
10702 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10703 X86::XOR8ri, X86::MOV8rm,
10705 X86::NOT8r, X86::AL,
10706 X86::GR8RegisterClass);
10707 case X86::ATOMNAND8:
10708 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10709 X86::AND8ri, X86::MOV8rm,
10711 X86::NOT8r, X86::AL,
10712 X86::GR8RegisterClass, true);
10713 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10714 // This group is for 64-bit host.
10715 case X86::ATOMAND64:
10716 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10717 X86::AND64ri32, X86::MOV64rm,
10719 X86::NOT64r, X86::RAX,
10720 X86::GR64RegisterClass);
10721 case X86::ATOMOR64:
10722 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10723 X86::OR64ri32, X86::MOV64rm,
10725 X86::NOT64r, X86::RAX,
10726 X86::GR64RegisterClass);
10727 case X86::ATOMXOR64:
10728 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10729 X86::XOR64ri32, X86::MOV64rm,
10731 X86::NOT64r, X86::RAX,
10732 X86::GR64RegisterClass);
10733 case X86::ATOMNAND64:
10734 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10735 X86::AND64ri32, X86::MOV64rm,
10737 X86::NOT64r, X86::RAX,
10738 X86::GR64RegisterClass, true);
10739 case X86::ATOMMIN64:
10740 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10741 case X86::ATOMMAX64:
10742 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10743 case X86::ATOMUMIN64:
10744 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10745 case X86::ATOMUMAX64:
10746 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10748 // This group does 64-bit operations on a 32-bit host.
10749 case X86::ATOMAND6432:
10750 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10751 X86::AND32rr, X86::AND32rr,
10752 X86::AND32ri, X86::AND32ri,
10754 case X86::ATOMOR6432:
10755 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10756 X86::OR32rr, X86::OR32rr,
10757 X86::OR32ri, X86::OR32ri,
10759 case X86::ATOMXOR6432:
10760 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10761 X86::XOR32rr, X86::XOR32rr,
10762 X86::XOR32ri, X86::XOR32ri,
10764 case X86::ATOMNAND6432:
10765 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10766 X86::AND32rr, X86::AND32rr,
10767 X86::AND32ri, X86::AND32ri,
10769 case X86::ATOMADD6432:
10770 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10771 X86::ADD32rr, X86::ADC32rr,
10772 X86::ADD32ri, X86::ADC32ri,
10774 case X86::ATOMSUB6432:
10775 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10776 X86::SUB32rr, X86::SBB32rr,
10777 X86::SUB32ri, X86::SBB32ri,
10779 case X86::ATOMSWAP6432:
10780 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10781 X86::MOV32rr, X86::MOV32rr,
10782 X86::MOV32ri, X86::MOV32ri,
10784 case X86::VASTART_SAVE_XMM_REGS:
10785 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10787 case X86::VAARG_64:
10788 return EmitVAARG64WithCustomInserter(MI, BB);
10792 //===----------------------------------------------------------------------===//
10793 // X86 Optimization Hooks
10794 //===----------------------------------------------------------------------===//
10796 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10800 const SelectionDAG &DAG,
10801 unsigned Depth) const {
10802 unsigned Opc = Op.getOpcode();
10803 assert((Opc >= ISD::BUILTIN_OP_END ||
10804 Opc == ISD::INTRINSIC_WO_CHAIN ||
10805 Opc == ISD::INTRINSIC_W_CHAIN ||
10806 Opc == ISD::INTRINSIC_VOID) &&
10807 "Should use MaskedValueIsZero if you don't know whether Op"
10808 " is a target node!");
10810 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
10824 // These nodes' second result is a boolean.
10825 if (Op.getResNo() == 0)
10828 case X86ISD::SETCC:
10829 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10830 Mask.getBitWidth() - 1);
10835 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10836 unsigned Depth) const {
10837 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10838 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10839 return Op.getValueType().getScalarType().getSizeInBits();
10845 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10846 /// node is a GlobalAddress + offset.
10847 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10848 const GlobalValue* &GA,
10849 int64_t &Offset) const {
10850 if (N->getOpcode() == X86ISD::Wrapper) {
10851 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10852 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10853 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10857 return TargetLowering::isGAPlusOffset(N, GA, Offset);
10860 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10861 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10862 /// if the load addresses are consecutive, non-overlapping, and in the right
10864 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10865 TargetLowering::DAGCombinerInfo &DCI) {
10866 DebugLoc dl = N->getDebugLoc();
10867 EVT VT = N->getValueType(0);
10869 if (VT.getSizeInBits() != 128)
10872 // Don't create instructions with illegal types after legalize types has run.
10873 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10874 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
10877 SmallVector<SDValue, 16> Elts;
10878 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10879 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10881 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10884 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10885 /// generation and convert it from being a bunch of shuffles and extracts
10886 /// to a simple store and scalar loads to extract the elements.
10887 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10888 const TargetLowering &TLI) {
10889 SDValue InputVector = N->getOperand(0);
10891 // Only operate on vectors of 4 elements, where the alternative shuffling
10892 // gets to be more expensive.
10893 if (InputVector.getValueType() != MVT::v4i32)
10896 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10897 // single use which is a sign-extend or zero-extend, and all elements are
10899 SmallVector<SDNode *, 4> Uses;
10900 unsigned ExtractedElements = 0;
10901 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10902 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10903 if (UI.getUse().getResNo() != InputVector.getResNo())
10906 SDNode *Extract = *UI;
10907 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10910 if (Extract->getValueType(0) != MVT::i32)
10912 if (!Extract->hasOneUse())
10914 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10915 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10917 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10920 // Record which element was extracted.
10921 ExtractedElements |=
10922 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10924 Uses.push_back(Extract);
10927 // If not all the elements were used, this may not be worthwhile.
10928 if (ExtractedElements != 15)
10931 // Ok, we've now decided to do the transformation.
10932 DebugLoc dl = InputVector.getDebugLoc();
10934 // Store the value to a temporary stack slot.
10935 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10936 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10937 MachinePointerInfo(), false, false, 0);
10939 // Replace each use (extract) with a load of the appropriate element.
10940 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10941 UE = Uses.end(); UI != UE; ++UI) {
10942 SDNode *Extract = *UI;
10944 // Compute the element's address.
10945 SDValue Idx = Extract->getOperand(1);
10947 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10948 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10949 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10951 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10952 StackPtr, OffsetVal);
10954 // Load the scalar.
10955 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10956 ScalarAddr, MachinePointerInfo(),
10959 // Replace the exact with the load.
10960 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10963 // The replacement was made in place; don't return anything.
10967 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10968 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10969 const X86Subtarget *Subtarget) {
10970 DebugLoc DL = N->getDebugLoc();
10971 SDValue Cond = N->getOperand(0);
10972 // Get the LHS/RHS of the select.
10973 SDValue LHS = N->getOperand(1);
10974 SDValue RHS = N->getOperand(2);
10976 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10977 // instructions match the semantics of the common C idiom x<y?x:y but not
10978 // x<=y?x:y, because of how they handle negative zero (which can be
10979 // ignored in unsafe-math mode).
10980 if (Subtarget->hasSSE2() &&
10981 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10982 Cond.getOpcode() == ISD::SETCC) {
10983 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10985 unsigned Opcode = 0;
10986 // Check for x CC y ? x : y.
10987 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10988 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10992 // Converting this to a min would handle NaNs incorrectly, and swapping
10993 // the operands would cause it to handle comparisons between positive
10994 // and negative zero incorrectly.
10995 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10996 if (!UnsafeFPMath &&
10997 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10999 std::swap(LHS, RHS);
11001 Opcode = X86ISD::FMIN;
11004 // Converting this to a min would handle comparisons between positive
11005 // and negative zero incorrectly.
11006 if (!UnsafeFPMath &&
11007 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11009 Opcode = X86ISD::FMIN;
11012 // Converting this to a min would handle both negative zeros and NaNs
11013 // incorrectly, but we can swap the operands to fix both.
11014 std::swap(LHS, RHS);
11018 Opcode = X86ISD::FMIN;
11022 // Converting this to a max would handle comparisons between positive
11023 // and negative zero incorrectly.
11024 if (!UnsafeFPMath &&
11025 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11027 Opcode = X86ISD::FMAX;
11030 // Converting this to a max would handle NaNs incorrectly, and swapping
11031 // the operands would cause it to handle comparisons between positive
11032 // and negative zero incorrectly.
11033 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11034 if (!UnsafeFPMath &&
11035 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11037 std::swap(LHS, RHS);
11039 Opcode = X86ISD::FMAX;
11042 // Converting this to a max would handle both negative zeros and NaNs
11043 // incorrectly, but we can swap the operands to fix both.
11044 std::swap(LHS, RHS);
11048 Opcode = X86ISD::FMAX;
11051 // Check for x CC y ? y : x -- a min/max with reversed arms.
11052 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11053 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11057 // Converting this to a min would handle comparisons between positive
11058 // and negative zero incorrectly, and swapping the operands would
11059 // cause it to handle NaNs incorrectly.
11060 if (!UnsafeFPMath &&
11061 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11062 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11064 std::swap(LHS, RHS);
11066 Opcode = X86ISD::FMIN;
11069 // Converting this to a min would handle NaNs incorrectly.
11070 if (!UnsafeFPMath &&
11071 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11073 Opcode = X86ISD::FMIN;
11076 // Converting this to a min would handle both negative zeros and NaNs
11077 // incorrectly, but we can swap the operands to fix both.
11078 std::swap(LHS, RHS);
11082 Opcode = X86ISD::FMIN;
11086 // Converting this to a max would handle NaNs incorrectly.
11087 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11089 Opcode = X86ISD::FMAX;
11092 // Converting this to a max would handle comparisons between positive
11093 // and negative zero incorrectly, and swapping the operands would
11094 // cause it to handle NaNs incorrectly.
11095 if (!UnsafeFPMath &&
11096 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11097 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11099 std::swap(LHS, RHS);
11101 Opcode = X86ISD::FMAX;
11104 // Converting this to a max would handle both negative zeros and NaNs
11105 // incorrectly, but we can swap the operands to fix both.
11106 std::swap(LHS, RHS);
11110 Opcode = X86ISD::FMAX;
11116 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11119 // If this is a select between two integer constants, try to do some
11121 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11122 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11123 // Don't do this for crazy integer types.
11124 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11125 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11126 // so that TrueC (the true value) is larger than FalseC.
11127 bool NeedsCondInvert = false;
11129 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11130 // Efficiently invertible.
11131 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
11132 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
11133 isa<ConstantSDNode>(Cond.getOperand(1))))) {
11134 NeedsCondInvert = true;
11135 std::swap(TrueC, FalseC);
11138 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
11139 if (FalseC->getAPIntValue() == 0 &&
11140 TrueC->getAPIntValue().isPowerOf2()) {
11141 if (NeedsCondInvert) // Invert the condition if needed.
11142 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11143 DAG.getConstant(1, Cond.getValueType()));
11145 // Zero extend the condition if needed.
11146 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11148 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11149 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11150 DAG.getConstant(ShAmt, MVT::i8));
11153 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11154 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11155 if (NeedsCondInvert) // Invert the condition if needed.
11156 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11157 DAG.getConstant(1, Cond.getValueType()));
11159 // Zero extend the condition if needed.
11160 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11161 FalseC->getValueType(0), Cond);
11162 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11163 SDValue(FalseC, 0));
11166 // Optimize cases that will turn into an LEA instruction. This requires
11167 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11168 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11169 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11170 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11172 bool isFastMultiplier = false;
11174 switch ((unsigned char)Diff) {
11176 case 1: // result = add base, cond
11177 case 2: // result = lea base( , cond*2)
11178 case 3: // result = lea base(cond, cond*2)
11179 case 4: // result = lea base( , cond*4)
11180 case 5: // result = lea base(cond, cond*4)
11181 case 8: // result = lea base( , cond*8)
11182 case 9: // result = lea base(cond, cond*8)
11183 isFastMultiplier = true;
11188 if (isFastMultiplier) {
11189 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11190 if (NeedsCondInvert) // Invert the condition if needed.
11191 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11192 DAG.getConstant(1, Cond.getValueType()));
11194 // Zero extend the condition if needed.
11195 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11197 // Scale the condition by the difference.
11199 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11200 DAG.getConstant(Diff, Cond.getValueType()));
11202 // Add the base if non-zero.
11203 if (FalseC->getAPIntValue() != 0)
11204 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11205 SDValue(FalseC, 0));
11215 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11216 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11217 TargetLowering::DAGCombinerInfo &DCI) {
11218 DebugLoc DL = N->getDebugLoc();
11220 // If the flag operand isn't dead, don't touch this CMOV.
11221 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11224 // If this is a select between two integer constants, try to do some
11225 // optimizations. Note that the operands are ordered the opposite of SELECT
11227 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
11228 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11229 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11230 // larger than FalseC (the false value).
11231 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11233 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11234 CC = X86::GetOppositeBranchCondition(CC);
11235 std::swap(TrueC, FalseC);
11238 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
11239 // This is efficient for any integer data type (including i8/i16) and
11241 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11242 SDValue Cond = N->getOperand(3);
11243 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11244 DAG.getConstant(CC, MVT::i8), Cond);
11246 // Zero extend the condition if needed.
11247 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11249 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11250 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11251 DAG.getConstant(ShAmt, MVT::i8));
11252 if (N->getNumValues() == 2) // Dead flag value?
11253 return DCI.CombineTo(N, Cond, SDValue());
11257 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
11258 // for any integer data type, including i8/i16.
11259 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11260 SDValue Cond = N->getOperand(3);
11261 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11262 DAG.getConstant(CC, MVT::i8), Cond);
11264 // Zero extend the condition if needed.
11265 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11266 FalseC->getValueType(0), Cond);
11267 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11268 SDValue(FalseC, 0));
11270 if (N->getNumValues() == 2) // Dead flag value?
11271 return DCI.CombineTo(N, Cond, SDValue());
11275 // Optimize cases that will turn into an LEA instruction. This requires
11276 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11277 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11278 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11279 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11281 bool isFastMultiplier = false;
11283 switch ((unsigned char)Diff) {
11285 case 1: // result = add base, cond
11286 case 2: // result = lea base( , cond*2)
11287 case 3: // result = lea base(cond, cond*2)
11288 case 4: // result = lea base( , cond*4)
11289 case 5: // result = lea base(cond, cond*4)
11290 case 8: // result = lea base( , cond*8)
11291 case 9: // result = lea base(cond, cond*8)
11292 isFastMultiplier = true;
11297 if (isFastMultiplier) {
11298 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11299 SDValue Cond = N->getOperand(3);
11300 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11301 DAG.getConstant(CC, MVT::i8), Cond);
11302 // Zero extend the condition if needed.
11303 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11305 // Scale the condition by the difference.
11307 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11308 DAG.getConstant(Diff, Cond.getValueType()));
11310 // Add the base if non-zero.
11311 if (FalseC->getAPIntValue() != 0)
11312 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11313 SDValue(FalseC, 0));
11314 if (N->getNumValues() == 2) // Dead flag value?
11315 return DCI.CombineTo(N, Cond, SDValue());
11325 /// PerformMulCombine - Optimize a single multiply with constant into two
11326 /// in order to implement it with two cheaper instructions, e.g.
11327 /// LEA + SHL, LEA + LEA.
11328 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11329 TargetLowering::DAGCombinerInfo &DCI) {
11330 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11333 EVT VT = N->getValueType(0);
11334 if (VT != MVT::i64)
11337 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11340 uint64_t MulAmt = C->getZExtValue();
11341 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11344 uint64_t MulAmt1 = 0;
11345 uint64_t MulAmt2 = 0;
11346 if ((MulAmt % 9) == 0) {
11348 MulAmt2 = MulAmt / 9;
11349 } else if ((MulAmt % 5) == 0) {
11351 MulAmt2 = MulAmt / 5;
11352 } else if ((MulAmt % 3) == 0) {
11354 MulAmt2 = MulAmt / 3;
11357 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11358 DebugLoc DL = N->getDebugLoc();
11360 if (isPowerOf2_64(MulAmt2) &&
11361 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11362 // If second multiplifer is pow2, issue it first. We want the multiply by
11363 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11365 std::swap(MulAmt1, MulAmt2);
11368 if (isPowerOf2_64(MulAmt1))
11369 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11370 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11372 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11373 DAG.getConstant(MulAmt1, VT));
11375 if (isPowerOf2_64(MulAmt2))
11376 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11377 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11379 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11380 DAG.getConstant(MulAmt2, VT));
11382 // Do not add new nodes to DAG combiner worklist.
11383 DCI.CombineTo(N, NewMul, false);
11388 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11389 SDValue N0 = N->getOperand(0);
11390 SDValue N1 = N->getOperand(1);
11391 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11392 EVT VT = N0.getValueType();
11394 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11395 // since the result of setcc_c is all zero's or all ones.
11396 if (N1C && N0.getOpcode() == ISD::AND &&
11397 N0.getOperand(1).getOpcode() == ISD::Constant) {
11398 SDValue N00 = N0.getOperand(0);
11399 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11400 ((N00.getOpcode() == ISD::ANY_EXTEND ||
11401 N00.getOpcode() == ISD::ZERO_EXTEND) &&
11402 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11403 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11404 APInt ShAmt = N1C->getAPIntValue();
11405 Mask = Mask.shl(ShAmt);
11407 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11408 N00, DAG.getConstant(Mask, VT));
11415 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11417 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11418 const X86Subtarget *Subtarget) {
11419 EVT VT = N->getValueType(0);
11420 if (!VT.isVector() && VT.isInteger() &&
11421 N->getOpcode() == ISD::SHL)
11422 return PerformSHLCombine(N, DAG);
11424 // On X86 with SSE2 support, we can transform this to a vector shift if
11425 // all elements are shifted by the same amount. We can't do this in legalize
11426 // because the a constant vector is typically transformed to a constant pool
11427 // so we have no knowledge of the shift amount.
11428 if (!Subtarget->hasSSE2())
11431 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11434 SDValue ShAmtOp = N->getOperand(1);
11435 EVT EltVT = VT.getVectorElementType();
11436 DebugLoc DL = N->getDebugLoc();
11437 SDValue BaseShAmt = SDValue();
11438 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11439 unsigned NumElts = VT.getVectorNumElements();
11441 for (; i != NumElts; ++i) {
11442 SDValue Arg = ShAmtOp.getOperand(i);
11443 if (Arg.getOpcode() == ISD::UNDEF) continue;
11447 for (; i != NumElts; ++i) {
11448 SDValue Arg = ShAmtOp.getOperand(i);
11449 if (Arg.getOpcode() == ISD::UNDEF) continue;
11450 if (Arg != BaseShAmt) {
11454 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11455 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11456 SDValue InVec = ShAmtOp.getOperand(0);
11457 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11458 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11460 for (; i != NumElts; ++i) {
11461 SDValue Arg = InVec.getOperand(i);
11462 if (Arg.getOpcode() == ISD::UNDEF) continue;
11466 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11467 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11468 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11469 if (C->getZExtValue() == SplatIdx)
11470 BaseShAmt = InVec.getOperand(1);
11473 if (BaseShAmt.getNode() == 0)
11474 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11475 DAG.getIntPtrConstant(0));
11479 // The shift amount is an i32.
11480 if (EltVT.bitsGT(MVT::i32))
11481 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11482 else if (EltVT.bitsLT(MVT::i32))
11483 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11485 // The shift amount is identical so we can do a vector shift.
11486 SDValue ValOp = N->getOperand(0);
11487 switch (N->getOpcode()) {
11489 llvm_unreachable("Unknown shift opcode!");
11492 if (VT == MVT::v2i64)
11493 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11494 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11496 if (VT == MVT::v4i32)
11497 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11498 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11500 if (VT == MVT::v8i16)
11501 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11502 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11506 if (VT == MVT::v4i32)
11507 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11508 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11510 if (VT == MVT::v8i16)
11511 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11512 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11516 if (VT == MVT::v2i64)
11517 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11518 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11520 if (VT == MVT::v4i32)
11521 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11522 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11524 if (VT == MVT::v8i16)
11525 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11526 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11534 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11535 TargetLowering::DAGCombinerInfo &DCI,
11536 const X86Subtarget *Subtarget) {
11537 if (DCI.isBeforeLegalizeOps())
11540 // Want to form PANDN nodes, in the hopes of then easily combining them with
11541 // OR and AND nodes to form PBLEND/PSIGN.
11542 EVT VT = N->getValueType(0);
11543 if (VT != MVT::v2i64)
11546 SDValue N0 = N->getOperand(0);
11547 SDValue N1 = N->getOperand(1);
11548 DebugLoc DL = N->getDebugLoc();
11550 // Check LHS for vnot
11551 if (N0.getOpcode() == ISD::XOR &&
11552 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11553 return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11555 // Check RHS for vnot
11556 if (N1.getOpcode() == ISD::XOR &&
11557 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11558 return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11563 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11564 TargetLowering::DAGCombinerInfo &DCI,
11565 const X86Subtarget *Subtarget) {
11566 if (DCI.isBeforeLegalizeOps())
11569 EVT VT = N->getValueType(0);
11570 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11573 SDValue N0 = N->getOperand(0);
11574 SDValue N1 = N->getOperand(1);
11576 // look for psign/blend
11577 if (Subtarget->hasSSSE3()) {
11578 if (VT == MVT::v2i64) {
11579 // Canonicalize pandn to RHS
11580 if (N0.getOpcode() == X86ISD::PANDN)
11582 // or (and (m, x), (pandn m, y))
11583 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11584 SDValue Mask = N1.getOperand(0);
11585 SDValue X = N1.getOperand(1);
11587 if (N0.getOperand(0) == Mask)
11588 Y = N0.getOperand(1);
11589 if (N0.getOperand(1) == Mask)
11590 Y = N0.getOperand(0);
11592 // Check to see if the mask appeared in both the AND and PANDN and
11596 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11597 if (Mask.getOpcode() != ISD::BITCAST ||
11598 X.getOpcode() != ISD::BITCAST ||
11599 Y.getOpcode() != ISD::BITCAST)
11602 // Look through mask bitcast.
11603 Mask = Mask.getOperand(0);
11604 EVT MaskVT = Mask.getValueType();
11606 // Validate that the Mask operand is a vector sra node. The sra node
11607 // will be an intrinsic.
11608 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11611 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11612 // there is no psrai.b
11613 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11614 case Intrinsic::x86_sse2_psrai_w:
11615 case Intrinsic::x86_sse2_psrai_d:
11617 default: return SDValue();
11620 // Check that the SRA is all signbits.
11621 SDValue SraC = Mask.getOperand(2);
11622 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
11623 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11624 if ((SraAmt + 1) != EltBits)
11627 DebugLoc DL = N->getDebugLoc();
11629 // Now we know we at least have a plendvb with the mask val. See if
11630 // we can form a psignb/w/d.
11631 // psign = x.type == y.type == mask.type && y = sub(0, x);
11632 X = X.getOperand(0);
11633 Y = Y.getOperand(0);
11634 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11635 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11636 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11639 case 8: Opc = X86ISD::PSIGNB; break;
11640 case 16: Opc = X86ISD::PSIGNW; break;
11641 case 32: Opc = X86ISD::PSIGND; break;
11645 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11646 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11649 // PBLENDVB only available on SSE 4.1
11650 if (!Subtarget->hasSSE41())
11653 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11654 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11655 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11656 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11657 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11662 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11663 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11665 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11667 if (!N0.hasOneUse() || !N1.hasOneUse())
11670 SDValue ShAmt0 = N0.getOperand(1);
11671 if (ShAmt0.getValueType() != MVT::i8)
11673 SDValue ShAmt1 = N1.getOperand(1);
11674 if (ShAmt1.getValueType() != MVT::i8)
11676 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11677 ShAmt0 = ShAmt0.getOperand(0);
11678 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11679 ShAmt1 = ShAmt1.getOperand(0);
11681 DebugLoc DL = N->getDebugLoc();
11682 unsigned Opc = X86ISD::SHLD;
11683 SDValue Op0 = N0.getOperand(0);
11684 SDValue Op1 = N1.getOperand(0);
11685 if (ShAmt0.getOpcode() == ISD::SUB) {
11686 Opc = X86ISD::SHRD;
11687 std::swap(Op0, Op1);
11688 std::swap(ShAmt0, ShAmt1);
11691 unsigned Bits = VT.getSizeInBits();
11692 if (ShAmt1.getOpcode() == ISD::SUB) {
11693 SDValue Sum = ShAmt1.getOperand(0);
11694 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11695 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11696 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11697 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11698 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11699 return DAG.getNode(Opc, DL, VT,
11701 DAG.getNode(ISD::TRUNCATE, DL,
11704 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11705 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11707 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11708 return DAG.getNode(Opc, DL, VT,
11709 N0.getOperand(0), N1.getOperand(0),
11710 DAG.getNode(ISD::TRUNCATE, DL,
11717 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11718 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11719 const X86Subtarget *Subtarget) {
11720 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
11721 // the FP state in cases where an emms may be missing.
11722 // A preferable solution to the general problem is to figure out the right
11723 // places to insert EMMS. This qualifies as a quick hack.
11725 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11726 StoreSDNode *St = cast<StoreSDNode>(N);
11727 EVT VT = St->getValue().getValueType();
11728 if (VT.getSizeInBits() != 64)
11731 const Function *F = DAG.getMachineFunction().getFunction();
11732 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11733 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11734 && Subtarget->hasSSE2();
11735 if ((VT.isVector() ||
11736 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11737 isa<LoadSDNode>(St->getValue()) &&
11738 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11739 St->getChain().hasOneUse() && !St->isVolatile()) {
11740 SDNode* LdVal = St->getValue().getNode();
11741 LoadSDNode *Ld = 0;
11742 int TokenFactorIndex = -1;
11743 SmallVector<SDValue, 8> Ops;
11744 SDNode* ChainVal = St->getChain().getNode();
11745 // Must be a store of a load. We currently handle two cases: the load
11746 // is a direct child, and it's under an intervening TokenFactor. It is
11747 // possible to dig deeper under nested TokenFactors.
11748 if (ChainVal == LdVal)
11749 Ld = cast<LoadSDNode>(St->getChain());
11750 else if (St->getValue().hasOneUse() &&
11751 ChainVal->getOpcode() == ISD::TokenFactor) {
11752 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11753 if (ChainVal->getOperand(i).getNode() == LdVal) {
11754 TokenFactorIndex = i;
11755 Ld = cast<LoadSDNode>(St->getValue());
11757 Ops.push_back(ChainVal->getOperand(i));
11761 if (!Ld || !ISD::isNormalLoad(Ld))
11764 // If this is not the MMX case, i.e. we are just turning i64 load/store
11765 // into f64 load/store, avoid the transformation if there are multiple
11766 // uses of the loaded value.
11767 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11770 DebugLoc LdDL = Ld->getDebugLoc();
11771 DebugLoc StDL = N->getDebugLoc();
11772 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11773 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11775 if (Subtarget->is64Bit() || F64IsLegal) {
11776 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11777 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11778 Ld->getPointerInfo(), Ld->isVolatile(),
11779 Ld->isNonTemporal(), Ld->getAlignment());
11780 SDValue NewChain = NewLd.getValue(1);
11781 if (TokenFactorIndex != -1) {
11782 Ops.push_back(NewChain);
11783 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11786 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11787 St->getPointerInfo(),
11788 St->isVolatile(), St->isNonTemporal(),
11789 St->getAlignment());
11792 // Otherwise, lower to two pairs of 32-bit loads / stores.
11793 SDValue LoAddr = Ld->getBasePtr();
11794 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11795 DAG.getConstant(4, MVT::i32));
11797 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11798 Ld->getPointerInfo(),
11799 Ld->isVolatile(), Ld->isNonTemporal(),
11800 Ld->getAlignment());
11801 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11802 Ld->getPointerInfo().getWithOffset(4),
11803 Ld->isVolatile(), Ld->isNonTemporal(),
11804 MinAlign(Ld->getAlignment(), 4));
11806 SDValue NewChain = LoLd.getValue(1);
11807 if (TokenFactorIndex != -1) {
11808 Ops.push_back(LoLd);
11809 Ops.push_back(HiLd);
11810 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11814 LoAddr = St->getBasePtr();
11815 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11816 DAG.getConstant(4, MVT::i32));
11818 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11819 St->getPointerInfo(),
11820 St->isVolatile(), St->isNonTemporal(),
11821 St->getAlignment());
11822 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11823 St->getPointerInfo().getWithOffset(4),
11825 St->isNonTemporal(),
11826 MinAlign(St->getAlignment(), 4));
11827 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11832 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11833 /// X86ISD::FXOR nodes.
11834 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11835 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11836 // F[X]OR(0.0, x) -> x
11837 // F[X]OR(x, 0.0) -> x
11838 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11839 if (C->getValueAPF().isPosZero())
11840 return N->getOperand(1);
11841 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11842 if (C->getValueAPF().isPosZero())
11843 return N->getOperand(0);
11847 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11848 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11849 // FAND(0.0, x) -> 0.0
11850 // FAND(x, 0.0) -> 0.0
11851 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11852 if (C->getValueAPF().isPosZero())
11853 return N->getOperand(0);
11854 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11855 if (C->getValueAPF().isPosZero())
11856 return N->getOperand(1);
11860 static SDValue PerformBTCombine(SDNode *N,
11862 TargetLowering::DAGCombinerInfo &DCI) {
11863 // BT ignores high bits in the bit index operand.
11864 SDValue Op1 = N->getOperand(1);
11865 if (Op1.hasOneUse()) {
11866 unsigned BitWidth = Op1.getValueSizeInBits();
11867 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11868 APInt KnownZero, KnownOne;
11869 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11870 !DCI.isBeforeLegalizeOps());
11871 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11872 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11873 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11874 DCI.CommitTargetLoweringOpt(TLO);
11879 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11880 SDValue Op = N->getOperand(0);
11881 if (Op.getOpcode() == ISD::BITCAST)
11882 Op = Op.getOperand(0);
11883 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11884 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11885 VT.getVectorElementType().getSizeInBits() ==
11886 OpVT.getVectorElementType().getSizeInBits()) {
11887 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11892 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11893 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
11894 // (and (i32 x86isd::setcc_carry), 1)
11895 // This eliminates the zext. This transformation is necessary because
11896 // ISD::SETCC is always legalized to i8.
11897 DebugLoc dl = N->getDebugLoc();
11898 SDValue N0 = N->getOperand(0);
11899 EVT VT = N->getValueType(0);
11900 if (N0.getOpcode() == ISD::AND &&
11902 N0.getOperand(0).hasOneUse()) {
11903 SDValue N00 = N0.getOperand(0);
11904 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11906 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11907 if (!C || C->getZExtValue() != 1)
11909 return DAG.getNode(ISD::AND, dl, VT,
11910 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11911 N00.getOperand(0), N00.getOperand(1)),
11912 DAG.getConstant(1, VT));
11918 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
11919 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
11920 unsigned X86CC = N->getConstantOperandVal(0);
11921 SDValue EFLAG = N->getOperand(1);
11922 DebugLoc DL = N->getDebugLoc();
11924 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
11925 // a zext and produces an all-ones bit which is more useful than 0/1 in some
11927 if (X86CC == X86::COND_B)
11928 return DAG.getNode(ISD::AND, DL, MVT::i8,
11929 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
11930 DAG.getConstant(X86CC, MVT::i8), EFLAG),
11931 DAG.getConstant(1, MVT::i8));
11936 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
11937 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
11938 X86TargetLowering::DAGCombinerInfo &DCI) {
11939 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
11940 // the result is either zero or one (depending on the input carry bit).
11941 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
11942 if (X86::isZeroNode(N->getOperand(0)) &&
11943 X86::isZeroNode(N->getOperand(1)) &&
11944 // We don't have a good way to replace an EFLAGS use, so only do this when
11946 SDValue(N, 1).use_empty()) {
11947 DebugLoc DL = N->getDebugLoc();
11948 EVT VT = N->getValueType(0);
11949 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
11950 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
11951 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
11952 DAG.getConstant(X86::COND_B,MVT::i8),
11954 DAG.getConstant(1, VT));
11955 return DCI.CombineTo(N, Res1, CarryOut);
11961 // fold (add Y, (sete X, 0)) -> adc 0, Y
11962 // (add Y, (setne X, 0)) -> sbb -1, Y
11963 // (sub (sete X, 0), Y) -> sbb 0, Y
11964 // (sub (setne X, 0), Y) -> adc -1, Y
11965 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
11966 DebugLoc DL = N->getDebugLoc();
11968 // Look through ZExts.
11969 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
11970 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
11973 SDValue SetCC = Ext.getOperand(0);
11974 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
11977 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
11978 if (CC != X86::COND_E && CC != X86::COND_NE)
11981 SDValue Cmp = SetCC.getOperand(1);
11982 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
11983 !X86::isZeroNode(Cmp.getOperand(1)) ||
11984 !Cmp.getOperand(0).getValueType().isInteger())
11987 SDValue CmpOp0 = Cmp.getOperand(0);
11988 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
11989 DAG.getConstant(1, CmpOp0.getValueType()));
11991 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
11992 if (CC == X86::COND_NE)
11993 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
11994 DL, OtherVal.getValueType(), OtherVal,
11995 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
11996 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
11997 DL, OtherVal.getValueType(), OtherVal,
11998 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12001 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12002 DAGCombinerInfo &DCI) const {
12003 SelectionDAG &DAG = DCI.DAG;
12004 switch (N->getOpcode()) {
12006 case ISD::EXTRACT_VECTOR_ELT:
12007 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12008 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
12009 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
12011 case ISD::SUB: return OptimizeConditonalInDecrement(N, DAG);
12012 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
12013 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
12016 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
12017 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
12018 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
12019 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
12021 case X86ISD::FOR: return PerformFORCombine(N, DAG);
12022 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
12023 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
12024 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
12025 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
12026 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
12027 case X86ISD::SHUFPS: // Handle all target specific shuffles
12028 case X86ISD::SHUFPD:
12029 case X86ISD::PALIGN:
12030 case X86ISD::PUNPCKHBW:
12031 case X86ISD::PUNPCKHWD:
12032 case X86ISD::PUNPCKHDQ:
12033 case X86ISD::PUNPCKHQDQ:
12034 case X86ISD::UNPCKHPS:
12035 case X86ISD::UNPCKHPD:
12036 case X86ISD::PUNPCKLBW:
12037 case X86ISD::PUNPCKLWD:
12038 case X86ISD::PUNPCKLDQ:
12039 case X86ISD::PUNPCKLQDQ:
12040 case X86ISD::UNPCKLPS:
12041 case X86ISD::UNPCKLPD:
12042 case X86ISD::VUNPCKLPS:
12043 case X86ISD::VUNPCKLPD:
12044 case X86ISD::VUNPCKLPSY:
12045 case X86ISD::VUNPCKLPDY:
12046 case X86ISD::MOVHLPS:
12047 case X86ISD::MOVLHPS:
12048 case X86ISD::PSHUFD:
12049 case X86ISD::PSHUFHW:
12050 case X86ISD::PSHUFLW:
12051 case X86ISD::MOVSS:
12052 case X86ISD::MOVSD:
12053 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12059 /// isTypeDesirableForOp - Return true if the target has native support for
12060 /// the specified value type and it is 'desirable' to use the type for the
12061 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12062 /// instruction encodings are longer and some i16 instructions are slow.
12063 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12064 if (!isTypeLegal(VT))
12066 if (VT != MVT::i16)
12073 case ISD::SIGN_EXTEND:
12074 case ISD::ZERO_EXTEND:
12075 case ISD::ANY_EXTEND:
12088 /// IsDesirableToPromoteOp - This method query the target whether it is
12089 /// beneficial for dag combiner to promote the specified node. If true, it
12090 /// should return the desired promotion type by reference.
12091 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12092 EVT VT = Op.getValueType();
12093 if (VT != MVT::i16)
12096 bool Promote = false;
12097 bool Commute = false;
12098 switch (Op.getOpcode()) {
12101 LoadSDNode *LD = cast<LoadSDNode>(Op);
12102 // If the non-extending load has a single use and it's not live out, then it
12103 // might be folded.
12104 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12105 Op.hasOneUse()*/) {
12106 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12107 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12108 // The only case where we'd want to promote LOAD (rather then it being
12109 // promoted as an operand is when it's only use is liveout.
12110 if (UI->getOpcode() != ISD::CopyToReg)
12117 case ISD::SIGN_EXTEND:
12118 case ISD::ZERO_EXTEND:
12119 case ISD::ANY_EXTEND:
12124 SDValue N0 = Op.getOperand(0);
12125 // Look out for (store (shl (load), x)).
12126 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12139 SDValue N0 = Op.getOperand(0);
12140 SDValue N1 = Op.getOperand(1);
12141 if (!Commute && MayFoldLoad(N1))
12143 // Avoid disabling potential load folding opportunities.
12144 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12146 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12156 //===----------------------------------------------------------------------===//
12157 // X86 Inline Assembly Support
12158 //===----------------------------------------------------------------------===//
12160 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12161 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12163 std::string AsmStr = IA->getAsmString();
12165 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12166 SmallVector<StringRef, 4> AsmPieces;
12167 SplitString(AsmStr, AsmPieces, ";\n");
12169 switch (AsmPieces.size()) {
12170 default: return false;
12172 AsmStr = AsmPieces[0];
12174 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
12176 // FIXME: this should verify that we are targetting a 486 or better. If not,
12177 // we will turn this bswap into something that will be lowered to logical ops
12178 // instead of emitting the bswap asm. For now, we don't support 486 or lower
12179 // so don't worry about this.
12181 if (AsmPieces.size() == 2 &&
12182 (AsmPieces[0] == "bswap" ||
12183 AsmPieces[0] == "bswapq" ||
12184 AsmPieces[0] == "bswapl") &&
12185 (AsmPieces[1] == "$0" ||
12186 AsmPieces[1] == "${0:q}")) {
12187 // No need to check constraints, nothing other than the equivalent of
12188 // "=r,0" would be valid here.
12189 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12190 if (!Ty || Ty->getBitWidth() % 16 != 0)
12192 return IntrinsicLowering::LowerToByteSwap(CI);
12194 // rorw $$8, ${0:w} --> llvm.bswap.i16
12195 if (CI->getType()->isIntegerTy(16) &&
12196 AsmPieces.size() == 3 &&
12197 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12198 AsmPieces[1] == "$$8," &&
12199 AsmPieces[2] == "${0:w}" &&
12200 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12202 const std::string &ConstraintsStr = IA->getConstraintString();
12203 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12204 std::sort(AsmPieces.begin(), AsmPieces.end());
12205 if (AsmPieces.size() == 4 &&
12206 AsmPieces[0] == "~{cc}" &&
12207 AsmPieces[1] == "~{dirflag}" &&
12208 AsmPieces[2] == "~{flags}" &&
12209 AsmPieces[3] == "~{fpsr}") {
12210 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12211 if (!Ty || Ty->getBitWidth() % 16 != 0)
12213 return IntrinsicLowering::LowerToByteSwap(CI);
12218 if (CI->getType()->isIntegerTy(32) &&
12219 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12220 SmallVector<StringRef, 4> Words;
12221 SplitString(AsmPieces[0], Words, " \t,");
12222 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12223 Words[2] == "${0:w}") {
12225 SplitString(AsmPieces[1], Words, " \t,");
12226 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12227 Words[2] == "$0") {
12229 SplitString(AsmPieces[2], Words, " \t,");
12230 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12231 Words[2] == "${0:w}") {
12233 const std::string &ConstraintsStr = IA->getConstraintString();
12234 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12235 std::sort(AsmPieces.begin(), AsmPieces.end());
12236 if (AsmPieces.size() == 4 &&
12237 AsmPieces[0] == "~{cc}" &&
12238 AsmPieces[1] == "~{dirflag}" &&
12239 AsmPieces[2] == "~{flags}" &&
12240 AsmPieces[3] == "~{fpsr}") {
12241 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12242 if (!Ty || Ty->getBitWidth() % 16 != 0)
12244 return IntrinsicLowering::LowerToByteSwap(CI);
12251 if (CI->getType()->isIntegerTy(64)) {
12252 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12253 if (Constraints.size() >= 2 &&
12254 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12255 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12256 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
12257 SmallVector<StringRef, 4> Words;
12258 SplitString(AsmPieces[0], Words, " \t");
12259 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12261 SplitString(AsmPieces[1], Words, " \t");
12262 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12264 SplitString(AsmPieces[2], Words, " \t,");
12265 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12266 Words[2] == "%edx") {
12267 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12268 if (!Ty || Ty->getBitWidth() % 16 != 0)
12270 return IntrinsicLowering::LowerToByteSwap(CI);
12283 /// getConstraintType - Given a constraint letter, return the type of
12284 /// constraint it is for this target.
12285 X86TargetLowering::ConstraintType
12286 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12287 if (Constraint.size() == 1) {
12288 switch (Constraint[0]) {
12298 return C_RegisterClass;
12322 return TargetLowering::getConstraintType(Constraint);
12325 /// Examine constraint type and operand type and determine a weight value.
12326 /// This object must already have been set up with the operand type
12327 /// and the current alternative constraint selected.
12328 TargetLowering::ConstraintWeight
12329 X86TargetLowering::getSingleConstraintMatchWeight(
12330 AsmOperandInfo &info, const char *constraint) const {
12331 ConstraintWeight weight = CW_Invalid;
12332 Value *CallOperandVal = info.CallOperandVal;
12333 // If we don't have a value, we can't do a match,
12334 // but allow it at the lowest weight.
12335 if (CallOperandVal == NULL)
12337 const Type *type = CallOperandVal->getType();
12338 // Look at the constraint type.
12339 switch (*constraint) {
12341 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12352 if (CallOperandVal->getType()->isIntegerTy())
12353 weight = CW_SpecificReg;
12358 if (type->isFloatingPointTy())
12359 weight = CW_SpecificReg;
12362 if (type->isX86_MMXTy() && Subtarget->hasMMX())
12363 weight = CW_SpecificReg;
12367 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12368 weight = CW_Register;
12371 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12372 if (C->getZExtValue() <= 31)
12373 weight = CW_Constant;
12377 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12378 if (C->getZExtValue() <= 63)
12379 weight = CW_Constant;
12383 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12384 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12385 weight = CW_Constant;
12389 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12390 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12391 weight = CW_Constant;
12395 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12396 if (C->getZExtValue() <= 3)
12397 weight = CW_Constant;
12401 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12402 if (C->getZExtValue() <= 0xff)
12403 weight = CW_Constant;
12408 if (dyn_cast<ConstantFP>(CallOperandVal)) {
12409 weight = CW_Constant;
12413 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12414 if ((C->getSExtValue() >= -0x80000000LL) &&
12415 (C->getSExtValue() <= 0x7fffffffLL))
12416 weight = CW_Constant;
12420 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12421 if (C->getZExtValue() <= 0xffffffff)
12422 weight = CW_Constant;
12429 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12430 /// with another that has more specific requirements based on the type of the
12431 /// corresponding operand.
12432 const char *X86TargetLowering::
12433 LowerXConstraint(EVT ConstraintVT) const {
12434 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12435 // 'f' like normal targets.
12436 if (ConstraintVT.isFloatingPoint()) {
12437 if (Subtarget->hasXMMInt())
12439 if (Subtarget->hasXMM())
12443 return TargetLowering::LowerXConstraint(ConstraintVT);
12446 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12447 /// vector. If it is invalid, don't add anything to Ops.
12448 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12450 std::vector<SDValue>&Ops,
12451 SelectionDAG &DAG) const {
12452 SDValue Result(0, 0);
12454 switch (Constraint) {
12457 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12458 if (C->getZExtValue() <= 31) {
12459 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12465 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12466 if (C->getZExtValue() <= 63) {
12467 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12473 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12474 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12475 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12481 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12482 if (C->getZExtValue() <= 255) {
12483 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12489 // 32-bit signed value
12490 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12491 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12492 C->getSExtValue())) {
12493 // Widen to 64 bits here to get it sign extended.
12494 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12497 // FIXME gcc accepts some relocatable values here too, but only in certain
12498 // memory models; it's complicated.
12503 // 32-bit unsigned value
12504 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12505 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12506 C->getZExtValue())) {
12507 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12511 // FIXME gcc accepts some relocatable values here too, but only in certain
12512 // memory models; it's complicated.
12516 // Literal immediates are always ok.
12517 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12518 // Widen to 64 bits here to get it sign extended.
12519 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12523 // In any sort of PIC mode addresses need to be computed at runtime by
12524 // adding in a register or some sort of table lookup. These can't
12525 // be used as immediates.
12526 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12529 // If we are in non-pic codegen mode, we allow the address of a global (with
12530 // an optional displacement) to be used with 'i'.
12531 GlobalAddressSDNode *GA = 0;
12532 int64_t Offset = 0;
12534 // Match either (GA), (GA+C), (GA+C1+C2), etc.
12536 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12537 Offset += GA->getOffset();
12539 } else if (Op.getOpcode() == ISD::ADD) {
12540 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12541 Offset += C->getZExtValue();
12542 Op = Op.getOperand(0);
12545 } else if (Op.getOpcode() == ISD::SUB) {
12546 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12547 Offset += -C->getZExtValue();
12548 Op = Op.getOperand(0);
12553 // Otherwise, this isn't something we can handle, reject it.
12557 const GlobalValue *GV = GA->getGlobal();
12558 // If we require an extra load to get this address, as in PIC mode, we
12559 // can't accept it.
12560 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12561 getTargetMachine())))
12564 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12565 GA->getValueType(0), Offset);
12570 if (Result.getNode()) {
12571 Ops.push_back(Result);
12574 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12577 std::vector<unsigned> X86TargetLowering::
12578 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12580 if (Constraint.size() == 1) {
12581 // FIXME: not handling fp-stack yet!
12582 switch (Constraint[0]) { // GCC X86 Constraint Letters
12583 default: break; // Unknown constraint letter
12584 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12585 if (Subtarget->is64Bit()) {
12586 if (VT == MVT::i32)
12587 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12588 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12589 X86::R10D,X86::R11D,X86::R12D,
12590 X86::R13D,X86::R14D,X86::R15D,
12591 X86::EBP, X86::ESP, 0);
12592 else if (VT == MVT::i16)
12593 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
12594 X86::SI, X86::DI, X86::R8W,X86::R9W,
12595 X86::R10W,X86::R11W,X86::R12W,
12596 X86::R13W,X86::R14W,X86::R15W,
12597 X86::BP, X86::SP, 0);
12598 else if (VT == MVT::i8)
12599 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
12600 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12601 X86::R10B,X86::R11B,X86::R12B,
12602 X86::R13B,X86::R14B,X86::R15B,
12603 X86::BPL, X86::SPL, 0);
12605 else if (VT == MVT::i64)
12606 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12607 X86::RSI, X86::RDI, X86::R8, X86::R9,
12608 X86::R10, X86::R11, X86::R12,
12609 X86::R13, X86::R14, X86::R15,
12610 X86::RBP, X86::RSP, 0);
12614 // 32-bit fallthrough
12615 case 'Q': // Q_REGS
12616 if (VT == MVT::i32)
12617 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12618 else if (VT == MVT::i16)
12619 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12620 else if (VT == MVT::i8)
12621 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12622 else if (VT == MVT::i64)
12623 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12628 return std::vector<unsigned>();
12631 std::pair<unsigned, const TargetRegisterClass*>
12632 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12634 // First, see if this is a constraint that directly corresponds to an LLVM
12636 if (Constraint.size() == 1) {
12637 // GCC Constraint Letters
12638 switch (Constraint[0]) {
12640 case 'r': // GENERAL_REGS
12641 case 'l': // INDEX_REGS
12643 return std::make_pair(0U, X86::GR8RegisterClass);
12644 if (VT == MVT::i16)
12645 return std::make_pair(0U, X86::GR16RegisterClass);
12646 if (VT == MVT::i32 || !Subtarget->is64Bit())
12647 return std::make_pair(0U, X86::GR32RegisterClass);
12648 return std::make_pair(0U, X86::GR64RegisterClass);
12649 case 'R': // LEGACY_REGS
12651 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12652 if (VT == MVT::i16)
12653 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12654 if (VT == MVT::i32 || !Subtarget->is64Bit())
12655 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12656 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12657 case 'f': // FP Stack registers.
12658 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12659 // value to the correct fpstack register class.
12660 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12661 return std::make_pair(0U, X86::RFP32RegisterClass);
12662 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12663 return std::make_pair(0U, X86::RFP64RegisterClass);
12664 return std::make_pair(0U, X86::RFP80RegisterClass);
12665 case 'y': // MMX_REGS if MMX allowed.
12666 if (!Subtarget->hasMMX()) break;
12667 return std::make_pair(0U, X86::VR64RegisterClass);
12668 case 'Y': // SSE_REGS if SSE2 allowed
12669 if (!Subtarget->hasXMMInt()) break;
12671 case 'x': // SSE_REGS if SSE1 allowed
12672 if (!Subtarget->hasXMM()) break;
12674 switch (VT.getSimpleVT().SimpleTy) {
12676 // Scalar SSE types.
12679 return std::make_pair(0U, X86::FR32RegisterClass);
12682 return std::make_pair(0U, X86::FR64RegisterClass);
12690 return std::make_pair(0U, X86::VR128RegisterClass);
12696 // Use the default implementation in TargetLowering to convert the register
12697 // constraint into a member of a register class.
12698 std::pair<unsigned, const TargetRegisterClass*> Res;
12699 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12701 // Not found as a standard register?
12702 if (Res.second == 0) {
12703 // Map st(0) -> st(7) -> ST0
12704 if (Constraint.size() == 7 && Constraint[0] == '{' &&
12705 tolower(Constraint[1]) == 's' &&
12706 tolower(Constraint[2]) == 't' &&
12707 Constraint[3] == '(' &&
12708 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12709 Constraint[5] == ')' &&
12710 Constraint[6] == '}') {
12712 Res.first = X86::ST0+Constraint[4]-'0';
12713 Res.second = X86::RFP80RegisterClass;
12717 // GCC allows "st(0)" to be called just plain "st".
12718 if (StringRef("{st}").equals_lower(Constraint)) {
12719 Res.first = X86::ST0;
12720 Res.second = X86::RFP80RegisterClass;
12725 if (StringRef("{flags}").equals_lower(Constraint)) {
12726 Res.first = X86::EFLAGS;
12727 Res.second = X86::CCRRegisterClass;
12731 // 'A' means EAX + EDX.
12732 if (Constraint == "A") {
12733 Res.first = X86::EAX;
12734 Res.second = X86::GR32_ADRegisterClass;
12740 // Otherwise, check to see if this is a register class of the wrong value
12741 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12742 // turn into {ax},{dx}.
12743 if (Res.second->hasType(VT))
12744 return Res; // Correct type already, nothing to do.
12746 // All of the single-register GCC register classes map their values onto
12747 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
12748 // really want an 8-bit or 32-bit register, map to the appropriate register
12749 // class and return the appropriate register.
12750 if (Res.second == X86::GR16RegisterClass) {
12751 if (VT == MVT::i8) {
12752 unsigned DestReg = 0;
12753 switch (Res.first) {
12755 case X86::AX: DestReg = X86::AL; break;
12756 case X86::DX: DestReg = X86::DL; break;
12757 case X86::CX: DestReg = X86::CL; break;
12758 case X86::BX: DestReg = X86::BL; break;
12761 Res.first = DestReg;
12762 Res.second = X86::GR8RegisterClass;
12764 } else if (VT == MVT::i32) {
12765 unsigned DestReg = 0;
12766 switch (Res.first) {
12768 case X86::AX: DestReg = X86::EAX; break;
12769 case X86::DX: DestReg = X86::EDX; break;
12770 case X86::CX: DestReg = X86::ECX; break;
12771 case X86::BX: DestReg = X86::EBX; break;
12772 case X86::SI: DestReg = X86::ESI; break;
12773 case X86::DI: DestReg = X86::EDI; break;
12774 case X86::BP: DestReg = X86::EBP; break;
12775 case X86::SP: DestReg = X86::ESP; break;
12778 Res.first = DestReg;
12779 Res.second = X86::GR32RegisterClass;
12781 } else if (VT == MVT::i64) {
12782 unsigned DestReg = 0;
12783 switch (Res.first) {
12785 case X86::AX: DestReg = X86::RAX; break;
12786 case X86::DX: DestReg = X86::RDX; break;
12787 case X86::CX: DestReg = X86::RCX; break;
12788 case X86::BX: DestReg = X86::RBX; break;
12789 case X86::SI: DestReg = X86::RSI; break;
12790 case X86::DI: DestReg = X86::RDI; break;
12791 case X86::BP: DestReg = X86::RBP; break;
12792 case X86::SP: DestReg = X86::RSP; break;
12795 Res.first = DestReg;
12796 Res.second = X86::GR64RegisterClass;
12799 } else if (Res.second == X86::FR32RegisterClass ||
12800 Res.second == X86::FR64RegisterClass ||
12801 Res.second == X86::VR128RegisterClass) {
12802 // Handle references to XMM physical registers that got mapped into the
12803 // wrong class. This can happen with constraints like {xmm0} where the
12804 // target independent register mapper will just pick the first match it can
12805 // find, ignoring the required type.
12806 if (VT == MVT::f32)
12807 Res.second = X86::FR32RegisterClass;
12808 else if (VT == MVT::f64)
12809 Res.second = X86::FR64RegisterClass;
12810 else if (X86::VR128RegisterClass->hasType(VT))
12811 Res.second = X86::VR128RegisterClass;