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);
224 setSchedulingPreference(Sched::ILP);
225 setStackPointerRegisterToSaveRestore(X86StackPtr);
227 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
228 // Setup Windows compiler runtime calls.
229 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
230 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
231 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
232 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
233 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
234 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
235 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
236 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
239 if (Subtarget->isTargetDarwin()) {
240 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
241 setUseUnderscoreSetJmp(false);
242 setUseUnderscoreLongJmp(false);
243 } else if (Subtarget->isTargetMingw()) {
244 // MS runtime is weird: it exports _setjmp, but longjmp!
245 setUseUnderscoreSetJmp(true);
246 setUseUnderscoreLongJmp(false);
248 setUseUnderscoreSetJmp(true);
249 setUseUnderscoreLongJmp(true);
252 // Set up the register classes.
253 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
254 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
255 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
256 if (Subtarget->is64Bit())
257 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
259 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
261 // We don't accept any truncstore of integer registers.
262 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
263 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
264 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
265 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
266 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
267 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
269 // SETOEQ and SETUNE require checking two conditions.
270 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
271 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
272 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
273 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
274 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
275 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
277 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
279 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
280 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
281 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
283 if (Subtarget->is64Bit()) {
284 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
285 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
286 } else if (!UseSoftFloat) {
287 // We have an algorithm for SSE2->double, and we turn this into a
288 // 64-bit FILD followed by conditional FADD for other targets.
289 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
290 // We have an algorithm for SSE2, and we turn this into a 64-bit
291 // FILD for other targets.
292 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
295 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
297 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
298 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
301 // SSE has no i16 to fp conversion, only i32
302 if (X86ScalarSSEf32) {
303 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
304 // f32 and f64 cases are Legal, f80 case is not
305 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
307 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
308 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
311 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
312 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
315 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
316 // are Legal, f80 is custom lowered.
317 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
318 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
320 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
322 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
323 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
325 if (X86ScalarSSEf32) {
326 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
327 // f32 and f64 cases are Legal, f80 case is not
328 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
330 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
331 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
334 // Handle FP_TO_UINT by promoting the destination to a larger signed
336 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
337 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
338 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
340 if (Subtarget->is64Bit()) {
341 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
342 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
343 } else if (!UseSoftFloat) {
344 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
345 // Expand FP_TO_UINT into a select.
346 // FIXME: We would like to use a Custom expander here eventually to do
347 // the optimal thing for SSE vs. the default expansion in the legalizer.
348 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
350 // With SSE3 we can use fisttpll to convert to a signed i64; without
351 // SSE, we're stuck with a fistpll.
352 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
355 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
356 if (!X86ScalarSSEf64) {
357 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
358 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
359 if (Subtarget->is64Bit()) {
360 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
361 // Without SSE, i64->f64 goes through memory.
362 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
366 // Scalar integer divide and remainder are lowered to use operations that
367 // produce two results, to match the available instructions. This exposes
368 // the two-result form to trivial CSE, which is able to combine x/y and x%y
369 // into a single instruction.
371 // Scalar integer multiply-high is also lowered to use two-result
372 // operations, to match the available instructions. However, plain multiply
373 // (low) operations are left as Legal, as there are single-result
374 // instructions for this in x86. Using the two-result multiply instructions
375 // when both high and low results are needed must be arranged by dagcombine.
376 for (unsigned i = 0, e = 4; i != e; ++i) {
378 setOperationAction(ISD::MULHS, VT, Expand);
379 setOperationAction(ISD::MULHU, VT, Expand);
380 setOperationAction(ISD::SDIV, VT, Expand);
381 setOperationAction(ISD::UDIV, VT, Expand);
382 setOperationAction(ISD::SREM, VT, Expand);
383 setOperationAction(ISD::UREM, VT, Expand);
385 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
386 setOperationAction(ISD::ADDC, VT, Custom);
387 setOperationAction(ISD::ADDE, VT, Custom);
388 setOperationAction(ISD::SUBC, VT, Custom);
389 setOperationAction(ISD::SUBE, VT, Custom);
392 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
393 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
394 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
395 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
396 if (Subtarget->is64Bit())
397 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
398 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
399 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
400 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
401 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
402 setOperationAction(ISD::FREM , MVT::f32 , Expand);
403 setOperationAction(ISD::FREM , MVT::f64 , Expand);
404 setOperationAction(ISD::FREM , MVT::f80 , Expand);
405 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
407 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
408 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
409 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
410 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
411 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
412 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
413 if (Subtarget->is64Bit()) {
414 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
415 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
418 if (Subtarget->hasPOPCNT()) {
419 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
421 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
422 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
423 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
424 if (Subtarget->is64Bit())
425 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
428 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
429 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
431 // These should be promoted to a larger select which is supported.
432 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
433 // X86 wants to expand cmov itself.
434 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
435 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
436 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
437 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
438 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
439 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
440 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
441 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
442 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
443 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
444 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
445 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
446 if (Subtarget->is64Bit()) {
447 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
448 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
450 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
453 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
454 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
455 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
456 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
457 if (Subtarget->is64Bit())
458 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
459 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
460 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
461 if (Subtarget->is64Bit()) {
462 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
463 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
464 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
465 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
466 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
468 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
469 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
470 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
471 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
472 if (Subtarget->is64Bit()) {
473 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
474 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
475 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
478 if (Subtarget->hasXMM())
479 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
481 // We may not have a libcall for MEMBARRIER so we should lower this.
482 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
484 // On X86 and X86-64, atomic operations are lowered to locked instructions.
485 // Locked instructions, in turn, have implicit fence semantics (all memory
486 // operations are flushed before issuing the locked instruction, and they
487 // are not buffered), so we can fold away the common pattern of
488 // fence-atomic-fence.
489 setShouldFoldAtomicFences(true);
491 // Expand certain atomics
492 for (unsigned i = 0, e = 4; i != e; ++i) {
494 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
495 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
498 if (!Subtarget->is64Bit()) {
499 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
500 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
501 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
502 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
503 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
504 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
505 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
508 // FIXME - use subtarget debug flags
509 if (!Subtarget->isTargetDarwin() &&
510 !Subtarget->isTargetELF() &&
511 !Subtarget->isTargetCygMing()) {
512 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
515 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
516 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
517 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
518 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
519 if (Subtarget->is64Bit()) {
520 setExceptionPointerRegister(X86::RAX);
521 setExceptionSelectorRegister(X86::RDX);
523 setExceptionPointerRegister(X86::EAX);
524 setExceptionSelectorRegister(X86::EDX);
526 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
527 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
529 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
531 setOperationAction(ISD::TRAP, MVT::Other, Legal);
533 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
534 setOperationAction(ISD::VASTART , MVT::Other, Custom);
535 setOperationAction(ISD::VAEND , MVT::Other, Expand);
536 if (Subtarget->is64Bit()) {
537 setOperationAction(ISD::VAARG , MVT::Other, Custom);
538 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
540 setOperationAction(ISD::VAARG , MVT::Other, Expand);
541 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
544 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
545 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
546 if (Subtarget->is64Bit())
547 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
548 if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
549 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
551 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
553 if (!UseSoftFloat && X86ScalarSSEf64) {
554 // f32 and f64 use SSE.
555 // Set up the FP register classes.
556 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
557 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
559 // Use ANDPD to simulate FABS.
560 setOperationAction(ISD::FABS , MVT::f64, Custom);
561 setOperationAction(ISD::FABS , MVT::f32, Custom);
563 // Use XORP to simulate FNEG.
564 setOperationAction(ISD::FNEG , MVT::f64, Custom);
565 setOperationAction(ISD::FNEG , MVT::f32, Custom);
567 // Use ANDPD and ORPD to simulate FCOPYSIGN.
568 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
569 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
571 // We don't support sin/cos/fmod
572 setOperationAction(ISD::FSIN , MVT::f64, Expand);
573 setOperationAction(ISD::FCOS , MVT::f64, Expand);
574 setOperationAction(ISD::FSIN , MVT::f32, Expand);
575 setOperationAction(ISD::FCOS , MVT::f32, Expand);
577 // Expand FP immediates into loads from the stack, except for the special
579 addLegalFPImmediate(APFloat(+0.0)); // xorpd
580 addLegalFPImmediate(APFloat(+0.0f)); // xorps
581 } else if (!UseSoftFloat && X86ScalarSSEf32) {
582 // Use SSE for f32, x87 for f64.
583 // Set up the FP register classes.
584 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
585 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
587 // Use ANDPS to simulate FABS.
588 setOperationAction(ISD::FABS , MVT::f32, Custom);
590 // Use XORP to simulate FNEG.
591 setOperationAction(ISD::FNEG , MVT::f32, Custom);
593 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
595 // Use ANDPS and ORPS to simulate FCOPYSIGN.
596 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
597 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
599 // We don't support sin/cos/fmod
600 setOperationAction(ISD::FSIN , MVT::f32, Expand);
601 setOperationAction(ISD::FCOS , MVT::f32, Expand);
603 // Special cases we handle for FP constants.
604 addLegalFPImmediate(APFloat(+0.0f)); // xorps
605 addLegalFPImmediate(APFloat(+0.0)); // FLD0
606 addLegalFPImmediate(APFloat(+1.0)); // FLD1
607 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
608 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
611 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
612 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
614 } else if (!UseSoftFloat) {
615 // f32 and f64 in x87.
616 // Set up the FP register classes.
617 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
618 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
620 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
621 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
622 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
623 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
626 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
627 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
629 addLegalFPImmediate(APFloat(+0.0)); // FLD0
630 addLegalFPImmediate(APFloat(+1.0)); // FLD1
631 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
632 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
633 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
634 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
635 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
636 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
639 // Long double always uses X87.
641 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
642 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
643 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
645 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
646 addLegalFPImmediate(TmpFlt); // FLD0
648 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
651 APFloat TmpFlt2(+1.0);
652 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
654 addLegalFPImmediate(TmpFlt2); // FLD1
655 TmpFlt2.changeSign();
656 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
660 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
661 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
665 // Always use a library call for pow.
666 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
667 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
668 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
670 setOperationAction(ISD::FLOG, MVT::f80, Expand);
671 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
672 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
673 setOperationAction(ISD::FEXP, MVT::f80, Expand);
674 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
676 // First set operation action for all vector types to either promote
677 // (for widening) or expand (for scalarization). Then we will selectively
678 // turn on ones that can be effectively codegen'd.
679 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
680 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
681 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
682 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
683 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
684 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
685 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
686 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
687 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
688 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
689 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
690 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
691 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
692 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
693 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
694 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
695 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
696 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
698 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
699 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
700 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
701 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
702 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
703 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
704 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
705 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
731 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
735 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
736 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
737 setTruncStoreAction((MVT::SimpleValueType)VT,
738 (MVT::SimpleValueType)InnerVT, Expand);
739 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
740 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
741 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
744 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
745 // with -msoft-float, disable use of MMX as well.
746 if (!UseSoftFloat && Subtarget->hasMMX()) {
747 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
748 // No operations on x86mmx supported, everything uses intrinsics.
751 // MMX-sized vectors (other than x86mmx) are expected to be expanded
752 // into smaller operations.
753 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
754 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
755 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
756 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
757 setOperationAction(ISD::AND, MVT::v8i8, Expand);
758 setOperationAction(ISD::AND, MVT::v4i16, Expand);
759 setOperationAction(ISD::AND, MVT::v2i32, Expand);
760 setOperationAction(ISD::AND, MVT::v1i64, Expand);
761 setOperationAction(ISD::OR, MVT::v8i8, Expand);
762 setOperationAction(ISD::OR, MVT::v4i16, Expand);
763 setOperationAction(ISD::OR, MVT::v2i32, Expand);
764 setOperationAction(ISD::OR, MVT::v1i64, Expand);
765 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
766 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
767 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
768 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
769 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
770 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
771 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
772 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
773 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
774 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
775 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
776 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
777 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
778 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
779 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
780 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
781 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
783 if (!UseSoftFloat && Subtarget->hasXMM()) {
784 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
786 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
787 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
788 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
789 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
790 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
791 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
792 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
793 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
794 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
795 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
796 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
797 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
800 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
801 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
803 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
804 // registers cannot be used even for integer operations.
805 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
806 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
807 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
808 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
810 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
811 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
812 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
813 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
814 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
815 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
816 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
817 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
818 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
819 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
820 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
821 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
822 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
823 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
824 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
825 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
827 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
828 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
829 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
830 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
832 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
833 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
834 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
835 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
836 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
838 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
839 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
840 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
841 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
842 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
844 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
845 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
846 EVT VT = (MVT::SimpleValueType)i;
847 // Do not attempt to custom lower non-power-of-2 vectors
848 if (!isPowerOf2_32(VT.getVectorNumElements()))
850 // Do not attempt to custom lower non-128-bit vectors
851 if (!VT.is128BitVector())
853 setOperationAction(ISD::BUILD_VECTOR,
854 VT.getSimpleVT().SimpleTy, Custom);
855 setOperationAction(ISD::VECTOR_SHUFFLE,
856 VT.getSimpleVT().SimpleTy, Custom);
857 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
858 VT.getSimpleVT().SimpleTy, Custom);
861 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
862 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
863 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
864 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
865 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
866 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
868 if (Subtarget->is64Bit()) {
869 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
870 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
873 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
874 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
875 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
878 // Do not attempt to promote non-128-bit vectors
879 if (!VT.is128BitVector())
882 setOperationAction(ISD::AND, SVT, Promote);
883 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
884 setOperationAction(ISD::OR, SVT, Promote);
885 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
886 setOperationAction(ISD::XOR, SVT, Promote);
887 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
888 setOperationAction(ISD::LOAD, SVT, Promote);
889 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
890 setOperationAction(ISD::SELECT, SVT, Promote);
891 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
894 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
896 // Custom lower v2i64 and v2f64 selects.
897 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
898 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
899 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
900 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
902 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
903 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
906 if (Subtarget->hasSSE41()) {
907 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
908 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
909 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
910 setOperationAction(ISD::FRINT, MVT::f32, Legal);
911 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
912 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
913 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
914 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
915 setOperationAction(ISD::FRINT, MVT::f64, Legal);
916 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
918 // FIXME: Do we need to handle scalar-to-vector here?
919 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
921 // Can turn SHL into an integer multiply.
922 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
923 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
925 // i8 and i16 vectors are custom , because the source register and source
926 // source memory operand types are not the same width. f32 vectors are
927 // custom since the immediate controlling the insert encodes additional
929 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
930 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
931 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
932 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
934 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
935 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
936 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
937 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
939 if (Subtarget->is64Bit()) {
940 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
941 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
945 if (Subtarget->hasSSE42())
946 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
948 if (!UseSoftFloat && Subtarget->hasAVX()) {
949 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
950 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
951 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
952 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
953 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
955 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
956 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
957 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
958 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
960 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
961 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
962 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
963 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
964 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
965 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
967 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
968 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
969 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
970 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
971 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
972 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
974 // Custom lower build_vector, vector_shuffle, scalar_to_vector,
975 // insert_vector_elt extract_subvector and extract_vector_elt for
977 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
978 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
980 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
981 // Do not attempt to custom lower non-256-bit vectors
982 if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
983 || (MVT(VT).getSizeInBits() < 256))
985 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
986 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
987 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
988 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
989 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
991 // Custom-lower insert_subvector and extract_subvector based on
993 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
994 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
996 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
997 // Do not attempt to custom lower non-256-bit vectors
998 if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1001 if (MVT(VT).getSizeInBits() == 128) {
1002 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1004 else if (MVT(VT).getSizeInBits() == 256) {
1005 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1009 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1010 // Don't promote loads because we need them for VPERM vector index versions.
1012 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1013 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1015 if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1016 || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1018 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
1019 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v4i64);
1020 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
1021 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v4i64);
1022 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
1023 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v4i64);
1024 //setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
1025 //AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v4i64);
1026 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1027 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1031 // We want to custom lower some of our intrinsics.
1032 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1035 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1036 // handle type legalization for these operations here.
1038 // FIXME: We really should do custom legalization for addition and
1039 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1040 // than generic legalization for 64-bit multiplication-with-overflow, though.
1041 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1042 // Add/Sub/Mul with overflow operations are custom lowered.
1044 setOperationAction(ISD::SADDO, VT, Custom);
1045 setOperationAction(ISD::UADDO, VT, Custom);
1046 setOperationAction(ISD::SSUBO, VT, Custom);
1047 setOperationAction(ISD::USUBO, VT, Custom);
1048 setOperationAction(ISD::SMULO, VT, Custom);
1049 setOperationAction(ISD::UMULO, VT, Custom);
1052 // There are no 8-bit 3-address imul/mul instructions
1053 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1054 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1056 if (!Subtarget->is64Bit()) {
1057 // These libcalls are not available in 32-bit.
1058 setLibcallName(RTLIB::SHL_I128, 0);
1059 setLibcallName(RTLIB::SRL_I128, 0);
1060 setLibcallName(RTLIB::SRA_I128, 0);
1063 // We have target-specific dag combine patterns for the following nodes:
1064 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1065 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1066 setTargetDAGCombine(ISD::BUILD_VECTOR);
1067 setTargetDAGCombine(ISD::SELECT);
1068 setTargetDAGCombine(ISD::SHL);
1069 setTargetDAGCombine(ISD::SRA);
1070 setTargetDAGCombine(ISD::SRL);
1071 setTargetDAGCombine(ISD::OR);
1072 setTargetDAGCombine(ISD::AND);
1073 setTargetDAGCombine(ISD::ADD);
1074 setTargetDAGCombine(ISD::SUB);
1075 setTargetDAGCombine(ISD::STORE);
1076 setTargetDAGCombine(ISD::ZERO_EXTEND);
1077 if (Subtarget->is64Bit())
1078 setTargetDAGCombine(ISD::MUL);
1080 computeRegisterProperties();
1082 // On Darwin, -Os means optimize for size without hurting performance,
1083 // do not reduce the limit.
1084 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1085 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1086 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1087 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1088 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1089 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1090 setPrefLoopAlignment(16);
1091 benefitFromCodePlacementOpt = true;
1095 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1100 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1101 /// the desired ByVal argument alignment.
1102 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1105 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1106 if (VTy->getBitWidth() == 128)
1108 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1109 unsigned EltAlign = 0;
1110 getMaxByValAlign(ATy->getElementType(), EltAlign);
1111 if (EltAlign > MaxAlign)
1112 MaxAlign = EltAlign;
1113 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1114 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1115 unsigned EltAlign = 0;
1116 getMaxByValAlign(STy->getElementType(i), EltAlign);
1117 if (EltAlign > MaxAlign)
1118 MaxAlign = EltAlign;
1126 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1127 /// function arguments in the caller parameter area. For X86, aggregates
1128 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1129 /// are at 4-byte boundaries.
1130 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1131 if (Subtarget->is64Bit()) {
1132 // Max of 8 and alignment of type.
1133 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1140 if (Subtarget->hasXMM())
1141 getMaxByValAlign(Ty, Align);
1145 /// getOptimalMemOpType - Returns the target specific optimal type for load
1146 /// and store operations as a result of memset, memcpy, and memmove
1147 /// lowering. If DstAlign is zero that means it's safe to destination
1148 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1149 /// means there isn't a need to check it against alignment requirement,
1150 /// probably because the source does not need to be loaded. If
1151 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1152 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1153 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1154 /// constant so it does not need to be loaded.
1155 /// It returns EVT::Other if the type should be determined using generic
1156 /// target-independent logic.
1158 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1159 unsigned DstAlign, unsigned SrcAlign,
1160 bool NonScalarIntSafe,
1162 MachineFunction &MF) const {
1163 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1164 // linux. This is because the stack realignment code can't handle certain
1165 // cases like PR2962. This should be removed when PR2962 is fixed.
1166 const Function *F = MF.getFunction();
1167 if (NonScalarIntSafe &&
1168 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1170 (Subtarget->isUnalignedMemAccessFast() ||
1171 ((DstAlign == 0 || DstAlign >= 16) &&
1172 (SrcAlign == 0 || SrcAlign >= 16))) &&
1173 Subtarget->getStackAlignment() >= 16) {
1174 if (Subtarget->hasSSE2())
1176 if (Subtarget->hasSSE1())
1178 } else if (!MemcpyStrSrc && Size >= 8 &&
1179 !Subtarget->is64Bit() &&
1180 Subtarget->getStackAlignment() >= 8 &&
1181 Subtarget->hasXMMInt()) {
1182 // Do not use f64 to lower memcpy if source is string constant. It's
1183 // better to use i32 to avoid the loads.
1187 if (Subtarget->is64Bit() && Size >= 8)
1192 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1193 /// current function. The returned value is a member of the
1194 /// MachineJumpTableInfo::JTEntryKind enum.
1195 unsigned X86TargetLowering::getJumpTableEncoding() const {
1196 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1198 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1199 Subtarget->isPICStyleGOT())
1200 return MachineJumpTableInfo::EK_Custom32;
1202 // Otherwise, use the normal jump table encoding heuristics.
1203 return TargetLowering::getJumpTableEncoding();
1207 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1208 const MachineBasicBlock *MBB,
1209 unsigned uid,MCContext &Ctx) const{
1210 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1211 Subtarget->isPICStyleGOT());
1212 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1214 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1215 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1218 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1220 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1221 SelectionDAG &DAG) const {
1222 if (!Subtarget->is64Bit())
1223 // This doesn't have DebugLoc associated with it, but is not really the
1224 // same as a Register.
1225 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1229 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1230 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1232 const MCExpr *X86TargetLowering::
1233 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1234 MCContext &Ctx) const {
1235 // X86-64 uses RIP relative addressing based on the jump table label.
1236 if (Subtarget->isPICStyleRIPRel())
1237 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1239 // Otherwise, the reference is relative to the PIC base.
1240 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1243 /// getFunctionAlignment - Return the Log2 alignment of this function.
1244 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1245 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1248 // FIXME: Why this routine is here? Move to RegInfo!
1249 std::pair<const TargetRegisterClass*, uint8_t>
1250 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1251 const TargetRegisterClass *RRC = 0;
1253 switch (VT.getSimpleVT().SimpleTy) {
1255 return TargetLowering::findRepresentativeClass(VT);
1256 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1257 RRC = (Subtarget->is64Bit()
1258 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1261 RRC = X86::VR64RegisterClass;
1263 case MVT::f32: case MVT::f64:
1264 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1265 case MVT::v4f32: case MVT::v2f64:
1266 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1268 RRC = X86::VR128RegisterClass;
1271 return std::make_pair(RRC, Cost);
1274 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1275 unsigned &Offset) const {
1276 if (!Subtarget->isTargetLinux())
1279 if (Subtarget->is64Bit()) {
1280 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1282 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1295 //===----------------------------------------------------------------------===//
1296 // Return Value Calling Convention Implementation
1297 //===----------------------------------------------------------------------===//
1299 #include "X86GenCallingConv.inc"
1302 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1303 const SmallVectorImpl<ISD::OutputArg> &Outs,
1304 LLVMContext &Context) const {
1305 SmallVector<CCValAssign, 16> RVLocs;
1306 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1308 return CCInfo.CheckReturn(Outs, RetCC_X86);
1312 X86TargetLowering::LowerReturn(SDValue Chain,
1313 CallingConv::ID CallConv, bool isVarArg,
1314 const SmallVectorImpl<ISD::OutputArg> &Outs,
1315 const SmallVectorImpl<SDValue> &OutVals,
1316 DebugLoc dl, SelectionDAG &DAG) const {
1317 MachineFunction &MF = DAG.getMachineFunction();
1318 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1320 SmallVector<CCValAssign, 16> RVLocs;
1321 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1322 RVLocs, *DAG.getContext());
1323 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1325 // Add the regs to the liveout set for the function.
1326 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1327 for (unsigned i = 0; i != RVLocs.size(); ++i)
1328 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1329 MRI.addLiveOut(RVLocs[i].getLocReg());
1333 SmallVector<SDValue, 6> RetOps;
1334 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1335 // Operand #1 = Bytes To Pop
1336 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1339 // Copy the result values into the output registers.
1340 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1341 CCValAssign &VA = RVLocs[i];
1342 assert(VA.isRegLoc() && "Can only return in registers!");
1343 SDValue ValToCopy = OutVals[i];
1344 EVT ValVT = ValToCopy.getValueType();
1346 // If this is x86-64, and we disabled SSE, we can't return FP values,
1347 // or SSE or MMX vectors.
1348 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1349 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1350 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1351 report_fatal_error("SSE register return with SSE disabled");
1353 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1354 // llvm-gcc has never done it right and no one has noticed, so this
1355 // should be OK for now.
1356 if (ValVT == MVT::f64 &&
1357 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1358 report_fatal_error("SSE2 register return with SSE2 disabled");
1360 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1361 // the RET instruction and handled by the FP Stackifier.
1362 if (VA.getLocReg() == X86::ST0 ||
1363 VA.getLocReg() == X86::ST1) {
1364 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1365 // change the value to the FP stack register class.
1366 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1367 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1368 RetOps.push_back(ValToCopy);
1369 // Don't emit a copytoreg.
1373 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1374 // which is returned in RAX / RDX.
1375 if (Subtarget->is64Bit()) {
1376 if (ValVT == MVT::x86mmx) {
1377 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1378 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1379 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1381 // If we don't have SSE2 available, convert to v4f32 so the generated
1382 // register is legal.
1383 if (!Subtarget->hasSSE2())
1384 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1389 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1390 Flag = Chain.getValue(1);
1393 // The x86-64 ABI for returning structs by value requires that we copy
1394 // the sret argument into %rax for the return. We saved the argument into
1395 // a virtual register in the entry block, so now we copy the value out
1397 if (Subtarget->is64Bit() &&
1398 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1399 MachineFunction &MF = DAG.getMachineFunction();
1400 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1401 unsigned Reg = FuncInfo->getSRetReturnReg();
1403 "SRetReturnReg should have been set in LowerFormalArguments().");
1404 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1406 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1407 Flag = Chain.getValue(1);
1409 // RAX now acts like a return value.
1410 MRI.addLiveOut(X86::RAX);
1413 RetOps[0] = Chain; // Update chain.
1415 // Add the flag if we have it.
1417 RetOps.push_back(Flag);
1419 return DAG.getNode(X86ISD::RET_FLAG, dl,
1420 MVT::Other, &RetOps[0], RetOps.size());
1423 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1424 if (N->getNumValues() != 1)
1426 if (!N->hasNUsesOfValue(1, 0))
1429 SDNode *Copy = *N->use_begin();
1430 if (Copy->getOpcode() != ISD::CopyToReg &&
1431 Copy->getOpcode() != ISD::FP_EXTEND)
1434 bool HasRet = false;
1435 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1437 if (UI->getOpcode() != X86ISD::RET_FLAG)
1445 /// LowerCallResult - Lower the result values of a call into the
1446 /// appropriate copies out of appropriate physical registers.
1449 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1450 CallingConv::ID CallConv, bool isVarArg,
1451 const SmallVectorImpl<ISD::InputArg> &Ins,
1452 DebugLoc dl, SelectionDAG &DAG,
1453 SmallVectorImpl<SDValue> &InVals) const {
1455 // Assign locations to each value returned by this call.
1456 SmallVector<CCValAssign, 16> RVLocs;
1457 bool Is64Bit = Subtarget->is64Bit();
1458 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1459 RVLocs, *DAG.getContext());
1460 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1462 // Copy all of the result registers out of their specified physreg.
1463 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1464 CCValAssign &VA = RVLocs[i];
1465 EVT CopyVT = VA.getValVT();
1467 // If this is x86-64, and we disabled SSE, we can't return FP values
1468 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1469 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1470 report_fatal_error("SSE register return with SSE disabled");
1475 // If this is a call to a function that returns an fp value on the floating
1476 // point stack, we must guarantee the the value is popped from the stack, so
1477 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1478 // if the return value is not used. We use the FpGET_ST0 instructions
1480 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1481 // If we prefer to use the value in xmm registers, copy it out as f80 and
1482 // use a truncate to move it from fp stack reg to xmm reg.
1483 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1484 bool isST0 = VA.getLocReg() == X86::ST0;
1486 if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1487 if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1488 if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1489 SDValue Ops[] = { Chain, InFlag };
1490 Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1492 Val = Chain.getValue(0);
1494 // Round the f80 to the right size, which also moves it to the appropriate
1496 if (CopyVT != VA.getValVT())
1497 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1498 // This truncation won't change the value.
1499 DAG.getIntPtrConstant(1));
1500 } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1501 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1502 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1503 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1504 MVT::v2i64, InFlag).getValue(1);
1505 Val = Chain.getValue(0);
1506 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1507 Val, DAG.getConstant(0, MVT::i64));
1509 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1510 MVT::i64, InFlag).getValue(1);
1511 Val = Chain.getValue(0);
1513 Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1515 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1516 CopyVT, InFlag).getValue(1);
1517 Val = Chain.getValue(0);
1519 InFlag = Chain.getValue(2);
1520 InVals.push_back(Val);
1527 //===----------------------------------------------------------------------===//
1528 // C & StdCall & Fast Calling Convention implementation
1529 //===----------------------------------------------------------------------===//
1530 // StdCall calling convention seems to be standard for many Windows' API
1531 // routines and around. It differs from C calling convention just a little:
1532 // callee should clean up the stack, not caller. Symbols should be also
1533 // decorated in some fancy way :) It doesn't support any vector arguments.
1534 // For info on fast calling convention see Fast Calling Convention (tail call)
1535 // implementation LowerX86_32FastCCCallTo.
1537 /// CallIsStructReturn - Determines whether a call uses struct return
1539 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1543 return Outs[0].Flags.isSRet();
1546 /// ArgsAreStructReturn - Determines whether a function uses struct
1547 /// return semantics.
1549 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1553 return Ins[0].Flags.isSRet();
1556 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1557 /// by "Src" to address "Dst" with size and alignment information specified by
1558 /// the specific parameter attribute. The copy will be passed as a byval
1559 /// function parameter.
1561 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1562 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1564 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1566 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1567 /*isVolatile*/false, /*AlwaysInline=*/true,
1568 MachinePointerInfo(), MachinePointerInfo());
1571 /// IsTailCallConvention - Return true if the calling convention is one that
1572 /// supports tail call optimization.
1573 static bool IsTailCallConvention(CallingConv::ID CC) {
1574 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1577 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1578 /// a tailcall target by changing its ABI.
1579 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1580 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1584 X86TargetLowering::LowerMemArgument(SDValue Chain,
1585 CallingConv::ID CallConv,
1586 const SmallVectorImpl<ISD::InputArg> &Ins,
1587 DebugLoc dl, SelectionDAG &DAG,
1588 const CCValAssign &VA,
1589 MachineFrameInfo *MFI,
1591 // Create the nodes corresponding to a load from this parameter slot.
1592 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1593 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1594 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1597 // If value is passed by pointer we have address passed instead of the value
1599 if (VA.getLocInfo() == CCValAssign::Indirect)
1600 ValVT = VA.getLocVT();
1602 ValVT = VA.getValVT();
1604 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1605 // changed with more analysis.
1606 // In case of tail call optimization mark all arguments mutable. Since they
1607 // could be overwritten by lowering of arguments in case of a tail call.
1608 if (Flags.isByVal()) {
1609 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1610 VA.getLocMemOffset(), isImmutable);
1611 return DAG.getFrameIndex(FI, getPointerTy());
1613 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1614 VA.getLocMemOffset(), isImmutable);
1615 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1616 return DAG.getLoad(ValVT, dl, Chain, FIN,
1617 MachinePointerInfo::getFixedStack(FI),
1623 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1624 CallingConv::ID CallConv,
1626 const SmallVectorImpl<ISD::InputArg> &Ins,
1629 SmallVectorImpl<SDValue> &InVals)
1631 MachineFunction &MF = DAG.getMachineFunction();
1632 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1634 const Function* Fn = MF.getFunction();
1635 if (Fn->hasExternalLinkage() &&
1636 Subtarget->isTargetCygMing() &&
1637 Fn->getName() == "main")
1638 FuncInfo->setForceFramePointer(true);
1640 MachineFrameInfo *MFI = MF.getFrameInfo();
1641 bool Is64Bit = Subtarget->is64Bit();
1642 bool IsWin64 = Subtarget->isTargetWin64();
1644 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1645 "Var args not supported with calling convention fastcc or ghc");
1647 // Assign locations to all of the incoming arguments.
1648 SmallVector<CCValAssign, 16> ArgLocs;
1649 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1650 ArgLocs, *DAG.getContext());
1652 // Allocate shadow area for Win64
1654 CCInfo.AllocateStack(32, 8);
1657 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1659 unsigned LastVal = ~0U;
1661 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1662 CCValAssign &VA = ArgLocs[i];
1663 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1665 assert(VA.getValNo() != LastVal &&
1666 "Don't support value assigned to multiple locs yet");
1667 LastVal = VA.getValNo();
1669 if (VA.isRegLoc()) {
1670 EVT RegVT = VA.getLocVT();
1671 TargetRegisterClass *RC = NULL;
1672 if (RegVT == MVT::i32)
1673 RC = X86::GR32RegisterClass;
1674 else if (Is64Bit && RegVT == MVT::i64)
1675 RC = X86::GR64RegisterClass;
1676 else if (RegVT == MVT::f32)
1677 RC = X86::FR32RegisterClass;
1678 else if (RegVT == MVT::f64)
1679 RC = X86::FR64RegisterClass;
1680 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1681 RC = X86::VR256RegisterClass;
1682 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1683 RC = X86::VR128RegisterClass;
1684 else if (RegVT == MVT::x86mmx)
1685 RC = X86::VR64RegisterClass;
1687 llvm_unreachable("Unknown argument type!");
1689 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1690 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1692 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1693 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1695 if (VA.getLocInfo() == CCValAssign::SExt)
1696 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1697 DAG.getValueType(VA.getValVT()));
1698 else if (VA.getLocInfo() == CCValAssign::ZExt)
1699 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1700 DAG.getValueType(VA.getValVT()));
1701 else if (VA.getLocInfo() == CCValAssign::BCvt)
1702 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1704 if (VA.isExtInLoc()) {
1705 // Handle MMX values passed in XMM regs.
1706 if (RegVT.isVector()) {
1707 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1710 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1713 assert(VA.isMemLoc());
1714 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1717 // If value is passed via pointer - do a load.
1718 if (VA.getLocInfo() == CCValAssign::Indirect)
1719 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1720 MachinePointerInfo(), false, false, 0);
1722 InVals.push_back(ArgValue);
1725 // The x86-64 ABI for returning structs by value requires that we copy
1726 // the sret argument into %rax for the return. Save the argument into
1727 // a virtual register so that we can access it from the return points.
1728 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1729 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1730 unsigned Reg = FuncInfo->getSRetReturnReg();
1732 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1733 FuncInfo->setSRetReturnReg(Reg);
1735 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1736 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1739 unsigned StackSize = CCInfo.getNextStackOffset();
1740 // Align stack specially for tail calls.
1741 if (FuncIsMadeTailCallSafe(CallConv))
1742 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1744 // If the function takes variable number of arguments, make a frame index for
1745 // the start of the first vararg value... for expansion of llvm.va_start.
1747 if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1748 CallConv != CallingConv::X86_ThisCall))) {
1749 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1752 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1754 // FIXME: We should really autogenerate these arrays
1755 static const unsigned GPR64ArgRegsWin64[] = {
1756 X86::RCX, X86::RDX, X86::R8, X86::R9
1758 static const unsigned GPR64ArgRegs64Bit[] = {
1759 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1761 static const unsigned XMMArgRegs64Bit[] = {
1762 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1763 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1765 const unsigned *GPR64ArgRegs;
1766 unsigned NumXMMRegs = 0;
1769 // The XMM registers which might contain var arg parameters are shadowed
1770 // in their paired GPR. So we only need to save the GPR to their home
1772 TotalNumIntRegs = 4;
1773 GPR64ArgRegs = GPR64ArgRegsWin64;
1775 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1776 GPR64ArgRegs = GPR64ArgRegs64Bit;
1778 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1780 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1783 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1784 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1785 "SSE register cannot be used when SSE is disabled!");
1786 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1787 "SSE register cannot be used when SSE is disabled!");
1788 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1789 // Kernel mode asks for SSE to be disabled, so don't push them
1791 TotalNumXMMRegs = 0;
1794 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1795 // Get to the caller-allocated home save location. Add 8 to account
1796 // for the return address.
1797 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1798 FuncInfo->setRegSaveFrameIndex(
1799 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1800 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1802 // For X86-64, if there are vararg parameters that are passed via
1803 // registers, then we must store them to their spots on the stack so they
1804 // may be loaded by deferencing the result of va_next.
1805 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1806 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1807 FuncInfo->setRegSaveFrameIndex(
1808 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1812 // Store the integer parameter registers.
1813 SmallVector<SDValue, 8> MemOps;
1814 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1816 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1817 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1818 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1819 DAG.getIntPtrConstant(Offset));
1820 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1821 X86::GR64RegisterClass);
1822 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1824 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1825 MachinePointerInfo::getFixedStack(
1826 FuncInfo->getRegSaveFrameIndex(), Offset),
1828 MemOps.push_back(Store);
1832 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1833 // Now store the XMM (fp + vector) parameter registers.
1834 SmallVector<SDValue, 11> SaveXMMOps;
1835 SaveXMMOps.push_back(Chain);
1837 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1838 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1839 SaveXMMOps.push_back(ALVal);
1841 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1842 FuncInfo->getRegSaveFrameIndex()));
1843 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1844 FuncInfo->getVarArgsFPOffset()));
1846 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1847 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1848 X86::VR128RegisterClass);
1849 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1850 SaveXMMOps.push_back(Val);
1852 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1854 &SaveXMMOps[0], SaveXMMOps.size()));
1857 if (!MemOps.empty())
1858 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1859 &MemOps[0], MemOps.size());
1863 // Some CCs need callee pop.
1864 if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1865 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1867 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1868 // If this is an sret function, the return should pop the hidden pointer.
1869 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1870 FuncInfo->setBytesToPopOnReturn(4);
1874 // RegSaveFrameIndex is X86-64 only.
1875 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1876 if (CallConv == CallingConv::X86_FastCall ||
1877 CallConv == CallingConv::X86_ThisCall)
1878 // fastcc functions can't have varargs.
1879 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1886 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1887 SDValue StackPtr, SDValue Arg,
1888 DebugLoc dl, SelectionDAG &DAG,
1889 const CCValAssign &VA,
1890 ISD::ArgFlagsTy Flags) const {
1891 unsigned LocMemOffset = VA.getLocMemOffset();
1892 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1893 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1894 if (Flags.isByVal())
1895 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1897 return DAG.getStore(Chain, dl, Arg, PtrOff,
1898 MachinePointerInfo::getStack(LocMemOffset),
1902 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1903 /// optimization is performed and it is required.
1905 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1906 SDValue &OutRetAddr, SDValue Chain,
1907 bool IsTailCall, bool Is64Bit,
1908 int FPDiff, DebugLoc dl) const {
1909 // Adjust the Return address stack slot.
1910 EVT VT = getPointerTy();
1911 OutRetAddr = getReturnAddressFrameIndex(DAG);
1913 // Load the "old" Return address.
1914 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1916 return SDValue(OutRetAddr.getNode(), 1);
1919 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1920 /// optimization is performed and it is required (FPDiff!=0).
1922 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1923 SDValue Chain, SDValue RetAddrFrIdx,
1924 bool Is64Bit, int FPDiff, DebugLoc dl) {
1925 // Store the return address to the appropriate stack slot.
1926 if (!FPDiff) return Chain;
1927 // Calculate the new stack slot for the return address.
1928 int SlotSize = Is64Bit ? 8 : 4;
1929 int NewReturnAddrFI =
1930 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1931 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1932 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1933 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1934 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1940 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1941 CallingConv::ID CallConv, bool isVarArg,
1943 const SmallVectorImpl<ISD::OutputArg> &Outs,
1944 const SmallVectorImpl<SDValue> &OutVals,
1945 const SmallVectorImpl<ISD::InputArg> &Ins,
1946 DebugLoc dl, SelectionDAG &DAG,
1947 SmallVectorImpl<SDValue> &InVals) const {
1948 MachineFunction &MF = DAG.getMachineFunction();
1949 bool Is64Bit = Subtarget->is64Bit();
1950 bool IsWin64 = Subtarget->isTargetWin64();
1951 bool IsStructRet = CallIsStructReturn(Outs);
1952 bool IsSibcall = false;
1955 // Check if it's really possible to do a tail call.
1956 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1957 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1958 Outs, OutVals, Ins, DAG);
1960 // Sibcalls are automatically detected tailcalls which do not require
1962 if (!GuaranteedTailCallOpt && isTailCall)
1969 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1970 "Var args not supported with calling convention fastcc or ghc");
1972 // Analyze operands of the call, assigning locations to each operand.
1973 SmallVector<CCValAssign, 16> ArgLocs;
1974 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1975 ArgLocs, *DAG.getContext());
1977 // Allocate shadow area for Win64
1979 CCInfo.AllocateStack(32, 8);
1982 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
1984 // Get a count of how many bytes are to be pushed on the stack.
1985 unsigned NumBytes = CCInfo.getNextStackOffset();
1987 // This is a sibcall. The memory operands are available in caller's
1988 // own caller's stack.
1990 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1991 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1994 if (isTailCall && !IsSibcall) {
1995 // Lower arguments at fp - stackoffset + fpdiff.
1996 unsigned NumBytesCallerPushed =
1997 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1998 FPDiff = NumBytesCallerPushed - NumBytes;
2000 // Set the delta of movement of the returnaddr stackslot.
2001 // But only set if delta is greater than previous delta.
2002 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2003 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2007 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2009 SDValue RetAddrFrIdx;
2010 // Load return adress for tail calls.
2011 if (isTailCall && FPDiff)
2012 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2013 Is64Bit, FPDiff, dl);
2015 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2016 SmallVector<SDValue, 8> MemOpChains;
2019 // Walk the register/memloc assignments, inserting copies/loads. In the case
2020 // of tail call optimization arguments are handle later.
2021 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2022 CCValAssign &VA = ArgLocs[i];
2023 EVT RegVT = VA.getLocVT();
2024 SDValue Arg = OutVals[i];
2025 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2026 bool isByVal = Flags.isByVal();
2028 // Promote the value if needed.
2029 switch (VA.getLocInfo()) {
2030 default: llvm_unreachable("Unknown loc info!");
2031 case CCValAssign::Full: break;
2032 case CCValAssign::SExt:
2033 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2035 case CCValAssign::ZExt:
2036 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2038 case CCValAssign::AExt:
2039 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2040 // Special case: passing MMX values in XMM registers.
2041 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2042 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2043 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2045 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2047 case CCValAssign::BCvt:
2048 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2050 case CCValAssign::Indirect: {
2051 // Store the argument.
2052 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2053 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2054 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2055 MachinePointerInfo::getFixedStack(FI),
2062 if (VA.isRegLoc()) {
2063 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2064 if (isVarArg && IsWin64) {
2065 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2066 // shadow reg if callee is a varargs function.
2067 unsigned ShadowReg = 0;
2068 switch (VA.getLocReg()) {
2069 case X86::XMM0: ShadowReg = X86::RCX; break;
2070 case X86::XMM1: ShadowReg = X86::RDX; break;
2071 case X86::XMM2: ShadowReg = X86::R8; break;
2072 case X86::XMM3: ShadowReg = X86::R9; break;
2075 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2077 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2078 assert(VA.isMemLoc());
2079 if (StackPtr.getNode() == 0)
2080 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2081 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2082 dl, DAG, VA, Flags));
2086 if (!MemOpChains.empty())
2087 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2088 &MemOpChains[0], MemOpChains.size());
2090 // Build a sequence of copy-to-reg nodes chained together with token chain
2091 // and flag operands which copy the outgoing args into registers.
2093 // Tail call byval lowering might overwrite argument registers so in case of
2094 // tail call optimization the copies to registers are lowered later.
2096 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2097 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2098 RegsToPass[i].second, InFlag);
2099 InFlag = Chain.getValue(1);
2102 if (Subtarget->isPICStyleGOT()) {
2103 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2106 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2107 DAG.getNode(X86ISD::GlobalBaseReg,
2108 DebugLoc(), getPointerTy()),
2110 InFlag = Chain.getValue(1);
2112 // If we are tail calling and generating PIC/GOT style code load the
2113 // address of the callee into ECX. The value in ecx is used as target of
2114 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2115 // for tail calls on PIC/GOT architectures. Normally we would just put the
2116 // address of GOT into ebx and then call target@PLT. But for tail calls
2117 // ebx would be restored (since ebx is callee saved) before jumping to the
2120 // Note: The actual moving to ECX is done further down.
2121 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2122 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2123 !G->getGlobal()->hasProtectedVisibility())
2124 Callee = LowerGlobalAddress(Callee, DAG);
2125 else if (isa<ExternalSymbolSDNode>(Callee))
2126 Callee = LowerExternalSymbol(Callee, DAG);
2130 if (Is64Bit && isVarArg && !IsWin64) {
2131 // From AMD64 ABI document:
2132 // For calls that may call functions that use varargs or stdargs
2133 // (prototype-less calls or calls to functions containing ellipsis (...) in
2134 // the declaration) %al is used as hidden argument to specify the number
2135 // of SSE registers used. The contents of %al do not need to match exactly
2136 // the number of registers, but must be an ubound on the number of SSE
2137 // registers used and is in the range 0 - 8 inclusive.
2139 // Count the number of XMM registers allocated.
2140 static const unsigned XMMArgRegs[] = {
2141 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2142 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2144 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2145 assert((Subtarget->hasXMM() || !NumXMMRegs)
2146 && "SSE registers cannot be used when SSE is disabled");
2148 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2149 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2150 InFlag = Chain.getValue(1);
2154 // For tail calls lower the arguments to the 'real' stack slot.
2156 // Force all the incoming stack arguments to be loaded from the stack
2157 // before any new outgoing arguments are stored to the stack, because the
2158 // outgoing stack slots may alias the incoming argument stack slots, and
2159 // the alias isn't otherwise explicit. This is slightly more conservative
2160 // than necessary, because it means that each store effectively depends
2161 // on every argument instead of just those arguments it would clobber.
2162 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2164 SmallVector<SDValue, 8> MemOpChains2;
2167 // Do not flag preceeding copytoreg stuff together with the following stuff.
2169 if (GuaranteedTailCallOpt) {
2170 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2171 CCValAssign &VA = ArgLocs[i];
2174 assert(VA.isMemLoc());
2175 SDValue Arg = OutVals[i];
2176 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2177 // Create frame index.
2178 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2179 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2180 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2181 FIN = DAG.getFrameIndex(FI, getPointerTy());
2183 if (Flags.isByVal()) {
2184 // Copy relative to framepointer.
2185 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2186 if (StackPtr.getNode() == 0)
2187 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2189 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2191 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2195 // Store relative to framepointer.
2196 MemOpChains2.push_back(
2197 DAG.getStore(ArgChain, dl, Arg, FIN,
2198 MachinePointerInfo::getFixedStack(FI),
2204 if (!MemOpChains2.empty())
2205 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2206 &MemOpChains2[0], MemOpChains2.size());
2208 // Copy arguments to their registers.
2209 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2210 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2211 RegsToPass[i].second, InFlag);
2212 InFlag = Chain.getValue(1);
2216 // Store the return address to the appropriate stack slot.
2217 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2221 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2222 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2223 // In the 64-bit large code model, we have to make all calls
2224 // through a register, since the call instruction's 32-bit
2225 // pc-relative offset may not be large enough to hold the whole
2227 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2228 // If the callee is a GlobalAddress node (quite common, every direct call
2229 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2232 // We should use extra load for direct calls to dllimported functions in
2234 const GlobalValue *GV = G->getGlobal();
2235 if (!GV->hasDLLImportLinkage()) {
2236 unsigned char OpFlags = 0;
2238 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2239 // external symbols most go through the PLT in PIC mode. If the symbol
2240 // has hidden or protected visibility, or if it is static or local, then
2241 // we don't need to use the PLT - we can directly call it.
2242 if (Subtarget->isTargetELF() &&
2243 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2244 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2245 OpFlags = X86II::MO_PLT;
2246 } else if (Subtarget->isPICStyleStubAny() &&
2247 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2248 Subtarget->getDarwinVers() < 9) {
2249 // PC-relative references to external symbols should go through $stub,
2250 // unless we're building with the leopard linker or later, which
2251 // automatically synthesizes these stubs.
2252 OpFlags = X86II::MO_DARWIN_STUB;
2255 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2256 G->getOffset(), OpFlags);
2258 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2259 unsigned char OpFlags = 0;
2261 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2262 // external symbols should go through the PLT.
2263 if (Subtarget->isTargetELF() &&
2264 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2265 OpFlags = X86II::MO_PLT;
2266 } else if (Subtarget->isPICStyleStubAny() &&
2267 Subtarget->getDarwinVers() < 9) {
2268 // PC-relative references to external symbols should go through $stub,
2269 // unless we're building with the leopard linker or later, which
2270 // automatically synthesizes these stubs.
2271 OpFlags = X86II::MO_DARWIN_STUB;
2274 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2278 // Returns a chain & a flag for retval copy to use.
2279 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2280 SmallVector<SDValue, 8> Ops;
2282 if (!IsSibcall && isTailCall) {
2283 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2284 DAG.getIntPtrConstant(0, true), InFlag);
2285 InFlag = Chain.getValue(1);
2288 Ops.push_back(Chain);
2289 Ops.push_back(Callee);
2292 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2294 // Add argument registers to the end of the list so that they are known live
2296 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2297 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2298 RegsToPass[i].second.getValueType()));
2300 // Add an implicit use GOT pointer in EBX.
2301 if (!isTailCall && Subtarget->isPICStyleGOT())
2302 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2304 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2305 if (Is64Bit && isVarArg && !IsWin64)
2306 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2308 if (InFlag.getNode())
2309 Ops.push_back(InFlag);
2313 //// If this is the first return lowered for this function, add the regs
2314 //// to the liveout set for the function.
2315 // This isn't right, although it's probably harmless on x86; liveouts
2316 // should be computed from returns not tail calls. Consider a void
2317 // function making a tail call to a function returning int.
2318 return DAG.getNode(X86ISD::TC_RETURN, dl,
2319 NodeTys, &Ops[0], Ops.size());
2322 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2323 InFlag = Chain.getValue(1);
2325 // Create the CALLSEQ_END node.
2326 unsigned NumBytesForCalleeToPush;
2327 if (Subtarget->IsCalleePop(isVarArg, CallConv))
2328 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2329 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2330 // If this is a call to a struct-return function, the callee
2331 // pops the hidden struct pointer, so we have to push it back.
2332 // This is common for Darwin/X86, Linux & Mingw32 targets.
2333 NumBytesForCalleeToPush = 4;
2335 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2337 // Returns a flag for retval copy to use.
2339 Chain = DAG.getCALLSEQ_END(Chain,
2340 DAG.getIntPtrConstant(NumBytes, true),
2341 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2344 InFlag = Chain.getValue(1);
2347 // Handle result values, copying them out of physregs into vregs that we
2349 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2350 Ins, dl, DAG, InVals);
2354 //===----------------------------------------------------------------------===//
2355 // Fast Calling Convention (tail call) implementation
2356 //===----------------------------------------------------------------------===//
2358 // Like std call, callee cleans arguments, convention except that ECX is
2359 // reserved for storing the tail called function address. Only 2 registers are
2360 // free for argument passing (inreg). Tail call optimization is performed
2362 // * tailcallopt is enabled
2363 // * caller/callee are fastcc
2364 // On X86_64 architecture with GOT-style position independent code only local
2365 // (within module) calls are supported at the moment.
2366 // To keep the stack aligned according to platform abi the function
2367 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2368 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2369 // If a tail called function callee has more arguments than the caller the
2370 // caller needs to make sure that there is room to move the RETADDR to. This is
2371 // achieved by reserving an area the size of the argument delta right after the
2372 // original REtADDR, but before the saved framepointer or the spilled registers
2373 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2385 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2386 /// for a 16 byte align requirement.
2388 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2389 SelectionDAG& DAG) const {
2390 MachineFunction &MF = DAG.getMachineFunction();
2391 const TargetMachine &TM = MF.getTarget();
2392 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2393 unsigned StackAlignment = TFI.getStackAlignment();
2394 uint64_t AlignMask = StackAlignment - 1;
2395 int64_t Offset = StackSize;
2396 uint64_t SlotSize = TD->getPointerSize();
2397 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2398 // Number smaller than 12 so just add the difference.
2399 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2401 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2402 Offset = ((~AlignMask) & Offset) + StackAlignment +
2403 (StackAlignment-SlotSize);
2408 /// MatchingStackOffset - Return true if the given stack call argument is
2409 /// already available in the same position (relatively) of the caller's
2410 /// incoming argument stack.
2412 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2413 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2414 const X86InstrInfo *TII) {
2415 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2417 if (Arg.getOpcode() == ISD::CopyFromReg) {
2418 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2419 if (!TargetRegisterInfo::isVirtualRegister(VR))
2421 MachineInstr *Def = MRI->getVRegDef(VR);
2424 if (!Flags.isByVal()) {
2425 if (!TII->isLoadFromStackSlot(Def, FI))
2428 unsigned Opcode = Def->getOpcode();
2429 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2430 Def->getOperand(1).isFI()) {
2431 FI = Def->getOperand(1).getIndex();
2432 Bytes = Flags.getByValSize();
2436 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2437 if (Flags.isByVal())
2438 // ByVal argument is passed in as a pointer but it's now being
2439 // dereferenced. e.g.
2440 // define @foo(%struct.X* %A) {
2441 // tail call @bar(%struct.X* byval %A)
2444 SDValue Ptr = Ld->getBasePtr();
2445 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2448 FI = FINode->getIndex();
2452 assert(FI != INT_MAX);
2453 if (!MFI->isFixedObjectIndex(FI))
2455 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2458 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2459 /// for tail call optimization. Targets which want to do tail call
2460 /// optimization should implement this function.
2462 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2463 CallingConv::ID CalleeCC,
2465 bool isCalleeStructRet,
2466 bool isCallerStructRet,
2467 const SmallVectorImpl<ISD::OutputArg> &Outs,
2468 const SmallVectorImpl<SDValue> &OutVals,
2469 const SmallVectorImpl<ISD::InputArg> &Ins,
2470 SelectionDAG& DAG) const {
2471 if (!IsTailCallConvention(CalleeCC) &&
2472 CalleeCC != CallingConv::C)
2475 // If -tailcallopt is specified, make fastcc functions tail-callable.
2476 const MachineFunction &MF = DAG.getMachineFunction();
2477 const Function *CallerF = DAG.getMachineFunction().getFunction();
2478 CallingConv::ID CallerCC = CallerF->getCallingConv();
2479 bool CCMatch = CallerCC == CalleeCC;
2481 if (GuaranteedTailCallOpt) {
2482 if (IsTailCallConvention(CalleeCC) && CCMatch)
2487 // Look for obvious safe cases to perform tail call optimization that do not
2488 // require ABI changes. This is what gcc calls sibcall.
2490 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2491 // emit a special epilogue.
2492 if (RegInfo->needsStackRealignment(MF))
2495 // Do not sibcall optimize vararg calls unless the call site is not passing
2497 if (isVarArg && !Outs.empty())
2500 // Also avoid sibcall optimization if either caller or callee uses struct
2501 // return semantics.
2502 if (isCalleeStructRet || isCallerStructRet)
2505 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2506 // Therefore if it's not used by the call it is not safe to optimize this into
2508 bool Unused = false;
2509 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2516 SmallVector<CCValAssign, 16> RVLocs;
2517 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2518 RVLocs, *DAG.getContext());
2519 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2520 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2521 CCValAssign &VA = RVLocs[i];
2522 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2527 // If the calling conventions do not match, then we'd better make sure the
2528 // results are returned in the same way as what the caller expects.
2530 SmallVector<CCValAssign, 16> RVLocs1;
2531 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2532 RVLocs1, *DAG.getContext());
2533 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2535 SmallVector<CCValAssign, 16> RVLocs2;
2536 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2537 RVLocs2, *DAG.getContext());
2538 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2540 if (RVLocs1.size() != RVLocs2.size())
2542 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2543 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2545 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2547 if (RVLocs1[i].isRegLoc()) {
2548 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2551 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2557 // If the callee takes no arguments then go on to check the results of the
2559 if (!Outs.empty()) {
2560 // Check if stack adjustment is needed. For now, do not do this if any
2561 // argument is passed on the stack.
2562 SmallVector<CCValAssign, 16> ArgLocs;
2563 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2564 ArgLocs, *DAG.getContext());
2566 // Allocate shadow area for Win64
2567 if (Subtarget->isTargetWin64()) {
2568 CCInfo.AllocateStack(32, 8);
2571 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2572 if (CCInfo.getNextStackOffset()) {
2573 MachineFunction &MF = DAG.getMachineFunction();
2574 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2577 // Check if the arguments are already laid out in the right way as
2578 // the caller's fixed stack objects.
2579 MachineFrameInfo *MFI = MF.getFrameInfo();
2580 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2581 const X86InstrInfo *TII =
2582 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2583 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2584 CCValAssign &VA = ArgLocs[i];
2585 SDValue Arg = OutVals[i];
2586 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2587 if (VA.getLocInfo() == CCValAssign::Indirect)
2589 if (!VA.isRegLoc()) {
2590 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2597 // If the tailcall address may be in a register, then make sure it's
2598 // possible to register allocate for it. In 32-bit, the call address can
2599 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2600 // callee-saved registers are restored. These happen to be the same
2601 // registers used to pass 'inreg' arguments so watch out for those.
2602 if (!Subtarget->is64Bit() &&
2603 !isa<GlobalAddressSDNode>(Callee) &&
2604 !isa<ExternalSymbolSDNode>(Callee)) {
2605 unsigned NumInRegs = 0;
2606 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2607 CCValAssign &VA = ArgLocs[i];
2610 unsigned Reg = VA.getLocReg();
2613 case X86::EAX: case X86::EDX: case X86::ECX:
2614 if (++NumInRegs == 3)
2622 // An stdcall caller is expected to clean up its arguments; the callee
2623 // isn't going to do that.
2624 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2631 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2632 return X86::createFastISel(funcInfo);
2636 //===----------------------------------------------------------------------===//
2637 // Other Lowering Hooks
2638 //===----------------------------------------------------------------------===//
2640 static bool MayFoldLoad(SDValue Op) {
2641 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2644 static bool MayFoldIntoStore(SDValue Op) {
2645 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2648 static bool isTargetShuffle(unsigned Opcode) {
2650 default: return false;
2651 case X86ISD::PSHUFD:
2652 case X86ISD::PSHUFHW:
2653 case X86ISD::PSHUFLW:
2654 case X86ISD::SHUFPD:
2655 case X86ISD::PALIGN:
2656 case X86ISD::SHUFPS:
2657 case X86ISD::MOVLHPS:
2658 case X86ISD::MOVLHPD:
2659 case X86ISD::MOVHLPS:
2660 case X86ISD::MOVLPS:
2661 case X86ISD::MOVLPD:
2662 case X86ISD::MOVSHDUP:
2663 case X86ISD::MOVSLDUP:
2664 case X86ISD::MOVDDUP:
2667 case X86ISD::UNPCKLPS:
2668 case X86ISD::UNPCKLPD:
2669 case X86ISD::VUNPCKLPS:
2670 case X86ISD::VUNPCKLPD:
2671 case X86ISD::VUNPCKLPSY:
2672 case X86ISD::VUNPCKLPDY:
2673 case X86ISD::PUNPCKLWD:
2674 case X86ISD::PUNPCKLBW:
2675 case X86ISD::PUNPCKLDQ:
2676 case X86ISD::PUNPCKLQDQ:
2677 case X86ISD::UNPCKHPS:
2678 case X86ISD::UNPCKHPD:
2679 case X86ISD::PUNPCKHWD:
2680 case X86ISD::PUNPCKHBW:
2681 case X86ISD::PUNPCKHDQ:
2682 case X86ISD::PUNPCKHQDQ:
2688 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2689 SDValue V1, SelectionDAG &DAG) {
2691 default: llvm_unreachable("Unknown x86 shuffle node");
2692 case X86ISD::MOVSHDUP:
2693 case X86ISD::MOVSLDUP:
2694 case X86ISD::MOVDDUP:
2695 return DAG.getNode(Opc, dl, VT, V1);
2701 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2702 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2704 default: llvm_unreachable("Unknown x86 shuffle node");
2705 case X86ISD::PSHUFD:
2706 case X86ISD::PSHUFHW:
2707 case X86ISD::PSHUFLW:
2708 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2714 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2715 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2717 default: llvm_unreachable("Unknown x86 shuffle node");
2718 case X86ISD::PALIGN:
2719 case X86ISD::SHUFPD:
2720 case X86ISD::SHUFPS:
2721 return DAG.getNode(Opc, dl, VT, V1, V2,
2722 DAG.getConstant(TargetMask, MVT::i8));
2727 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2728 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2730 default: llvm_unreachable("Unknown x86 shuffle node");
2731 case X86ISD::MOVLHPS:
2732 case X86ISD::MOVLHPD:
2733 case X86ISD::MOVHLPS:
2734 case X86ISD::MOVLPS:
2735 case X86ISD::MOVLPD:
2738 case X86ISD::UNPCKLPS:
2739 case X86ISD::UNPCKLPD:
2740 case X86ISD::VUNPCKLPS:
2741 case X86ISD::VUNPCKLPD:
2742 case X86ISD::VUNPCKLPSY:
2743 case X86ISD::VUNPCKLPDY:
2744 case X86ISD::PUNPCKLWD:
2745 case X86ISD::PUNPCKLBW:
2746 case X86ISD::PUNPCKLDQ:
2747 case X86ISD::PUNPCKLQDQ:
2748 case X86ISD::UNPCKHPS:
2749 case X86ISD::UNPCKHPD:
2750 case X86ISD::PUNPCKHWD:
2751 case X86ISD::PUNPCKHBW:
2752 case X86ISD::PUNPCKHDQ:
2753 case X86ISD::PUNPCKHQDQ:
2754 return DAG.getNode(Opc, dl, VT, V1, V2);
2759 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2760 MachineFunction &MF = DAG.getMachineFunction();
2761 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2762 int ReturnAddrIndex = FuncInfo->getRAIndex();
2764 if (ReturnAddrIndex == 0) {
2765 // Set up a frame object for the return address.
2766 uint64_t SlotSize = TD->getPointerSize();
2767 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2769 FuncInfo->setRAIndex(ReturnAddrIndex);
2772 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2776 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2777 bool hasSymbolicDisplacement) {
2778 // Offset should fit into 32 bit immediate field.
2779 if (!isInt<32>(Offset))
2782 // If we don't have a symbolic displacement - we don't have any extra
2784 if (!hasSymbolicDisplacement)
2787 // FIXME: Some tweaks might be needed for medium code model.
2788 if (M != CodeModel::Small && M != CodeModel::Kernel)
2791 // For small code model we assume that latest object is 16MB before end of 31
2792 // bits boundary. We may also accept pretty large negative constants knowing
2793 // that all objects are in the positive half of address space.
2794 if (M == CodeModel::Small && Offset < 16*1024*1024)
2797 // For kernel code model we know that all object resist in the negative half
2798 // of 32bits address space. We may not accept negative offsets, since they may
2799 // be just off and we may accept pretty large positive ones.
2800 if (M == CodeModel::Kernel && Offset > 0)
2806 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2807 /// specific condition code, returning the condition code and the LHS/RHS of the
2808 /// comparison to make.
2809 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2810 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2812 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2813 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2814 // X > -1 -> X == 0, jump !sign.
2815 RHS = DAG.getConstant(0, RHS.getValueType());
2816 return X86::COND_NS;
2817 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2818 // X < 0 -> X == 0, jump on sign.
2820 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2822 RHS = DAG.getConstant(0, RHS.getValueType());
2823 return X86::COND_LE;
2827 switch (SetCCOpcode) {
2828 default: llvm_unreachable("Invalid integer condition!");
2829 case ISD::SETEQ: return X86::COND_E;
2830 case ISD::SETGT: return X86::COND_G;
2831 case ISD::SETGE: return X86::COND_GE;
2832 case ISD::SETLT: return X86::COND_L;
2833 case ISD::SETLE: return X86::COND_LE;
2834 case ISD::SETNE: return X86::COND_NE;
2835 case ISD::SETULT: return X86::COND_B;
2836 case ISD::SETUGT: return X86::COND_A;
2837 case ISD::SETULE: return X86::COND_BE;
2838 case ISD::SETUGE: return X86::COND_AE;
2842 // First determine if it is required or is profitable to flip the operands.
2844 // If LHS is a foldable load, but RHS is not, flip the condition.
2845 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2846 !ISD::isNON_EXTLoad(RHS.getNode())) {
2847 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2848 std::swap(LHS, RHS);
2851 switch (SetCCOpcode) {
2857 std::swap(LHS, RHS);
2861 // On a floating point condition, the flags are set as follows:
2863 // 0 | 0 | 0 | X > Y
2864 // 0 | 0 | 1 | X < Y
2865 // 1 | 0 | 0 | X == Y
2866 // 1 | 1 | 1 | unordered
2867 switch (SetCCOpcode) {
2868 default: llvm_unreachable("Condcode should be pre-legalized away");
2870 case ISD::SETEQ: return X86::COND_E;
2871 case ISD::SETOLT: // flipped
2873 case ISD::SETGT: return X86::COND_A;
2874 case ISD::SETOLE: // flipped
2876 case ISD::SETGE: return X86::COND_AE;
2877 case ISD::SETUGT: // flipped
2879 case ISD::SETLT: return X86::COND_B;
2880 case ISD::SETUGE: // flipped
2882 case ISD::SETLE: return X86::COND_BE;
2884 case ISD::SETNE: return X86::COND_NE;
2885 case ISD::SETUO: return X86::COND_P;
2886 case ISD::SETO: return X86::COND_NP;
2888 case ISD::SETUNE: return X86::COND_INVALID;
2892 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2893 /// code. Current x86 isa includes the following FP cmov instructions:
2894 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2895 static bool hasFPCMov(unsigned X86CC) {
2911 /// isFPImmLegal - Returns true if the target can instruction select the
2912 /// specified FP immediate natively. If false, the legalizer will
2913 /// materialize the FP immediate as a load from a constant pool.
2914 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2915 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2916 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2922 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2923 /// the specified range (L, H].
2924 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2925 return (Val < 0) || (Val >= Low && Val < Hi);
2928 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2929 /// specified value.
2930 static bool isUndefOrEqual(int Val, int CmpVal) {
2931 if (Val < 0 || Val == CmpVal)
2936 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2937 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2938 /// the second operand.
2939 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2940 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2941 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2942 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2943 return (Mask[0] < 2 && Mask[1] < 2);
2947 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2948 SmallVector<int, 8> M;
2950 return ::isPSHUFDMask(M, N->getValueType(0));
2953 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2954 /// is suitable for input to PSHUFHW.
2955 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2956 if (VT != MVT::v8i16)
2959 // Lower quadword copied in order or undef.
2960 for (int i = 0; i != 4; ++i)
2961 if (Mask[i] >= 0 && Mask[i] != i)
2964 // Upper quadword shuffled.
2965 for (int i = 4; i != 8; ++i)
2966 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2972 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2973 SmallVector<int, 8> M;
2975 return ::isPSHUFHWMask(M, N->getValueType(0));
2978 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2979 /// is suitable for input to PSHUFLW.
2980 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2981 if (VT != MVT::v8i16)
2984 // Upper quadword copied in order.
2985 for (int i = 4; i != 8; ++i)
2986 if (Mask[i] >= 0 && Mask[i] != i)
2989 // Lower quadword shuffled.
2990 for (int i = 0; i != 4; ++i)
2997 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2998 SmallVector<int, 8> M;
3000 return ::isPSHUFLWMask(M, N->getValueType(0));
3003 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3004 /// is suitable for input to PALIGNR.
3005 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3007 int i, e = VT.getVectorNumElements();
3009 // Do not handle v2i64 / v2f64 shuffles with palignr.
3010 if (e < 4 || !hasSSSE3)
3013 for (i = 0; i != e; ++i)
3017 // All undef, not a palignr.
3021 // Determine if it's ok to perform a palignr with only the LHS, since we
3022 // don't have access to the actual shuffle elements to see if RHS is undef.
3023 bool Unary = Mask[i] < (int)e;
3024 bool NeedsUnary = false;
3026 int s = Mask[i] - i;
3028 // Check the rest of the elements to see if they are consecutive.
3029 for (++i; i != e; ++i) {
3034 Unary = Unary && (m < (int)e);
3035 NeedsUnary = NeedsUnary || (m < s);
3037 if (NeedsUnary && !Unary)
3039 if (Unary && m != ((s+i) & (e-1)))
3041 if (!Unary && m != (s+i))
3047 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3048 SmallVector<int, 8> M;
3050 return ::isPALIGNRMask(M, N->getValueType(0), true);
3053 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3054 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3055 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3056 int NumElems = VT.getVectorNumElements();
3057 if (NumElems != 2 && NumElems != 4)
3060 int Half = NumElems / 2;
3061 for (int i = 0; i < Half; ++i)
3062 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3064 for (int i = Half; i < NumElems; ++i)
3065 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3071 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3072 SmallVector<int, 8> M;
3074 return ::isSHUFPMask(M, N->getValueType(0));
3077 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3078 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3079 /// half elements to come from vector 1 (which would equal the dest.) and
3080 /// the upper half to come from vector 2.
3081 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3082 int NumElems = VT.getVectorNumElements();
3084 if (NumElems != 2 && NumElems != 4)
3087 int Half = NumElems / 2;
3088 for (int i = 0; i < Half; ++i)
3089 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3091 for (int i = Half; i < NumElems; ++i)
3092 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3097 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3098 SmallVector<int, 8> M;
3100 return isCommutedSHUFPMask(M, N->getValueType(0));
3103 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3104 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3105 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3106 if (N->getValueType(0).getVectorNumElements() != 4)
3109 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3110 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3111 isUndefOrEqual(N->getMaskElt(1), 7) &&
3112 isUndefOrEqual(N->getMaskElt(2), 2) &&
3113 isUndefOrEqual(N->getMaskElt(3), 3);
3116 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3117 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3119 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3120 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3125 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3126 isUndefOrEqual(N->getMaskElt(1), 3) &&
3127 isUndefOrEqual(N->getMaskElt(2), 2) &&
3128 isUndefOrEqual(N->getMaskElt(3), 3);
3131 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3132 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3133 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3134 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3136 if (NumElems != 2 && NumElems != 4)
3139 for (unsigned i = 0; i < NumElems/2; ++i)
3140 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3143 for (unsigned i = NumElems/2; i < NumElems; ++i)
3144 if (!isUndefOrEqual(N->getMaskElt(i), i))
3150 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3151 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3152 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3153 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3155 if ((NumElems != 2 && NumElems != 4)
3156 || N->getValueType(0).getSizeInBits() > 128)
3159 for (unsigned i = 0; i < NumElems/2; ++i)
3160 if (!isUndefOrEqual(N->getMaskElt(i), i))
3163 for (unsigned i = 0; i < NumElems/2; ++i)
3164 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3170 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3171 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3172 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3173 bool V2IsSplat = false) {
3174 int NumElts = VT.getVectorNumElements();
3175 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3178 // Handle vector lengths > 128 bits. Define a "section" as a set of
3179 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3181 unsigned NumSections = VT.getSizeInBits() / 128;
3182 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3183 unsigned NumSectionElts = NumElts / NumSections;
3186 unsigned End = NumSectionElts;
3187 for (unsigned s = 0; s < NumSections; ++s) {
3188 for (unsigned i = Start, j = s * NumSectionElts;
3192 int BitI1 = Mask[i+1];
3193 if (!isUndefOrEqual(BitI, j))
3196 if (!isUndefOrEqual(BitI1, NumElts))
3199 if (!isUndefOrEqual(BitI1, j + NumElts))
3203 // Process the next 128 bits.
3204 Start += NumSectionElts;
3205 End += NumSectionElts;
3211 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3212 SmallVector<int, 8> M;
3214 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3217 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3218 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3219 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3220 bool V2IsSplat = false) {
3221 int NumElts = VT.getVectorNumElements();
3222 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3225 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3227 int BitI1 = Mask[i+1];
3228 if (!isUndefOrEqual(BitI, j + NumElts/2))
3231 if (isUndefOrEqual(BitI1, NumElts))
3234 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3241 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3242 SmallVector<int, 8> M;
3244 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3247 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3248 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3250 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3251 int NumElems = VT.getVectorNumElements();
3252 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3255 // Handle vector lengths > 128 bits. Define a "section" as a set of
3256 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3258 unsigned NumSections = VT.getSizeInBits() / 128;
3259 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3260 unsigned NumSectionElts = NumElems / NumSections;
3262 for (unsigned s = 0; s < NumSections; ++s) {
3263 for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3264 i != NumSectionElts * (s + 1);
3267 int BitI1 = Mask[i+1];
3269 if (!isUndefOrEqual(BitI, j))
3271 if (!isUndefOrEqual(BitI1, j))
3279 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3280 SmallVector<int, 8> M;
3282 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3285 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3286 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3288 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3289 int NumElems = VT.getVectorNumElements();
3290 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3293 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3295 int BitI1 = Mask[i+1];
3296 if (!isUndefOrEqual(BitI, j))
3298 if (!isUndefOrEqual(BitI1, j))
3304 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3305 SmallVector<int, 8> M;
3307 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3310 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3311 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3312 /// MOVSD, and MOVD, i.e. setting the lowest element.
3313 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3314 if (VT.getVectorElementType().getSizeInBits() < 32)
3317 int NumElts = VT.getVectorNumElements();
3319 if (!isUndefOrEqual(Mask[0], NumElts))
3322 for (int i = 1; i < NumElts; ++i)
3323 if (!isUndefOrEqual(Mask[i], i))
3329 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3330 SmallVector<int, 8> M;
3332 return ::isMOVLMask(M, N->getValueType(0));
3335 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3336 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3337 /// element of vector 2 and the other elements to come from vector 1 in order.
3338 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3339 bool V2IsSplat = false, bool V2IsUndef = false) {
3340 int NumOps = VT.getVectorNumElements();
3341 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3344 if (!isUndefOrEqual(Mask[0], 0))
3347 for (int i = 1; i < NumOps; ++i)
3348 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3349 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3350 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3356 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3357 bool V2IsUndef = false) {
3358 SmallVector<int, 8> M;
3360 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3363 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3364 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3365 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3366 if (N->getValueType(0).getVectorNumElements() != 4)
3369 // Expect 1, 1, 3, 3
3370 for (unsigned i = 0; i < 2; ++i) {
3371 int Elt = N->getMaskElt(i);
3372 if (Elt >= 0 && Elt != 1)
3377 for (unsigned i = 2; i < 4; ++i) {
3378 int Elt = N->getMaskElt(i);
3379 if (Elt >= 0 && Elt != 3)
3384 // Don't use movshdup if it can be done with a shufps.
3385 // FIXME: verify that matching u, u, 3, 3 is what we want.
3389 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3390 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3391 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3392 if (N->getValueType(0).getVectorNumElements() != 4)
3395 // Expect 0, 0, 2, 2
3396 for (unsigned i = 0; i < 2; ++i)
3397 if (N->getMaskElt(i) > 0)
3401 for (unsigned i = 2; i < 4; ++i) {
3402 int Elt = N->getMaskElt(i);
3403 if (Elt >= 0 && Elt != 2)
3408 // Don't use movsldup if it can be done with a shufps.
3412 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3413 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3414 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3415 int e = N->getValueType(0).getVectorNumElements() / 2;
3417 for (int i = 0; i < e; ++i)
3418 if (!isUndefOrEqual(N->getMaskElt(i), i))
3420 for (int i = 0; i < e; ++i)
3421 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3426 /// isVEXTRACTF128Index - Return true if the specified
3427 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3428 /// suitable for input to VEXTRACTF128.
3429 bool X86::isVEXTRACTF128Index(SDNode *N) {
3430 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3433 // The index should be aligned on a 128-bit boundary.
3435 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3437 unsigned VL = N->getValueType(0).getVectorNumElements();
3438 unsigned VBits = N->getValueType(0).getSizeInBits();
3439 unsigned ElSize = VBits / VL;
3440 bool Result = (Index * ElSize) % 128 == 0;
3445 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3446 /// operand specifies a subvector insert that is suitable for input to
3448 bool X86::isVINSERTF128Index(SDNode *N) {
3449 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3452 // The index should be aligned on a 128-bit boundary.
3454 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3456 unsigned VL = N->getValueType(0).getVectorNumElements();
3457 unsigned VBits = N->getValueType(0).getSizeInBits();
3458 unsigned ElSize = VBits / VL;
3459 bool Result = (Index * ElSize) % 128 == 0;
3464 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3465 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3466 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3467 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3468 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3470 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3472 for (int i = 0; i < NumOperands; ++i) {
3473 int Val = SVOp->getMaskElt(NumOperands-i-1);
3474 if (Val < 0) Val = 0;
3475 if (Val >= NumOperands) Val -= NumOperands;
3477 if (i != NumOperands - 1)
3483 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3484 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3485 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3486 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3488 // 8 nodes, but we only care about the last 4.
3489 for (unsigned i = 7; i >= 4; --i) {
3490 int Val = SVOp->getMaskElt(i);
3499 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3500 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3501 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3502 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3504 // 8 nodes, but we only care about the first 4.
3505 for (int i = 3; i >= 0; --i) {
3506 int Val = SVOp->getMaskElt(i);
3515 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3516 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3517 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3518 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3519 EVT VVT = N->getValueType(0);
3520 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3524 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3525 Val = SVOp->getMaskElt(i);
3529 return (Val - i) * EltSize;
3532 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3533 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3535 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3536 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3537 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3540 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3542 EVT VecVT = N->getOperand(0).getValueType();
3543 EVT ElVT = VecVT.getVectorElementType();
3545 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3547 return Index / NumElemsPerChunk;
3550 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3551 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3553 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3554 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3555 llvm_unreachable("Illegal insert subvector for VINSERTF128");
3558 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3560 EVT VecVT = N->getValueType(0);
3561 EVT ElVT = VecVT.getVectorElementType();
3563 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3565 return Index / NumElemsPerChunk;
3568 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3570 bool X86::isZeroNode(SDValue Elt) {
3571 return ((isa<ConstantSDNode>(Elt) &&
3572 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3573 (isa<ConstantFPSDNode>(Elt) &&
3574 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3577 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3578 /// their permute mask.
3579 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3580 SelectionDAG &DAG) {
3581 EVT VT = SVOp->getValueType(0);
3582 unsigned NumElems = VT.getVectorNumElements();
3583 SmallVector<int, 8> MaskVec;
3585 for (unsigned i = 0; i != NumElems; ++i) {
3586 int idx = SVOp->getMaskElt(i);
3588 MaskVec.push_back(idx);
3589 else if (idx < (int)NumElems)
3590 MaskVec.push_back(idx + NumElems);
3592 MaskVec.push_back(idx - NumElems);
3594 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3595 SVOp->getOperand(0), &MaskVec[0]);
3598 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3599 /// the two vector operands have swapped position.
3600 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3601 unsigned NumElems = VT.getVectorNumElements();
3602 for (unsigned i = 0; i != NumElems; ++i) {
3606 else if (idx < (int)NumElems)
3607 Mask[i] = idx + NumElems;
3609 Mask[i] = idx - NumElems;
3613 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3614 /// match movhlps. The lower half elements should come from upper half of
3615 /// V1 (and in order), and the upper half elements should come from the upper
3616 /// half of V2 (and in order).
3617 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3618 if (Op->getValueType(0).getVectorNumElements() != 4)
3620 for (unsigned i = 0, e = 2; i != e; ++i)
3621 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3623 for (unsigned i = 2; i != 4; ++i)
3624 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3629 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3630 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3632 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3633 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3635 N = N->getOperand(0).getNode();
3636 if (!ISD::isNON_EXTLoad(N))
3639 *LD = cast<LoadSDNode>(N);
3643 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3644 /// match movlp{s|d}. The lower half elements should come from lower half of
3645 /// V1 (and in order), and the upper half elements should come from the upper
3646 /// half of V2 (and in order). And since V1 will become the source of the
3647 /// MOVLP, it must be either a vector load or a scalar load to vector.
3648 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3649 ShuffleVectorSDNode *Op) {
3650 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3652 // Is V2 is a vector load, don't do this transformation. We will try to use
3653 // load folding shufps op.
3654 if (ISD::isNON_EXTLoad(V2))
3657 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3659 if (NumElems != 2 && NumElems != 4)
3661 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3662 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3664 for (unsigned i = NumElems/2; i != NumElems; ++i)
3665 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3670 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3672 static bool isSplatVector(SDNode *N) {
3673 if (N->getOpcode() != ISD::BUILD_VECTOR)
3676 SDValue SplatValue = N->getOperand(0);
3677 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3678 if (N->getOperand(i) != SplatValue)
3683 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3684 /// to an zero vector.
3685 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3686 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3687 SDValue V1 = N->getOperand(0);
3688 SDValue V2 = N->getOperand(1);
3689 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3690 for (unsigned i = 0; i != NumElems; ++i) {
3691 int Idx = N->getMaskElt(i);
3692 if (Idx >= (int)NumElems) {
3693 unsigned Opc = V2.getOpcode();
3694 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3696 if (Opc != ISD::BUILD_VECTOR ||
3697 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3699 } else if (Idx >= 0) {
3700 unsigned Opc = V1.getOpcode();
3701 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3703 if (Opc != ISD::BUILD_VECTOR ||
3704 !X86::isZeroNode(V1.getOperand(Idx)))
3711 /// getZeroVector - Returns a vector of specified type with all zero elements.
3713 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3715 assert(VT.isVector() && "Expected a vector type");
3717 // Always build SSE zero vectors as <4 x i32> bitcasted
3718 // to their dest type. This ensures they get CSE'd.
3720 if (VT.getSizeInBits() == 128) { // SSE
3721 if (HasSSE2) { // SSE2
3722 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3723 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3725 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3726 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3728 } else if (VT.getSizeInBits() == 256) { // AVX
3729 // 256-bit logic and arithmetic instructions in AVX are
3730 // all floating-point, no support for integer ops. Default
3731 // to emitting fp zeroed vectors then.
3732 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3733 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3734 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3736 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3739 /// getOnesVector - Returns a vector of specified type with all bits set.
3741 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3742 assert(VT.isVector() && "Expected a vector type");
3744 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3745 // type. This ensures they get CSE'd.
3746 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3748 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3749 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3753 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3754 /// that point to V2 points to its first element.
3755 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3756 EVT VT = SVOp->getValueType(0);
3757 unsigned NumElems = VT.getVectorNumElements();
3759 bool Changed = false;
3760 SmallVector<int, 8> MaskVec;
3761 SVOp->getMask(MaskVec);
3763 for (unsigned i = 0; i != NumElems; ++i) {
3764 if (MaskVec[i] > (int)NumElems) {
3765 MaskVec[i] = NumElems;
3770 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3771 SVOp->getOperand(1), &MaskVec[0]);
3772 return SDValue(SVOp, 0);
3775 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3776 /// operation of specified width.
3777 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3779 unsigned NumElems = VT.getVectorNumElements();
3780 SmallVector<int, 8> Mask;
3781 Mask.push_back(NumElems);
3782 for (unsigned i = 1; i != NumElems; ++i)
3784 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3787 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3788 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3790 unsigned NumElems = VT.getVectorNumElements();
3791 SmallVector<int, 8> Mask;
3792 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3794 Mask.push_back(i + NumElems);
3796 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3799 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3800 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3802 unsigned NumElems = VT.getVectorNumElements();
3803 unsigned Half = NumElems/2;
3804 SmallVector<int, 8> Mask;
3805 for (unsigned i = 0; i != Half; ++i) {
3806 Mask.push_back(i + Half);
3807 Mask.push_back(i + NumElems + Half);
3809 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3812 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3813 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3814 EVT PVT = MVT::v4f32;
3815 EVT VT = SV->getValueType(0);
3816 DebugLoc dl = SV->getDebugLoc();
3817 SDValue V1 = SV->getOperand(0);
3818 int NumElems = VT.getVectorNumElements();
3819 int EltNo = SV->getSplatIndex();
3821 // unpack elements to the correct location
3822 while (NumElems > 4) {
3823 if (EltNo < NumElems/2) {
3824 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3826 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3827 EltNo -= NumElems/2;
3832 // Perform the splat.
3833 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3834 V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3835 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3836 return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3839 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3840 /// vector of zero or undef vector. This produces a shuffle where the low
3841 /// element of V2 is swizzled into the zero/undef vector, landing at element
3842 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3843 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3844 bool isZero, bool HasSSE2,
3845 SelectionDAG &DAG) {
3846 EVT VT = V2.getValueType();
3848 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3849 unsigned NumElems = VT.getVectorNumElements();
3850 SmallVector<int, 16> MaskVec;
3851 for (unsigned i = 0; i != NumElems; ++i)
3852 // If this is the insertion idx, put the low elt of V2 here.
3853 MaskVec.push_back(i == Idx ? NumElems : i);
3854 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3857 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3858 /// element of the result of the vector shuffle.
3859 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3862 return SDValue(); // Limit search depth.
3864 SDValue V = SDValue(N, 0);
3865 EVT VT = V.getValueType();
3866 unsigned Opcode = V.getOpcode();
3868 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3869 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3870 Index = SV->getMaskElt(Index);
3873 return DAG.getUNDEF(VT.getVectorElementType());
3875 int NumElems = VT.getVectorNumElements();
3876 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3877 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3880 // Recurse into target specific vector shuffles to find scalars.
3881 if (isTargetShuffle(Opcode)) {
3882 int NumElems = VT.getVectorNumElements();
3883 SmallVector<unsigned, 16> ShuffleMask;
3887 case X86ISD::SHUFPS:
3888 case X86ISD::SHUFPD:
3889 ImmN = N->getOperand(N->getNumOperands()-1);
3890 DecodeSHUFPSMask(NumElems,
3891 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3894 case X86ISD::PUNPCKHBW:
3895 case X86ISD::PUNPCKHWD:
3896 case X86ISD::PUNPCKHDQ:
3897 case X86ISD::PUNPCKHQDQ:
3898 DecodePUNPCKHMask(NumElems, ShuffleMask);
3900 case X86ISD::UNPCKHPS:
3901 case X86ISD::UNPCKHPD:
3902 DecodeUNPCKHPMask(NumElems, ShuffleMask);
3904 case X86ISD::PUNPCKLBW:
3905 case X86ISD::PUNPCKLWD:
3906 case X86ISD::PUNPCKLDQ:
3907 case X86ISD::PUNPCKLQDQ:
3908 DecodePUNPCKLMask(VT, ShuffleMask);
3910 case X86ISD::UNPCKLPS:
3911 case X86ISD::UNPCKLPD:
3912 case X86ISD::VUNPCKLPS:
3913 case X86ISD::VUNPCKLPD:
3914 case X86ISD::VUNPCKLPSY:
3915 case X86ISD::VUNPCKLPDY:
3916 DecodeUNPCKLPMask(VT, ShuffleMask);
3918 case X86ISD::MOVHLPS:
3919 DecodeMOVHLPSMask(NumElems, ShuffleMask);
3921 case X86ISD::MOVLHPS:
3922 DecodeMOVLHPSMask(NumElems, ShuffleMask);
3924 case X86ISD::PSHUFD:
3925 ImmN = N->getOperand(N->getNumOperands()-1);
3926 DecodePSHUFMask(NumElems,
3927 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3930 case X86ISD::PSHUFHW:
3931 ImmN = N->getOperand(N->getNumOperands()-1);
3932 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3935 case X86ISD::PSHUFLW:
3936 ImmN = N->getOperand(N->getNumOperands()-1);
3937 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3941 case X86ISD::MOVSD: {
3942 // The index 0 always comes from the first element of the second source,
3943 // this is why MOVSS and MOVSD are used in the first place. The other
3944 // elements come from the other positions of the first source vector.
3945 unsigned OpNum = (Index == 0) ? 1 : 0;
3946 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3950 assert("not implemented for target shuffle node");
3954 Index = ShuffleMask[Index];
3956 return DAG.getUNDEF(VT.getVectorElementType());
3958 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3959 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3963 // Actual nodes that may contain scalar elements
3964 if (Opcode == ISD::BITCAST) {
3965 V = V.getOperand(0);
3966 EVT SrcVT = V.getValueType();
3967 unsigned NumElems = VT.getVectorNumElements();
3969 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3973 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3974 return (Index == 0) ? V.getOperand(0)
3975 : DAG.getUNDEF(VT.getVectorElementType());
3977 if (V.getOpcode() == ISD::BUILD_VECTOR)
3978 return V.getOperand(Index);
3983 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3984 /// shuffle operation which come from a consecutively from a zero. The
3985 /// search can start in two diferent directions, from left or right.
3987 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3988 bool ZerosFromLeft, SelectionDAG &DAG) {
3991 while (i < NumElems) {
3992 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3993 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3994 if (!(Elt.getNode() &&
3995 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4003 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4004 /// MaskE correspond consecutively to elements from one of the vector operands,
4005 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4007 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4008 int OpIdx, int NumElems, unsigned &OpNum) {
4009 bool SeenV1 = false;
4010 bool SeenV2 = false;
4012 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4013 int Idx = SVOp->getMaskElt(i);
4014 // Ignore undef indicies
4023 // Only accept consecutive elements from the same vector
4024 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4028 OpNum = SeenV1 ? 0 : 1;
4032 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4033 /// logical left shift of a vector.
4034 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4035 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4036 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4037 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4038 false /* check zeros from right */, DAG);
4044 // Considering the elements in the mask that are not consecutive zeros,
4045 // check if they consecutively come from only one of the source vectors.
4047 // V1 = {X, A, B, C} 0
4049 // vector_shuffle V1, V2 <1, 2, 3, X>
4051 if (!isShuffleMaskConsecutive(SVOp,
4052 0, // Mask Start Index
4053 NumElems-NumZeros-1, // Mask End Index
4054 NumZeros, // Where to start looking in the src vector
4055 NumElems, // Number of elements in vector
4056 OpSrc)) // Which source operand ?
4061 ShVal = SVOp->getOperand(OpSrc);
4065 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4066 /// logical left shift of a vector.
4067 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4068 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4069 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4070 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4071 true /* check zeros from left */, DAG);
4077 // Considering the elements in the mask that are not consecutive zeros,
4078 // check if they consecutively come from only one of the source vectors.
4080 // 0 { A, B, X, X } = V2
4082 // vector_shuffle V1, V2 <X, X, 4, 5>
4084 if (!isShuffleMaskConsecutive(SVOp,
4085 NumZeros, // Mask Start Index
4086 NumElems-1, // Mask End Index
4087 0, // Where to start looking in the src vector
4088 NumElems, // Number of elements in vector
4089 OpSrc)) // Which source operand ?
4094 ShVal = SVOp->getOperand(OpSrc);
4098 /// isVectorShift - Returns true if the shuffle can be implemented as a
4099 /// logical left or right shift of a vector.
4100 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4101 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4102 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4103 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4109 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4111 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4112 unsigned NumNonZero, unsigned NumZero,
4114 const TargetLowering &TLI) {
4118 DebugLoc dl = Op.getDebugLoc();
4121 for (unsigned i = 0; i < 16; ++i) {
4122 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4123 if (ThisIsNonZero && First) {
4125 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4127 V = DAG.getUNDEF(MVT::v8i16);
4132 SDValue ThisElt(0, 0), LastElt(0, 0);
4133 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4134 if (LastIsNonZero) {
4135 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4136 MVT::i16, Op.getOperand(i-1));
4138 if (ThisIsNonZero) {
4139 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4140 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4141 ThisElt, DAG.getConstant(8, MVT::i8));
4143 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4147 if (ThisElt.getNode())
4148 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4149 DAG.getIntPtrConstant(i/2));
4153 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4156 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4158 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4159 unsigned NumNonZero, unsigned NumZero,
4161 const TargetLowering &TLI) {
4165 DebugLoc dl = Op.getDebugLoc();
4168 for (unsigned i = 0; i < 8; ++i) {
4169 bool isNonZero = (NonZeros & (1 << i)) != 0;
4173 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4175 V = DAG.getUNDEF(MVT::v8i16);
4178 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4179 MVT::v8i16, V, Op.getOperand(i),
4180 DAG.getIntPtrConstant(i));
4187 /// getVShift - Return a vector logical shift node.
4189 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4190 unsigned NumBits, SelectionDAG &DAG,
4191 const TargetLowering &TLI, DebugLoc dl) {
4192 EVT ShVT = MVT::v2i64;
4193 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4194 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4195 return DAG.getNode(ISD::BITCAST, dl, VT,
4196 DAG.getNode(Opc, dl, ShVT, SrcOp,
4197 DAG.getConstant(NumBits,
4198 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4202 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4203 SelectionDAG &DAG) const {
4205 // Check if the scalar load can be widened into a vector load. And if
4206 // the address is "base + cst" see if the cst can be "absorbed" into
4207 // the shuffle mask.
4208 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4209 SDValue Ptr = LD->getBasePtr();
4210 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4212 EVT PVT = LD->getValueType(0);
4213 if (PVT != MVT::i32 && PVT != MVT::f32)
4218 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4219 FI = FINode->getIndex();
4221 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4222 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4223 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4224 Offset = Ptr.getConstantOperandVal(1);
4225 Ptr = Ptr.getOperand(0);
4230 SDValue Chain = LD->getChain();
4231 // Make sure the stack object alignment is at least 16.
4232 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4233 if (DAG.InferPtrAlignment(Ptr) < 16) {
4234 if (MFI->isFixedObjectIndex(FI)) {
4235 // Can't change the alignment. FIXME: It's possible to compute
4236 // the exact stack offset and reference FI + adjust offset instead.
4237 // If someone *really* cares about this. That's the way to implement it.
4240 MFI->setObjectAlignment(FI, 16);
4244 // (Offset % 16) must be multiple of 4. Then address is then
4245 // Ptr + (Offset & ~15).
4248 if ((Offset % 16) & 3)
4250 int64_t StartOffset = Offset & ~15;
4252 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4253 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4255 int EltNo = (Offset - StartOffset) >> 2;
4256 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4257 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4258 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4259 LD->getPointerInfo().getWithOffset(StartOffset),
4261 // Canonicalize it to a v4i32 shuffle.
4262 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4263 return DAG.getNode(ISD::BITCAST, dl, VT,
4264 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4265 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4271 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4272 /// vector of type 'VT', see if the elements can be replaced by a single large
4273 /// load which has the same value as a build_vector whose operands are 'elts'.
4275 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4277 /// FIXME: we'd also like to handle the case where the last elements are zero
4278 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4279 /// There's even a handy isZeroNode for that purpose.
4280 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4281 DebugLoc &DL, SelectionDAG &DAG) {
4282 EVT EltVT = VT.getVectorElementType();
4283 unsigned NumElems = Elts.size();
4285 LoadSDNode *LDBase = NULL;
4286 unsigned LastLoadedElt = -1U;
4288 // For each element in the initializer, see if we've found a load or an undef.
4289 // If we don't find an initial load element, or later load elements are
4290 // non-consecutive, bail out.
4291 for (unsigned i = 0; i < NumElems; ++i) {
4292 SDValue Elt = Elts[i];
4294 if (!Elt.getNode() ||
4295 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4298 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4300 LDBase = cast<LoadSDNode>(Elt.getNode());
4304 if (Elt.getOpcode() == ISD::UNDEF)
4307 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4308 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4313 // If we have found an entire vector of loads and undefs, then return a large
4314 // load of the entire vector width starting at the base pointer. If we found
4315 // consecutive loads for the low half, generate a vzext_load node.
4316 if (LastLoadedElt == NumElems - 1) {
4317 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4318 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4319 LDBase->getPointerInfo(),
4320 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4321 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4322 LDBase->getPointerInfo(),
4323 LDBase->isVolatile(), LDBase->isNonTemporal(),
4324 LDBase->getAlignment());
4325 } else if (NumElems == 4 && LastLoadedElt == 1) {
4326 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4327 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4328 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4330 LDBase->getMemOperand());
4331 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4337 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4338 DebugLoc dl = Op.getDebugLoc();
4340 EVT VT = Op.getValueType();
4341 EVT ExtVT = VT.getVectorElementType();
4343 unsigned NumElems = Op.getNumOperands();
4345 // For AVX-length vectors, build the individual 128-bit pieces and
4346 // use shuffles to put them in place.
4347 if (VT.getSizeInBits() > 256 &&
4348 Subtarget->hasAVX() &&
4349 !ISD::isBuildVectorAllZeros(Op.getNode())) {
4350 SmallVector<SDValue, 8> V;
4352 for (unsigned i = 0; i < NumElems; ++i) {
4353 V[i] = Op.getOperand(i);
4356 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4358 // Build the lower subvector.
4359 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4360 // Build the upper subvector.
4361 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4364 return ConcatVectors(Lower, Upper, DAG);
4367 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4368 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4369 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4370 // is present, so AllOnes is ignored.
4371 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4372 (Op.getValueType().getSizeInBits() != 256 &&
4373 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4374 // Canonicalize this to <4 x i32> (SSE) to
4375 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4376 // eliminated on x86-32 hosts.
4377 if (Op.getValueType() == MVT::v4i32)
4380 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4381 return getOnesVector(Op.getValueType(), DAG, dl);
4382 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4385 unsigned EVTBits = ExtVT.getSizeInBits();
4387 unsigned NumZero = 0;
4388 unsigned NumNonZero = 0;
4389 unsigned NonZeros = 0;
4390 bool IsAllConstants = true;
4391 SmallSet<SDValue, 8> Values;
4392 for (unsigned i = 0; i < NumElems; ++i) {
4393 SDValue Elt = Op.getOperand(i);
4394 if (Elt.getOpcode() == ISD::UNDEF)
4397 if (Elt.getOpcode() != ISD::Constant &&
4398 Elt.getOpcode() != ISD::ConstantFP)
4399 IsAllConstants = false;
4400 if (X86::isZeroNode(Elt))
4403 NonZeros |= (1 << i);
4408 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4409 if (NumNonZero == 0)
4410 return DAG.getUNDEF(VT);
4412 // Special case for single non-zero, non-undef, element.
4413 if (NumNonZero == 1) {
4414 unsigned Idx = CountTrailingZeros_32(NonZeros);
4415 SDValue Item = Op.getOperand(Idx);
4417 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4418 // the value are obviously zero, truncate the value to i32 and do the
4419 // insertion that way. Only do this if the value is non-constant or if the
4420 // value is a constant being inserted into element 0. It is cheaper to do
4421 // a constant pool load than it is to do a movd + shuffle.
4422 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4423 (!IsAllConstants || Idx == 0)) {
4424 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4426 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4427 EVT VecVT = MVT::v4i32;
4428 unsigned VecElts = 4;
4430 // Truncate the value (which may itself be a constant) to i32, and
4431 // convert it to a vector with movd (S2V+shuffle to zero extend).
4432 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4433 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4434 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4435 Subtarget->hasSSE2(), DAG);
4437 // Now we have our 32-bit value zero extended in the low element of
4438 // a vector. If Idx != 0, swizzle it into place.
4440 SmallVector<int, 4> Mask;
4441 Mask.push_back(Idx);
4442 for (unsigned i = 1; i != VecElts; ++i)
4444 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4445 DAG.getUNDEF(Item.getValueType()),
4448 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4452 // If we have a constant or non-constant insertion into the low element of
4453 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4454 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4455 // depending on what the source datatype is.
4458 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4459 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4460 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4461 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4462 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4463 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4465 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4466 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4467 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4468 EVT MiddleVT = MVT::v4i32;
4469 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4470 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4471 Subtarget->hasSSE2(), DAG);
4472 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4476 // Is it a vector logical left shift?
4477 if (NumElems == 2 && Idx == 1 &&
4478 X86::isZeroNode(Op.getOperand(0)) &&
4479 !X86::isZeroNode(Op.getOperand(1))) {
4480 unsigned NumBits = VT.getSizeInBits();
4481 return getVShift(true, VT,
4482 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4483 VT, Op.getOperand(1)),
4484 NumBits/2, DAG, *this, dl);
4487 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4490 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4491 // is a non-constant being inserted into an element other than the low one,
4492 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4493 // movd/movss) to move this into the low element, then shuffle it into
4495 if (EVTBits == 32) {
4496 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4498 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4499 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4500 Subtarget->hasSSE2(), DAG);
4501 SmallVector<int, 8> MaskVec;
4502 for (unsigned i = 0; i < NumElems; i++)
4503 MaskVec.push_back(i == Idx ? 0 : 1);
4504 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4508 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4509 if (Values.size() == 1) {
4510 if (EVTBits == 32) {
4511 // Instead of a shuffle like this:
4512 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4513 // Check if it's possible to issue this instead.
4514 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4515 unsigned Idx = CountTrailingZeros_32(NonZeros);
4516 SDValue Item = Op.getOperand(Idx);
4517 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4518 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4523 // A vector full of immediates; various special cases are already
4524 // handled, so this is best done with a single constant-pool load.
4528 // Let legalizer expand 2-wide build_vectors.
4529 if (EVTBits == 64) {
4530 if (NumNonZero == 1) {
4531 // One half is zero or undef.
4532 unsigned Idx = CountTrailingZeros_32(NonZeros);
4533 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4534 Op.getOperand(Idx));
4535 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4536 Subtarget->hasSSE2(), DAG);
4541 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4542 if (EVTBits == 8 && NumElems == 16) {
4543 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4545 if (V.getNode()) return V;
4548 if (EVTBits == 16 && NumElems == 8) {
4549 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4551 if (V.getNode()) return V;
4554 // If element VT is == 32 bits, turn it into a number of shuffles.
4555 SmallVector<SDValue, 8> V;
4557 if (NumElems == 4 && NumZero > 0) {
4558 for (unsigned i = 0; i < 4; ++i) {
4559 bool isZero = !(NonZeros & (1 << i));
4561 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4563 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4566 for (unsigned i = 0; i < 2; ++i) {
4567 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4570 V[i] = V[i*2]; // Must be a zero vector.
4573 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4576 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4579 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4584 SmallVector<int, 8> MaskVec;
4585 bool Reverse = (NonZeros & 0x3) == 2;
4586 for (unsigned i = 0; i < 2; ++i)
4587 MaskVec.push_back(Reverse ? 1-i : i);
4588 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4589 for (unsigned i = 0; i < 2; ++i)
4590 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4591 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4594 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4595 // Check for a build vector of consecutive loads.
4596 for (unsigned i = 0; i < NumElems; ++i)
4597 V[i] = Op.getOperand(i);
4599 // Check for elements which are consecutive loads.
4600 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4604 // For SSE 4.1, use insertps to put the high elements into the low element.
4605 if (getSubtarget()->hasSSE41()) {
4607 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4608 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4610 Result = DAG.getUNDEF(VT);
4612 for (unsigned i = 1; i < NumElems; ++i) {
4613 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4614 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4615 Op.getOperand(i), DAG.getIntPtrConstant(i));
4620 // Otherwise, expand into a number of unpckl*, start by extending each of
4621 // our (non-undef) elements to the full vector width with the element in the
4622 // bottom slot of the vector (which generates no code for SSE).
4623 for (unsigned i = 0; i < NumElems; ++i) {
4624 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4625 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4627 V[i] = DAG.getUNDEF(VT);
4630 // Next, we iteratively mix elements, e.g. for v4f32:
4631 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4632 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4633 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4634 unsigned EltStride = NumElems >> 1;
4635 while (EltStride != 0) {
4636 for (unsigned i = 0; i < EltStride; ++i) {
4637 // If V[i+EltStride] is undef and this is the first round of mixing,
4638 // then it is safe to just drop this shuffle: V[i] is already in the
4639 // right place, the one element (since it's the first round) being
4640 // inserted as undef can be dropped. This isn't safe for successive
4641 // rounds because they will permute elements within both vectors.
4642 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4643 EltStride == NumElems/2)
4646 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4656 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4657 // We support concatenate two MMX registers and place them in a MMX
4658 // register. This is better than doing a stack convert.
4659 DebugLoc dl = Op.getDebugLoc();
4660 EVT ResVT = Op.getValueType();
4661 assert(Op.getNumOperands() == 2);
4662 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4663 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4665 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4666 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4667 InVec = Op.getOperand(1);
4668 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4669 unsigned NumElts = ResVT.getVectorNumElements();
4670 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4671 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4672 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4674 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4675 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4676 Mask[0] = 0; Mask[1] = 2;
4677 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4679 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4682 // v8i16 shuffles - Prefer shuffles in the following order:
4683 // 1. [all] pshuflw, pshufhw, optional move
4684 // 2. [ssse3] 1 x pshufb
4685 // 3. [ssse3] 2 x pshufb + 1 x por
4686 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4688 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4689 SelectionDAG &DAG) const {
4690 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4691 SDValue V1 = SVOp->getOperand(0);
4692 SDValue V2 = SVOp->getOperand(1);
4693 DebugLoc dl = SVOp->getDebugLoc();
4694 SmallVector<int, 8> MaskVals;
4696 // Determine if more than 1 of the words in each of the low and high quadwords
4697 // of the result come from the same quadword of one of the two inputs. Undef
4698 // mask values count as coming from any quadword, for better codegen.
4699 SmallVector<unsigned, 4> LoQuad(4);
4700 SmallVector<unsigned, 4> HiQuad(4);
4701 BitVector InputQuads(4);
4702 for (unsigned i = 0; i < 8; ++i) {
4703 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4704 int EltIdx = SVOp->getMaskElt(i);
4705 MaskVals.push_back(EltIdx);
4714 InputQuads.set(EltIdx / 4);
4717 int BestLoQuad = -1;
4718 unsigned MaxQuad = 1;
4719 for (unsigned i = 0; i < 4; ++i) {
4720 if (LoQuad[i] > MaxQuad) {
4722 MaxQuad = LoQuad[i];
4726 int BestHiQuad = -1;
4728 for (unsigned i = 0; i < 4; ++i) {
4729 if (HiQuad[i] > MaxQuad) {
4731 MaxQuad = HiQuad[i];
4735 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4736 // of the two input vectors, shuffle them into one input vector so only a
4737 // single pshufb instruction is necessary. If There are more than 2 input
4738 // quads, disable the next transformation since it does not help SSSE3.
4739 bool V1Used = InputQuads[0] || InputQuads[1];
4740 bool V2Used = InputQuads[2] || InputQuads[3];
4741 if (Subtarget->hasSSSE3()) {
4742 if (InputQuads.count() == 2 && V1Used && V2Used) {
4743 BestLoQuad = InputQuads.find_first();
4744 BestHiQuad = InputQuads.find_next(BestLoQuad);
4746 if (InputQuads.count() > 2) {
4752 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4753 // the shuffle mask. If a quad is scored as -1, that means that it contains
4754 // words from all 4 input quadwords.
4756 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4757 SmallVector<int, 8> MaskV;
4758 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4759 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4760 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4761 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4762 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4763 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4765 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4766 // source words for the shuffle, to aid later transformations.
4767 bool AllWordsInNewV = true;
4768 bool InOrder[2] = { true, true };
4769 for (unsigned i = 0; i != 8; ++i) {
4770 int idx = MaskVals[i];
4772 InOrder[i/4] = false;
4773 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4775 AllWordsInNewV = false;
4779 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4780 if (AllWordsInNewV) {
4781 for (int i = 0; i != 8; ++i) {
4782 int idx = MaskVals[i];
4785 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4786 if ((idx != i) && idx < 4)
4788 if ((idx != i) && idx > 3)
4797 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4798 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4799 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4800 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4801 unsigned TargetMask = 0;
4802 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4803 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4804 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4805 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4806 V1 = NewV.getOperand(0);
4807 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4811 // If we have SSSE3, and all words of the result are from 1 input vector,
4812 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4813 // is present, fall back to case 4.
4814 if (Subtarget->hasSSSE3()) {
4815 SmallVector<SDValue,16> pshufbMask;
4817 // If we have elements from both input vectors, set the high bit of the
4818 // shuffle mask element to zero out elements that come from V2 in the V1
4819 // mask, and elements that come from V1 in the V2 mask, so that the two
4820 // results can be OR'd together.
4821 bool TwoInputs = V1Used && V2Used;
4822 for (unsigned i = 0; i != 8; ++i) {
4823 int EltIdx = MaskVals[i] * 2;
4824 if (TwoInputs && (EltIdx >= 16)) {
4825 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4826 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4829 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4830 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4832 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4833 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4834 DAG.getNode(ISD::BUILD_VECTOR, dl,
4835 MVT::v16i8, &pshufbMask[0], 16));
4837 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4839 // Calculate the shuffle mask for the second input, shuffle it, and
4840 // OR it with the first shuffled input.
4842 for (unsigned i = 0; i != 8; ++i) {
4843 int EltIdx = MaskVals[i] * 2;
4845 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4846 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4849 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4850 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4852 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4853 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4854 DAG.getNode(ISD::BUILD_VECTOR, dl,
4855 MVT::v16i8, &pshufbMask[0], 16));
4856 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4857 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4860 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4861 // and update MaskVals with new element order.
4862 BitVector InOrder(8);
4863 if (BestLoQuad >= 0) {
4864 SmallVector<int, 8> MaskV;
4865 for (int i = 0; i != 4; ++i) {
4866 int idx = MaskVals[i];
4868 MaskV.push_back(-1);
4870 } else if ((idx / 4) == BestLoQuad) {
4871 MaskV.push_back(idx & 3);
4874 MaskV.push_back(-1);
4877 for (unsigned i = 4; i != 8; ++i)
4879 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4882 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4883 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4885 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4889 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4890 // and update MaskVals with the new element order.
4891 if (BestHiQuad >= 0) {
4892 SmallVector<int, 8> MaskV;
4893 for (unsigned i = 0; i != 4; ++i)
4895 for (unsigned i = 4; i != 8; ++i) {
4896 int idx = MaskVals[i];
4898 MaskV.push_back(-1);
4900 } else if ((idx / 4) == BestHiQuad) {
4901 MaskV.push_back((idx & 3) + 4);
4904 MaskV.push_back(-1);
4907 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4910 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4911 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4913 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4917 // In case BestHi & BestLo were both -1, which means each quadword has a word
4918 // from each of the four input quadwords, calculate the InOrder bitvector now
4919 // before falling through to the insert/extract cleanup.
4920 if (BestLoQuad == -1 && BestHiQuad == -1) {
4922 for (int i = 0; i != 8; ++i)
4923 if (MaskVals[i] < 0 || MaskVals[i] == i)
4927 // The other elements are put in the right place using pextrw and pinsrw.
4928 for (unsigned i = 0; i != 8; ++i) {
4931 int EltIdx = MaskVals[i];
4934 SDValue ExtOp = (EltIdx < 8)
4935 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4936 DAG.getIntPtrConstant(EltIdx))
4937 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4938 DAG.getIntPtrConstant(EltIdx - 8));
4939 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4940 DAG.getIntPtrConstant(i));
4945 // v16i8 shuffles - Prefer shuffles in the following order:
4946 // 1. [ssse3] 1 x pshufb
4947 // 2. [ssse3] 2 x pshufb + 1 x por
4948 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4950 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4952 const X86TargetLowering &TLI) {
4953 SDValue V1 = SVOp->getOperand(0);
4954 SDValue V2 = SVOp->getOperand(1);
4955 DebugLoc dl = SVOp->getDebugLoc();
4956 SmallVector<int, 16> MaskVals;
4957 SVOp->getMask(MaskVals);
4959 // If we have SSSE3, case 1 is generated when all result bytes come from
4960 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4961 // present, fall back to case 3.
4962 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4965 for (unsigned i = 0; i < 16; ++i) {
4966 int EltIdx = MaskVals[i];
4975 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4976 if (TLI.getSubtarget()->hasSSSE3()) {
4977 SmallVector<SDValue,16> pshufbMask;
4979 // If all result elements are from one input vector, then only translate
4980 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4982 // Otherwise, we have elements from both input vectors, and must zero out
4983 // elements that come from V2 in the first mask, and V1 in the second mask
4984 // so that we can OR them together.
4985 bool TwoInputs = !(V1Only || V2Only);
4986 for (unsigned i = 0; i != 16; ++i) {
4987 int EltIdx = MaskVals[i];
4988 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4989 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4992 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4994 // If all the elements are from V2, assign it to V1 and return after
4995 // building the first pshufb.
4998 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4999 DAG.getNode(ISD::BUILD_VECTOR, dl,
5000 MVT::v16i8, &pshufbMask[0], 16));
5004 // Calculate the shuffle mask for the second input, shuffle it, and
5005 // OR it with the first shuffled input.
5007 for (unsigned i = 0; i != 16; ++i) {
5008 int EltIdx = MaskVals[i];
5010 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5013 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5015 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5016 DAG.getNode(ISD::BUILD_VECTOR, dl,
5017 MVT::v16i8, &pshufbMask[0], 16));
5018 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5021 // No SSSE3 - Calculate in place words and then fix all out of place words
5022 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5023 // the 16 different words that comprise the two doublequadword input vectors.
5024 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5025 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5026 SDValue NewV = V2Only ? V2 : V1;
5027 for (int i = 0; i != 8; ++i) {
5028 int Elt0 = MaskVals[i*2];
5029 int Elt1 = MaskVals[i*2+1];
5031 // This word of the result is all undef, skip it.
5032 if (Elt0 < 0 && Elt1 < 0)
5035 // This word of the result is already in the correct place, skip it.
5036 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5038 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5041 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5042 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5045 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5046 // using a single extract together, load it and store it.
5047 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5048 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5049 DAG.getIntPtrConstant(Elt1 / 2));
5050 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5051 DAG.getIntPtrConstant(i));
5055 // If Elt1 is defined, extract it from the appropriate source. If the
5056 // source byte is not also odd, shift the extracted word left 8 bits
5057 // otherwise clear the bottom 8 bits if we need to do an or.
5059 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5060 DAG.getIntPtrConstant(Elt1 / 2));
5061 if ((Elt1 & 1) == 0)
5062 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5064 TLI.getShiftAmountTy(InsElt.getValueType())));
5066 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5067 DAG.getConstant(0xFF00, MVT::i16));
5069 // If Elt0 is defined, extract it from the appropriate source. If the
5070 // source byte is not also even, shift the extracted word right 8 bits. If
5071 // Elt1 was also defined, OR the extracted values together before
5072 // inserting them in the result.
5074 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5075 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5076 if ((Elt0 & 1) != 0)
5077 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5079 TLI.getShiftAmountTy(InsElt0.getValueType())));
5081 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5082 DAG.getConstant(0x00FF, MVT::i16));
5083 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5086 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5087 DAG.getIntPtrConstant(i));
5089 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5092 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5093 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5094 /// done when every pair / quad of shuffle mask elements point to elements in
5095 /// the right sequence. e.g.
5096 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5098 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5099 SelectionDAG &DAG, DebugLoc dl) {
5100 EVT VT = SVOp->getValueType(0);
5101 SDValue V1 = SVOp->getOperand(0);
5102 SDValue V2 = SVOp->getOperand(1);
5103 unsigned NumElems = VT.getVectorNumElements();
5104 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5106 switch (VT.getSimpleVT().SimpleTy) {
5107 default: assert(false && "Unexpected!");
5108 case MVT::v4f32: NewVT = MVT::v2f64; break;
5109 case MVT::v4i32: NewVT = MVT::v2i64; break;
5110 case MVT::v8i16: NewVT = MVT::v4i32; break;
5111 case MVT::v16i8: NewVT = MVT::v4i32; break;
5114 int Scale = NumElems / NewWidth;
5115 SmallVector<int, 8> MaskVec;
5116 for (unsigned i = 0; i < NumElems; i += Scale) {
5118 for (int j = 0; j < Scale; ++j) {
5119 int EltIdx = SVOp->getMaskElt(i+j);
5123 StartIdx = EltIdx - (EltIdx % Scale);
5124 if (EltIdx != StartIdx + j)
5128 MaskVec.push_back(-1);
5130 MaskVec.push_back(StartIdx / Scale);
5133 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5134 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5135 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5138 /// getVZextMovL - Return a zero-extending vector move low node.
5140 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5141 SDValue SrcOp, SelectionDAG &DAG,
5142 const X86Subtarget *Subtarget, DebugLoc dl) {
5143 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5144 LoadSDNode *LD = NULL;
5145 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5146 LD = dyn_cast<LoadSDNode>(SrcOp);
5148 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5150 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5151 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5152 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5153 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5154 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5156 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5157 return DAG.getNode(ISD::BITCAST, dl, VT,
5158 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5159 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5167 return DAG.getNode(ISD::BITCAST, dl, VT,
5168 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5169 DAG.getNode(ISD::BITCAST, dl,
5173 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5176 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5177 SDValue V1 = SVOp->getOperand(0);
5178 SDValue V2 = SVOp->getOperand(1);
5179 DebugLoc dl = SVOp->getDebugLoc();
5180 EVT VT = SVOp->getValueType(0);
5182 SmallVector<std::pair<int, int>, 8> Locs;
5184 SmallVector<int, 8> Mask1(4U, -1);
5185 SmallVector<int, 8> PermMask;
5186 SVOp->getMask(PermMask);
5190 for (unsigned i = 0; i != 4; ++i) {
5191 int Idx = PermMask[i];
5193 Locs[i] = std::make_pair(-1, -1);
5195 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5197 Locs[i] = std::make_pair(0, NumLo);
5201 Locs[i] = std::make_pair(1, NumHi);
5203 Mask1[2+NumHi] = Idx;
5209 if (NumLo <= 2 && NumHi <= 2) {
5210 // If no more than two elements come from either vector. This can be
5211 // implemented with two shuffles. First shuffle gather the elements.
5212 // The second shuffle, which takes the first shuffle as both of its
5213 // vector operands, put the elements into the right order.
5214 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5216 SmallVector<int, 8> Mask2(4U, -1);
5218 for (unsigned i = 0; i != 4; ++i) {
5219 if (Locs[i].first == -1)
5222 unsigned Idx = (i < 2) ? 0 : 4;
5223 Idx += Locs[i].first * 2 + Locs[i].second;
5228 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5229 } else if (NumLo == 3 || NumHi == 3) {
5230 // Otherwise, we must have three elements from one vector, call it X, and
5231 // one element from the other, call it Y. First, use a shufps to build an
5232 // intermediate vector with the one element from Y and the element from X
5233 // that will be in the same half in the final destination (the indexes don't
5234 // matter). Then, use a shufps to build the final vector, taking the half
5235 // containing the element from Y from the intermediate, and the other half
5238 // Normalize it so the 3 elements come from V1.
5239 CommuteVectorShuffleMask(PermMask, VT);
5243 // Find the element from V2.
5245 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5246 int Val = PermMask[HiIndex];
5253 Mask1[0] = PermMask[HiIndex];
5255 Mask1[2] = PermMask[HiIndex^1];
5257 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5260 Mask1[0] = PermMask[0];
5261 Mask1[1] = PermMask[1];
5262 Mask1[2] = HiIndex & 1 ? 6 : 4;
5263 Mask1[3] = HiIndex & 1 ? 4 : 6;
5264 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5266 Mask1[0] = HiIndex & 1 ? 2 : 0;
5267 Mask1[1] = HiIndex & 1 ? 0 : 2;
5268 Mask1[2] = PermMask[2];
5269 Mask1[3] = PermMask[3];
5274 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5278 // Break it into (shuffle shuffle_hi, shuffle_lo).
5281 SmallVector<int,8> LoMask(4U, -1);
5282 SmallVector<int,8> HiMask(4U, -1);
5284 SmallVector<int,8> *MaskPtr = &LoMask;
5285 unsigned MaskIdx = 0;
5288 for (unsigned i = 0; i != 4; ++i) {
5295 int Idx = PermMask[i];
5297 Locs[i] = std::make_pair(-1, -1);
5298 } else if (Idx < 4) {
5299 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5300 (*MaskPtr)[LoIdx] = Idx;
5303 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5304 (*MaskPtr)[HiIdx] = Idx;
5309 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5310 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5311 SmallVector<int, 8> MaskOps;
5312 for (unsigned i = 0; i != 4; ++i) {
5313 if (Locs[i].first == -1) {
5314 MaskOps.push_back(-1);
5316 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5317 MaskOps.push_back(Idx);
5320 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5323 static bool MayFoldVectorLoad(SDValue V) {
5324 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5325 V = V.getOperand(0);
5326 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5327 V = V.getOperand(0);
5333 // FIXME: the version above should always be used. Since there's
5334 // a bug where several vector shuffles can't be folded because the
5335 // DAG is not updated during lowering and a node claims to have two
5336 // uses while it only has one, use this version, and let isel match
5337 // another instruction if the load really happens to have more than
5338 // one use. Remove this version after this bug get fixed.
5339 // rdar://8434668, PR8156
5340 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5341 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5342 V = V.getOperand(0);
5343 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5344 V = V.getOperand(0);
5345 if (ISD::isNormalLoad(V.getNode()))
5350 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5351 /// a vector extract, and if both can be later optimized into a single load.
5352 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5353 /// here because otherwise a target specific shuffle node is going to be
5354 /// emitted for this shuffle, and the optimization not done.
5355 /// FIXME: This is probably not the best approach, but fix the problem
5356 /// until the right path is decided.
5358 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5359 const TargetLowering &TLI) {
5360 EVT VT = V.getValueType();
5361 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5363 // Be sure that the vector shuffle is present in a pattern like this:
5364 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5368 SDNode *N = *V.getNode()->use_begin();
5369 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5372 SDValue EltNo = N->getOperand(1);
5373 if (!isa<ConstantSDNode>(EltNo))
5376 // If the bit convert changed the number of elements, it is unsafe
5377 // to examine the mask.
5378 bool HasShuffleIntoBitcast = false;
5379 if (V.getOpcode() == ISD::BITCAST) {
5380 EVT SrcVT = V.getOperand(0).getValueType();
5381 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5383 V = V.getOperand(0);
5384 HasShuffleIntoBitcast = true;
5387 // Select the input vector, guarding against out of range extract vector.
5388 unsigned NumElems = VT.getVectorNumElements();
5389 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5390 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5391 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5393 // Skip one more bit_convert if necessary
5394 if (V.getOpcode() == ISD::BITCAST)
5395 V = V.getOperand(0);
5397 if (ISD::isNormalLoad(V.getNode())) {
5398 // Is the original load suitable?
5399 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5401 // FIXME: avoid the multi-use bug that is preventing lots of
5402 // of foldings to be detected, this is still wrong of course, but
5403 // give the temporary desired behavior, and if it happens that
5404 // the load has real more uses, during isel it will not fold, and
5405 // will generate poor code.
5406 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5409 if (!HasShuffleIntoBitcast)
5412 // If there's a bitcast before the shuffle, check if the load type and
5413 // alignment is valid.
5414 unsigned Align = LN0->getAlignment();
5416 TLI.getTargetData()->getABITypeAlignment(
5417 VT.getTypeForEVT(*DAG.getContext()));
5419 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5427 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5428 EVT VT = Op.getValueType();
5430 // Canonizalize to v2f64.
5431 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5432 return DAG.getNode(ISD::BITCAST, dl, VT,
5433 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5438 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5440 SDValue V1 = Op.getOperand(0);
5441 SDValue V2 = Op.getOperand(1);
5442 EVT VT = Op.getValueType();
5444 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5446 if (HasSSE2 && VT == MVT::v2f64)
5447 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5450 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5454 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5455 SDValue V1 = Op.getOperand(0);
5456 SDValue V2 = Op.getOperand(1);
5457 EVT VT = Op.getValueType();
5459 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5460 "unsupported shuffle type");
5462 if (V2.getOpcode() == ISD::UNDEF)
5466 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5470 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5471 SDValue V1 = Op.getOperand(0);
5472 SDValue V2 = Op.getOperand(1);
5473 EVT VT = Op.getValueType();
5474 unsigned NumElems = VT.getVectorNumElements();
5476 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5477 // operand of these instructions is only memory, so check if there's a
5478 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5480 bool CanFoldLoad = false;
5482 // Trivial case, when V2 comes from a load.
5483 if (MayFoldVectorLoad(V2))
5486 // When V1 is a load, it can be folded later into a store in isel, example:
5487 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5489 // (MOVLPSmr addr:$src1, VR128:$src2)
5490 // So, recognize this potential and also use MOVLPS or MOVLPD
5491 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5494 // Both of them can't be memory operations though.
5495 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5496 CanFoldLoad = false;
5499 if (HasSSE2 && NumElems == 2)
5500 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5503 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5506 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5507 // movl and movlp will both match v2i64, but v2i64 is never matched by
5508 // movl earlier because we make it strict to avoid messing with the movlp load
5509 // folding logic (see the code above getMOVLP call). Match it here then,
5510 // this is horrible, but will stay like this until we move all shuffle
5511 // matching to x86 specific nodes. Note that for the 1st condition all
5512 // types are matched with movsd.
5513 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5514 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5516 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5519 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5521 // Invert the operand order and use SHUFPS to match it.
5522 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5523 X86::getShuffleSHUFImmediate(SVOp), DAG);
5526 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5527 switch(VT.getSimpleVT().SimpleTy) {
5528 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5529 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5531 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5533 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5534 case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5535 case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5536 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5537 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5539 llvm_unreachable("Unknown type for unpckl");
5544 static inline unsigned getUNPCKHOpcode(EVT VT) {
5545 switch(VT.getSimpleVT().SimpleTy) {
5546 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5547 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5548 case MVT::v4f32: return X86ISD::UNPCKHPS;
5549 case MVT::v2f64: return X86ISD::UNPCKHPD;
5550 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5551 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5553 llvm_unreachable("Unknown type for unpckh");
5559 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5560 const TargetLowering &TLI,
5561 const X86Subtarget *Subtarget) {
5562 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5563 EVT VT = Op.getValueType();
5564 DebugLoc dl = Op.getDebugLoc();
5565 SDValue V1 = Op.getOperand(0);
5566 SDValue V2 = Op.getOperand(1);
5568 if (isZeroShuffle(SVOp))
5569 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5571 // Handle splat operations
5572 if (SVOp->isSplat()) {
5573 // Special case, this is the only place now where it's
5574 // allowed to return a vector_shuffle operation without
5575 // using a target specific node, because *hopefully* it
5576 // will be optimized away by the dag combiner.
5577 if (VT.getVectorNumElements() <= 4 &&
5578 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5581 // Handle splats by matching through known masks
5582 if (VT.getVectorNumElements() <= 4)
5585 // Canonicalize all of the remaining to v4f32.
5586 return PromoteSplat(SVOp, DAG);
5589 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5591 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5592 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5593 if (NewOp.getNode())
5594 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5595 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5596 // FIXME: Figure out a cleaner way to do this.
5597 // Try to make use of movq to zero out the top part.
5598 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5599 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5600 if (NewOp.getNode()) {
5601 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5602 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5603 DAG, Subtarget, dl);
5605 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5606 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5607 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5608 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5609 DAG, Subtarget, dl);
5616 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5617 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5618 SDValue V1 = Op.getOperand(0);
5619 SDValue V2 = Op.getOperand(1);
5620 EVT VT = Op.getValueType();
5621 DebugLoc dl = Op.getDebugLoc();
5622 unsigned NumElems = VT.getVectorNumElements();
5623 bool isMMX = VT.getSizeInBits() == 64;
5624 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5625 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5626 bool V1IsSplat = false;
5627 bool V2IsSplat = false;
5628 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5629 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5630 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5631 MachineFunction &MF = DAG.getMachineFunction();
5632 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5634 // Shuffle operations on MMX not supported.
5638 // Vector shuffle lowering takes 3 steps:
5640 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5641 // narrowing and commutation of operands should be handled.
5642 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5644 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5645 // so the shuffle can be broken into other shuffles and the legalizer can
5646 // try the lowering again.
5648 // The general ideia is that no vector_shuffle operation should be left to
5649 // be matched during isel, all of them must be converted to a target specific
5652 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5653 // narrowing and commutation of operands should be handled. The actual code
5654 // doesn't include all of those, work in progress...
5655 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5656 if (NewOp.getNode())
5659 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5660 // unpckh_undef). Only use pshufd if speed is more important than size.
5661 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5662 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5663 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5664 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5665 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5666 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5668 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5669 RelaxedMayFoldVectorLoad(V1))
5670 return getMOVDDup(Op, dl, V1, DAG);
5672 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5673 return getMOVHighToLow(Op, dl, DAG);
5675 // Use to match splats
5676 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5677 (VT == MVT::v2f64 || VT == MVT::v2i64))
5678 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5680 if (X86::isPSHUFDMask(SVOp)) {
5681 // The actual implementation will match the mask in the if above and then
5682 // during isel it can match several different instructions, not only pshufd
5683 // as its name says, sad but true, emulate the behavior for now...
5684 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5685 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5687 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5689 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5690 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5692 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5693 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5696 if (VT == MVT::v4f32)
5697 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5701 // Check if this can be converted into a logical shift.
5702 bool isLeft = false;
5705 bool isShift = getSubtarget()->hasSSE2() &&
5706 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5707 if (isShift && ShVal.hasOneUse()) {
5708 // If the shifted value has multiple uses, it may be cheaper to use
5709 // v_set0 + movlhps or movhlps, etc.
5710 EVT EltVT = VT.getVectorElementType();
5711 ShAmt *= EltVT.getSizeInBits();
5712 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5715 if (X86::isMOVLMask(SVOp)) {
5718 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5719 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5720 if (!X86::isMOVLPMask(SVOp)) {
5721 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5722 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5724 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5725 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5729 // FIXME: fold these into legal mask.
5730 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5731 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5733 if (X86::isMOVHLPSMask(SVOp))
5734 return getMOVHighToLow(Op, dl, DAG);
5736 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5737 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5739 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5740 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5742 if (X86::isMOVLPMask(SVOp))
5743 return getMOVLP(Op, dl, DAG, HasSSE2);
5745 if (ShouldXformToMOVHLPS(SVOp) ||
5746 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5747 return CommuteVectorShuffle(SVOp, DAG);
5750 // No better options. Use a vshl / vsrl.
5751 EVT EltVT = VT.getVectorElementType();
5752 ShAmt *= EltVT.getSizeInBits();
5753 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5756 bool Commuted = false;
5757 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5758 // 1,1,1,1 -> v8i16 though.
5759 V1IsSplat = isSplatVector(V1.getNode());
5760 V2IsSplat = isSplatVector(V2.getNode());
5762 // Canonicalize the splat or undef, if present, to be on the RHS.
5763 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5764 Op = CommuteVectorShuffle(SVOp, DAG);
5765 SVOp = cast<ShuffleVectorSDNode>(Op);
5766 V1 = SVOp->getOperand(0);
5767 V2 = SVOp->getOperand(1);
5768 std::swap(V1IsSplat, V2IsSplat);
5769 std::swap(V1IsUndef, V2IsUndef);
5773 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5774 // Shuffling low element of v1 into undef, just return v1.
5777 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5778 // the instruction selector will not match, so get a canonical MOVL with
5779 // swapped operands to undo the commute.
5780 return getMOVL(DAG, dl, VT, V2, V1);
5783 if (X86::isUNPCKLMask(SVOp))
5784 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5785 dl, VT, V1, V2, DAG);
5787 if (X86::isUNPCKHMask(SVOp))
5788 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5791 // Normalize mask so all entries that point to V2 points to its first
5792 // element then try to match unpck{h|l} again. If match, return a
5793 // new vector_shuffle with the corrected mask.
5794 SDValue NewMask = NormalizeMask(SVOp, DAG);
5795 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5796 if (NSVOp != SVOp) {
5797 if (X86::isUNPCKLMask(NSVOp, true)) {
5799 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5806 // Commute is back and try unpck* again.
5807 // FIXME: this seems wrong.
5808 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5809 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5811 if (X86::isUNPCKLMask(NewSVOp))
5812 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5813 dl, VT, V2, V1, DAG);
5815 if (X86::isUNPCKHMask(NewSVOp))
5816 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5819 // Normalize the node to match x86 shuffle ops if needed
5820 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5821 return CommuteVectorShuffle(SVOp, DAG);
5823 // The checks below are all present in isShuffleMaskLegal, but they are
5824 // inlined here right now to enable us to directly emit target specific
5825 // nodes, and remove one by one until they don't return Op anymore.
5826 SmallVector<int, 16> M;
5829 if (isPALIGNRMask(M, VT, HasSSSE3))
5830 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5831 X86::getShufflePALIGNRImmediate(SVOp),
5834 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5835 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5836 if (VT == MVT::v2f64) {
5837 X86ISD::NodeType Opcode =
5838 getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5839 return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5841 if (VT == MVT::v2i64)
5842 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5845 if (isPSHUFHWMask(M, VT))
5846 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5847 X86::getShufflePSHUFHWImmediate(SVOp),
5850 if (isPSHUFLWMask(M, VT))
5851 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5852 X86::getShufflePSHUFLWImmediate(SVOp),
5855 if (isSHUFPMask(M, VT)) {
5856 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5857 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5858 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5860 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5861 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5865 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5866 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5867 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5868 dl, VT, V1, V1, DAG);
5869 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5870 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5871 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5873 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5874 if (VT == MVT::v8i16) {
5875 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5876 if (NewOp.getNode())
5880 if (VT == MVT::v16i8) {
5881 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5882 if (NewOp.getNode())
5886 // Handle all 4 wide cases with a number of shuffles.
5888 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5894 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5895 SelectionDAG &DAG) const {
5896 EVT VT = Op.getValueType();
5897 DebugLoc dl = Op.getDebugLoc();
5898 if (VT.getSizeInBits() == 8) {
5899 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5900 Op.getOperand(0), Op.getOperand(1));
5901 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5902 DAG.getValueType(VT));
5903 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5904 } else if (VT.getSizeInBits() == 16) {
5905 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5906 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5908 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5909 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5910 DAG.getNode(ISD::BITCAST, dl,
5914 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5915 Op.getOperand(0), Op.getOperand(1));
5916 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5917 DAG.getValueType(VT));
5918 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5919 } else if (VT == MVT::f32) {
5920 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5921 // the result back to FR32 register. It's only worth matching if the
5922 // result has a single use which is a store or a bitcast to i32. And in
5923 // the case of a store, it's not worth it if the index is a constant 0,
5924 // because a MOVSSmr can be used instead, which is smaller and faster.
5925 if (!Op.hasOneUse())
5927 SDNode *User = *Op.getNode()->use_begin();
5928 if ((User->getOpcode() != ISD::STORE ||
5929 (isa<ConstantSDNode>(Op.getOperand(1)) &&
5930 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5931 (User->getOpcode() != ISD::BITCAST ||
5932 User->getValueType(0) != MVT::i32))
5934 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5935 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5938 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5939 } else if (VT == MVT::i32) {
5940 // ExtractPS works with constant index.
5941 if (isa<ConstantSDNode>(Op.getOperand(1)))
5949 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5950 SelectionDAG &DAG) const {
5951 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5954 SDValue Vec = Op.getOperand(0);
5955 EVT VecVT = Vec.getValueType();
5957 // If this is a 256-bit vector result, first extract the 128-bit
5958 // vector and then extract from the 128-bit vector.
5959 if (VecVT.getSizeInBits() > 128) {
5960 DebugLoc dl = Op.getNode()->getDebugLoc();
5961 unsigned NumElems = VecVT.getVectorNumElements();
5962 SDValue Idx = Op.getOperand(1);
5964 if (!isa<ConstantSDNode>(Idx))
5967 unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
5968 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5970 // Get the 128-bit vector.
5971 bool Upper = IdxVal >= ExtractNumElems;
5972 Vec = Extract128BitVector(Vec, Idx, DAG, dl);
5975 SDValue ScaledIdx = Idx;
5977 ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
5978 DAG.getConstant(ExtractNumElems,
5979 Idx.getValueType()));
5980 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
5984 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
5986 if (Subtarget->hasSSE41()) {
5987 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5992 EVT VT = Op.getValueType();
5993 DebugLoc dl = Op.getDebugLoc();
5994 // TODO: handle v16i8.
5995 if (VT.getSizeInBits() == 16) {
5996 SDValue Vec = Op.getOperand(0);
5997 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5999 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6000 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6001 DAG.getNode(ISD::BITCAST, dl,
6004 // Transform it so it match pextrw which produces a 32-bit result.
6005 EVT EltVT = MVT::i32;
6006 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6007 Op.getOperand(0), Op.getOperand(1));
6008 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6009 DAG.getValueType(VT));
6010 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6011 } else if (VT.getSizeInBits() == 32) {
6012 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6016 // SHUFPS the element to the lowest double word, then movss.
6017 int Mask[4] = { Idx, -1, -1, -1 };
6018 EVT VVT = Op.getOperand(0).getValueType();
6019 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6020 DAG.getUNDEF(VVT), Mask);
6021 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6022 DAG.getIntPtrConstant(0));
6023 } else if (VT.getSizeInBits() == 64) {
6024 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6025 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6026 // to match extract_elt for f64.
6027 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6031 // UNPCKHPD the element to the lowest double word, then movsd.
6032 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6033 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6034 int Mask[2] = { 1, -1 };
6035 EVT VVT = Op.getOperand(0).getValueType();
6036 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6037 DAG.getUNDEF(VVT), Mask);
6038 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6039 DAG.getIntPtrConstant(0));
6046 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6047 SelectionDAG &DAG) const {
6048 EVT VT = Op.getValueType();
6049 EVT EltVT = VT.getVectorElementType();
6050 DebugLoc dl = Op.getDebugLoc();
6052 SDValue N0 = Op.getOperand(0);
6053 SDValue N1 = Op.getOperand(1);
6054 SDValue N2 = Op.getOperand(2);
6056 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6057 isa<ConstantSDNode>(N2)) {
6059 if (VT == MVT::v8i16)
6060 Opc = X86ISD::PINSRW;
6061 else if (VT == MVT::v16i8)
6062 Opc = X86ISD::PINSRB;
6064 Opc = X86ISD::PINSRB;
6066 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6068 if (N1.getValueType() != MVT::i32)
6069 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6070 if (N2.getValueType() != MVT::i32)
6071 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6072 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6073 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6074 // Bits [7:6] of the constant are the source select. This will always be
6075 // zero here. The DAG Combiner may combine an extract_elt index into these
6076 // bits. For example (insert (extract, 3), 2) could be matched by putting
6077 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6078 // Bits [5:4] of the constant are the destination select. This is the
6079 // value of the incoming immediate.
6080 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6081 // combine either bitwise AND or insert of float 0.0 to set these bits.
6082 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6083 // Create this as a scalar to vector..
6084 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6085 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6086 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6087 // PINSR* works with constant index.
6094 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6095 EVT VT = Op.getValueType();
6096 EVT EltVT = VT.getVectorElementType();
6098 DebugLoc dl = Op.getDebugLoc();
6099 SDValue N0 = Op.getOperand(0);
6100 SDValue N1 = Op.getOperand(1);
6101 SDValue N2 = Op.getOperand(2);
6103 // If this is a 256-bit vector result, first insert into a 128-bit
6104 // vector and then insert into the 256-bit vector.
6105 if (VT.getSizeInBits() > 128) {
6106 if (!isa<ConstantSDNode>(N2))
6109 // Get the 128-bit vector.
6110 unsigned NumElems = VT.getVectorNumElements();
6111 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6112 bool Upper = IdxVal >= NumElems / 2;
6114 SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6117 SDValue ScaledN2 = N2;
6119 ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6120 DAG.getConstant(NumElems /
6121 (VT.getSizeInBits() / 128),
6122 N2.getValueType()));
6123 Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6126 // Insert the 128-bit vector
6127 // FIXME: Why UNDEF?
6128 return Insert128BitVector(N0, Op, N2, DAG, dl);
6131 if (Subtarget->hasSSE41())
6132 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6134 if (EltVT == MVT::i8)
6137 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6138 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6139 // as its second argument.
6140 if (N1.getValueType() != MVT::i32)
6141 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6142 if (N2.getValueType() != MVT::i32)
6143 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6144 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6150 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6151 LLVMContext *Context = DAG.getContext();
6152 DebugLoc dl = Op.getDebugLoc();
6153 EVT OpVT = Op.getValueType();
6155 // If this is a 256-bit vector result, first insert into a 128-bit
6156 // vector and then insert into the 256-bit vector.
6157 if (OpVT.getSizeInBits() > 128) {
6158 // Insert into a 128-bit vector.
6159 EVT VT128 = EVT::getVectorVT(*Context,
6160 OpVT.getVectorElementType(),
6161 OpVT.getVectorNumElements() / 2);
6163 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6165 // Insert the 128-bit vector.
6166 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6167 DAG.getConstant(0, MVT::i32),
6171 if (Op.getValueType() == MVT::v1i64 &&
6172 Op.getOperand(0).getValueType() == MVT::i64)
6173 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6175 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6176 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6177 "Expected an SSE type!");
6178 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6179 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6182 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
6183 // a simple subregister reference or explicit instructions to grab
6184 // upper bits of a vector.
6186 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6187 if (Subtarget->hasAVX()) {
6188 DebugLoc dl = Op.getNode()->getDebugLoc();
6189 SDValue Vec = Op.getNode()->getOperand(0);
6190 SDValue Idx = Op.getNode()->getOperand(1);
6192 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6193 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6194 return Extract128BitVector(Vec, Idx, DAG, dl);
6200 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
6201 // simple superregister reference or explicit instructions to insert
6202 // the upper bits of a vector.
6204 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6205 if (Subtarget->hasAVX()) {
6206 DebugLoc dl = Op.getNode()->getDebugLoc();
6207 SDValue Vec = Op.getNode()->getOperand(0);
6208 SDValue SubVec = Op.getNode()->getOperand(1);
6209 SDValue Idx = Op.getNode()->getOperand(2);
6211 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6212 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6213 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6219 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6220 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6221 // one of the above mentioned nodes. It has to be wrapped because otherwise
6222 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6223 // be used to form addressing mode. These wrapped nodes will be selected
6226 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6227 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6229 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6231 unsigned char OpFlag = 0;
6232 unsigned WrapperKind = X86ISD::Wrapper;
6233 CodeModel::Model M = getTargetMachine().getCodeModel();
6235 if (Subtarget->isPICStyleRIPRel() &&
6236 (M == CodeModel::Small || M == CodeModel::Kernel))
6237 WrapperKind = X86ISD::WrapperRIP;
6238 else if (Subtarget->isPICStyleGOT())
6239 OpFlag = X86II::MO_GOTOFF;
6240 else if (Subtarget->isPICStyleStubPIC())
6241 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6243 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6245 CP->getOffset(), OpFlag);
6246 DebugLoc DL = CP->getDebugLoc();
6247 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6248 // With PIC, the address is actually $g + Offset.
6250 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6251 DAG.getNode(X86ISD::GlobalBaseReg,
6252 DebugLoc(), getPointerTy()),
6259 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6260 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6262 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6264 unsigned char OpFlag = 0;
6265 unsigned WrapperKind = X86ISD::Wrapper;
6266 CodeModel::Model M = getTargetMachine().getCodeModel();
6268 if (Subtarget->isPICStyleRIPRel() &&
6269 (M == CodeModel::Small || M == CodeModel::Kernel))
6270 WrapperKind = X86ISD::WrapperRIP;
6271 else if (Subtarget->isPICStyleGOT())
6272 OpFlag = X86II::MO_GOTOFF;
6273 else if (Subtarget->isPICStyleStubPIC())
6274 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6276 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6278 DebugLoc DL = JT->getDebugLoc();
6279 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6281 // With PIC, the address is actually $g + Offset.
6283 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6284 DAG.getNode(X86ISD::GlobalBaseReg,
6285 DebugLoc(), getPointerTy()),
6292 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6293 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6295 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6297 unsigned char OpFlag = 0;
6298 unsigned WrapperKind = X86ISD::Wrapper;
6299 CodeModel::Model M = getTargetMachine().getCodeModel();
6301 if (Subtarget->isPICStyleRIPRel() &&
6302 (M == CodeModel::Small || M == CodeModel::Kernel))
6303 WrapperKind = X86ISD::WrapperRIP;
6304 else if (Subtarget->isPICStyleGOT())
6305 OpFlag = X86II::MO_GOTOFF;
6306 else if (Subtarget->isPICStyleStubPIC())
6307 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6309 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6311 DebugLoc DL = Op.getDebugLoc();
6312 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6315 // With PIC, the address is actually $g + Offset.
6316 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6317 !Subtarget->is64Bit()) {
6318 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6319 DAG.getNode(X86ISD::GlobalBaseReg,
6320 DebugLoc(), getPointerTy()),
6328 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6329 // Create the TargetBlockAddressAddress node.
6330 unsigned char OpFlags =
6331 Subtarget->ClassifyBlockAddressReference();
6332 CodeModel::Model M = getTargetMachine().getCodeModel();
6333 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6334 DebugLoc dl = Op.getDebugLoc();
6335 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6336 /*isTarget=*/true, OpFlags);
6338 if (Subtarget->isPICStyleRIPRel() &&
6339 (M == CodeModel::Small || M == CodeModel::Kernel))
6340 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6342 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6344 // With PIC, the address is actually $g + Offset.
6345 if (isGlobalRelativeToPICBase(OpFlags)) {
6346 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6347 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6355 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6357 SelectionDAG &DAG) const {
6358 // Create the TargetGlobalAddress node, folding in the constant
6359 // offset if it is legal.
6360 unsigned char OpFlags =
6361 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6362 CodeModel::Model M = getTargetMachine().getCodeModel();
6364 if (OpFlags == X86II::MO_NO_FLAG &&
6365 X86::isOffsetSuitableForCodeModel(Offset, M)) {
6366 // A direct static reference to a global.
6367 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6370 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6373 if (Subtarget->isPICStyleRIPRel() &&
6374 (M == CodeModel::Small || M == CodeModel::Kernel))
6375 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6377 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6379 // With PIC, the address is actually $g + Offset.
6380 if (isGlobalRelativeToPICBase(OpFlags)) {
6381 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6382 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6386 // For globals that require a load from a stub to get the address, emit the
6388 if (isGlobalStubReference(OpFlags))
6389 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6390 MachinePointerInfo::getGOT(), false, false, 0);
6392 // If there was a non-zero offset that we didn't fold, create an explicit
6395 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6396 DAG.getConstant(Offset, getPointerTy()));
6402 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6403 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6404 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6405 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6409 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6410 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6411 unsigned char OperandFlags) {
6412 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6413 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6414 DebugLoc dl = GA->getDebugLoc();
6415 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6416 GA->getValueType(0),
6420 SDValue Ops[] = { Chain, TGA, *InFlag };
6421 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6423 SDValue Ops[] = { Chain, TGA };
6424 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6427 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6428 MFI->setAdjustsStack(true);
6430 SDValue Flag = Chain.getValue(1);
6431 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6434 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6436 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6439 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6440 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6441 DAG.getNode(X86ISD::GlobalBaseReg,
6442 DebugLoc(), PtrVT), InFlag);
6443 InFlag = Chain.getValue(1);
6445 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6448 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6450 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6452 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6453 X86::RAX, X86II::MO_TLSGD);
6456 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6457 // "local exec" model.
6458 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6459 const EVT PtrVT, TLSModel::Model model,
6461 DebugLoc dl = GA->getDebugLoc();
6463 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6464 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6465 is64Bit ? 257 : 256));
6467 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6468 DAG.getIntPtrConstant(0),
6469 MachinePointerInfo(Ptr), false, false, 0);
6471 unsigned char OperandFlags = 0;
6472 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6474 unsigned WrapperKind = X86ISD::Wrapper;
6475 if (model == TLSModel::LocalExec) {
6476 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6477 } else if (is64Bit) {
6478 assert(model == TLSModel::InitialExec);
6479 OperandFlags = X86II::MO_GOTTPOFF;
6480 WrapperKind = X86ISD::WrapperRIP;
6482 assert(model == TLSModel::InitialExec);
6483 OperandFlags = X86II::MO_INDNTPOFF;
6486 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6488 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6489 GA->getValueType(0),
6490 GA->getOffset(), OperandFlags);
6491 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6493 if (model == TLSModel::InitialExec)
6494 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6495 MachinePointerInfo::getGOT(), false, false, 0);
6497 // The address of the thread local variable is the add of the thread
6498 // pointer with the offset of the variable.
6499 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6503 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6505 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6506 const GlobalValue *GV = GA->getGlobal();
6508 if (Subtarget->isTargetELF()) {
6509 // TODO: implement the "local dynamic" model
6510 // TODO: implement the "initial exec"model for pic executables
6512 // If GV is an alias then use the aliasee for determining
6513 // thread-localness.
6514 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6515 GV = GA->resolveAliasedGlobal(false);
6517 TLSModel::Model model
6518 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6521 case TLSModel::GeneralDynamic:
6522 case TLSModel::LocalDynamic: // not implemented
6523 if (Subtarget->is64Bit())
6524 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6525 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6527 case TLSModel::InitialExec:
6528 case TLSModel::LocalExec:
6529 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6530 Subtarget->is64Bit());
6532 } else if (Subtarget->isTargetDarwin()) {
6533 // Darwin only has one model of TLS. Lower to that.
6534 unsigned char OpFlag = 0;
6535 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6536 X86ISD::WrapperRIP : X86ISD::Wrapper;
6538 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6540 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6541 !Subtarget->is64Bit();
6543 OpFlag = X86II::MO_TLVP_PIC_BASE;
6545 OpFlag = X86II::MO_TLVP;
6546 DebugLoc DL = Op.getDebugLoc();
6547 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6548 GA->getValueType(0),
6549 GA->getOffset(), OpFlag);
6550 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6552 // With PIC32, the address is actually $g + Offset.
6554 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6555 DAG.getNode(X86ISD::GlobalBaseReg,
6556 DebugLoc(), getPointerTy()),
6559 // Lowering the machine isd will make sure everything is in the right
6561 SDValue Chain = DAG.getEntryNode();
6562 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6563 SDValue Args[] = { Chain, Offset };
6564 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6566 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6567 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6568 MFI->setAdjustsStack(true);
6570 // And our return value (tls address) is in the standard call return value
6572 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6573 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6577 "TLS not implemented for this target.");
6579 llvm_unreachable("Unreachable");
6584 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6585 /// take a 2 x i32 value to shift plus a shift amount.
6586 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6587 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6588 EVT VT = Op.getValueType();
6589 unsigned VTBits = VT.getSizeInBits();
6590 DebugLoc dl = Op.getDebugLoc();
6591 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6592 SDValue ShOpLo = Op.getOperand(0);
6593 SDValue ShOpHi = Op.getOperand(1);
6594 SDValue ShAmt = Op.getOperand(2);
6595 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6596 DAG.getConstant(VTBits - 1, MVT::i8))
6597 : DAG.getConstant(0, VT);
6600 if (Op.getOpcode() == ISD::SHL_PARTS) {
6601 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6602 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6604 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6605 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6608 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6609 DAG.getConstant(VTBits, MVT::i8));
6610 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6611 AndNode, DAG.getConstant(0, MVT::i8));
6614 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6615 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6616 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6618 if (Op.getOpcode() == ISD::SHL_PARTS) {
6619 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6620 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6622 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6623 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6626 SDValue Ops[2] = { Lo, Hi };
6627 return DAG.getMergeValues(Ops, 2, dl);
6630 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6631 SelectionDAG &DAG) const {
6632 EVT SrcVT = Op.getOperand(0).getValueType();
6634 if (SrcVT.isVector())
6637 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6638 "Unknown SINT_TO_FP to lower!");
6640 // These are really Legal; return the operand so the caller accepts it as
6642 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6644 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6645 Subtarget->is64Bit()) {
6649 DebugLoc dl = Op.getDebugLoc();
6650 unsigned Size = SrcVT.getSizeInBits()/8;
6651 MachineFunction &MF = DAG.getMachineFunction();
6652 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6653 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6654 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6656 MachinePointerInfo::getFixedStack(SSFI),
6658 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6661 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6663 SelectionDAG &DAG) const {
6665 DebugLoc DL = Op.getDebugLoc();
6667 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6669 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6671 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6673 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6675 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6676 MachineMemOperand *MMO =
6677 DAG.getMachineFunction()
6678 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6679 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6681 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6682 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6684 Tys, Ops, array_lengthof(Ops),
6688 Chain = Result.getValue(1);
6689 SDValue InFlag = Result.getValue(2);
6691 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6692 // shouldn't be necessary except that RFP cannot be live across
6693 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6694 MachineFunction &MF = DAG.getMachineFunction();
6695 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6696 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6697 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6698 Tys = DAG.getVTList(MVT::Other);
6700 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6702 MachineMemOperand *MMO =
6703 DAG.getMachineFunction()
6704 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6705 MachineMemOperand::MOStore, SSFISize, SSFISize);
6707 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6708 Ops, array_lengthof(Ops),
6709 Op.getValueType(), MMO);
6710 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6711 MachinePointerInfo::getFixedStack(SSFI),
6718 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6719 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6720 SelectionDAG &DAG) const {
6721 // This algorithm is not obvious. Here it is in C code, more or less:
6723 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6724 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6725 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6727 // Copy ints to xmm registers.
6728 __m128i xh = _mm_cvtsi32_si128( hi );
6729 __m128i xl = _mm_cvtsi32_si128( lo );
6731 // Combine into low half of a single xmm register.
6732 __m128i x = _mm_unpacklo_epi32( xh, xl );
6736 // Merge in appropriate exponents to give the integer bits the right
6738 x = _mm_unpacklo_epi32( x, exp );
6740 // Subtract away the biases to deal with the IEEE-754 double precision
6742 d = _mm_sub_pd( (__m128d) x, bias );
6744 // All conversions up to here are exact. The correctly rounded result is
6745 // calculated using the current rounding mode using the following
6747 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6748 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6749 // store doesn't really need to be here (except
6750 // maybe to zero the other double)
6755 DebugLoc dl = Op.getDebugLoc();
6756 LLVMContext *Context = DAG.getContext();
6758 // Build some magic constants.
6759 std::vector<Constant*> CV0;
6760 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6761 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6762 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6763 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6764 Constant *C0 = ConstantVector::get(CV0);
6765 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6767 std::vector<Constant*> CV1;
6769 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6771 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6772 Constant *C1 = ConstantVector::get(CV1);
6773 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6775 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6776 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6778 DAG.getIntPtrConstant(1)));
6779 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6780 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6782 DAG.getIntPtrConstant(0)));
6783 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6784 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6785 MachinePointerInfo::getConstantPool(),
6787 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6788 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6789 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6790 MachinePointerInfo::getConstantPool(),
6792 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6794 // Add the halves; easiest way is to swap them into another reg first.
6795 int ShufMask[2] = { 1, -1 };
6796 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6797 DAG.getUNDEF(MVT::v2f64), ShufMask);
6798 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6799 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6800 DAG.getIntPtrConstant(0));
6803 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6804 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6805 SelectionDAG &DAG) const {
6806 DebugLoc dl = Op.getDebugLoc();
6807 // FP constant to bias correct the final result.
6808 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6811 // Load the 32-bit value into an XMM register.
6812 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6813 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6815 DAG.getIntPtrConstant(0)));
6817 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6818 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6819 DAG.getIntPtrConstant(0));
6821 // Or the load with the bias.
6822 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6823 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6824 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6826 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6827 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6828 MVT::v2f64, Bias)));
6829 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6830 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6831 DAG.getIntPtrConstant(0));
6833 // Subtract the bias.
6834 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6836 // Handle final rounding.
6837 EVT DestVT = Op.getValueType();
6839 if (DestVT.bitsLT(MVT::f64)) {
6840 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6841 DAG.getIntPtrConstant(0));
6842 } else if (DestVT.bitsGT(MVT::f64)) {
6843 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6846 // Handle final rounding.
6850 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6851 SelectionDAG &DAG) const {
6852 SDValue N0 = Op.getOperand(0);
6853 DebugLoc dl = Op.getDebugLoc();
6855 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6856 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6857 // the optimization here.
6858 if (DAG.SignBitIsZero(N0))
6859 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6861 EVT SrcVT = N0.getValueType();
6862 EVT DstVT = Op.getValueType();
6863 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6864 return LowerUINT_TO_FP_i64(Op, DAG);
6865 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6866 return LowerUINT_TO_FP_i32(Op, DAG);
6868 // Make a 64-bit buffer, and use it to build an FILD.
6869 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6870 if (SrcVT == MVT::i32) {
6871 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6872 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6873 getPointerTy(), StackSlot, WordOff);
6874 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6875 StackSlot, MachinePointerInfo(),
6877 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6878 OffsetSlot, MachinePointerInfo(),
6880 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6884 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6885 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6886 StackSlot, MachinePointerInfo(),
6888 // For i64 source, we need to add the appropriate power of 2 if the input
6889 // was negative. This is the same as the optimization in
6890 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6891 // we must be careful to do the computation in x87 extended precision, not
6892 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6893 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6894 MachineMemOperand *MMO =
6895 DAG.getMachineFunction()
6896 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6897 MachineMemOperand::MOLoad, 8, 8);
6899 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6900 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6901 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6904 APInt FF(32, 0x5F800000ULL);
6906 // Check whether the sign bit is set.
6907 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6908 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6911 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6912 SDValue FudgePtr = DAG.getConstantPool(
6913 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6916 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6917 SDValue Zero = DAG.getIntPtrConstant(0);
6918 SDValue Four = DAG.getIntPtrConstant(4);
6919 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6921 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6923 // Load the value out, extending it from f32 to f80.
6924 // FIXME: Avoid the extend by constructing the right constant pool?
6925 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
6926 FudgePtr, MachinePointerInfo::getConstantPool(),
6927 MVT::f32, false, false, 4);
6928 // Extend everything to 80 bits to force it to be done on x87.
6929 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6930 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6933 std::pair<SDValue,SDValue> X86TargetLowering::
6934 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6935 DebugLoc DL = Op.getDebugLoc();
6937 EVT DstTy = Op.getValueType();
6940 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6944 assert(DstTy.getSimpleVT() <= MVT::i64 &&
6945 DstTy.getSimpleVT() >= MVT::i16 &&
6946 "Unknown FP_TO_SINT to lower!");
6948 // These are really Legal.
6949 if (DstTy == MVT::i32 &&
6950 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6951 return std::make_pair(SDValue(), SDValue());
6952 if (Subtarget->is64Bit() &&
6953 DstTy == MVT::i64 &&
6954 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6955 return std::make_pair(SDValue(), SDValue());
6957 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6959 MachineFunction &MF = DAG.getMachineFunction();
6960 unsigned MemSize = DstTy.getSizeInBits()/8;
6961 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6962 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6967 switch (DstTy.getSimpleVT().SimpleTy) {
6968 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6969 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6970 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6971 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6974 SDValue Chain = DAG.getEntryNode();
6975 SDValue Value = Op.getOperand(0);
6976 EVT TheVT = Op.getOperand(0).getValueType();
6977 if (isScalarFPTypeInSSEReg(TheVT)) {
6978 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6979 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6980 MachinePointerInfo::getFixedStack(SSFI),
6982 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6984 Chain, StackSlot, DAG.getValueType(TheVT)
6987 MachineMemOperand *MMO =
6988 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6989 MachineMemOperand::MOLoad, MemSize, MemSize);
6990 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6992 Chain = Value.getValue(1);
6993 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6994 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6997 MachineMemOperand *MMO =
6998 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6999 MachineMemOperand::MOStore, MemSize, MemSize);
7001 // Build the FP_TO_INT*_IN_MEM
7002 SDValue Ops[] = { Chain, Value, StackSlot };
7003 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7004 Ops, 3, DstTy, MMO);
7006 return std::make_pair(FIST, StackSlot);
7009 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7010 SelectionDAG &DAG) const {
7011 if (Op.getValueType().isVector())
7014 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7015 SDValue FIST = Vals.first, StackSlot = Vals.second;
7016 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7017 if (FIST.getNode() == 0) return Op;
7020 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7021 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7024 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7025 SelectionDAG &DAG) const {
7026 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7027 SDValue FIST = Vals.first, StackSlot = Vals.second;
7028 assert(FIST.getNode() && "Unexpected failure");
7031 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7032 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7035 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7036 SelectionDAG &DAG) const {
7037 LLVMContext *Context = DAG.getContext();
7038 DebugLoc dl = Op.getDebugLoc();
7039 EVT VT = Op.getValueType();
7042 EltVT = VT.getVectorElementType();
7043 std::vector<Constant*> CV;
7044 if (EltVT == MVT::f64) {
7045 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7049 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7055 Constant *C = ConstantVector::get(CV);
7056 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7057 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7058 MachinePointerInfo::getConstantPool(),
7060 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7063 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7064 LLVMContext *Context = DAG.getContext();
7065 DebugLoc dl = Op.getDebugLoc();
7066 EVT VT = Op.getValueType();
7069 EltVT = VT.getVectorElementType();
7070 std::vector<Constant*> CV;
7071 if (EltVT == MVT::f64) {
7072 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7076 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7082 Constant *C = ConstantVector::get(CV);
7083 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7084 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7085 MachinePointerInfo::getConstantPool(),
7087 if (VT.isVector()) {
7088 return DAG.getNode(ISD::BITCAST, dl, VT,
7089 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7090 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7092 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7094 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7098 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7099 LLVMContext *Context = DAG.getContext();
7100 SDValue Op0 = Op.getOperand(0);
7101 SDValue Op1 = Op.getOperand(1);
7102 DebugLoc dl = Op.getDebugLoc();
7103 EVT VT = Op.getValueType();
7104 EVT SrcVT = Op1.getValueType();
7106 // If second operand is smaller, extend it first.
7107 if (SrcVT.bitsLT(VT)) {
7108 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7111 // And if it is bigger, shrink it first.
7112 if (SrcVT.bitsGT(VT)) {
7113 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7117 // At this point the operands and the result should have the same
7118 // type, and that won't be f80 since that is not custom lowered.
7120 // First get the sign bit of second operand.
7121 std::vector<Constant*> CV;
7122 if (SrcVT == MVT::f64) {
7123 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7124 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7126 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7127 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7128 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7129 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7131 Constant *C = ConstantVector::get(CV);
7132 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7133 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7134 MachinePointerInfo::getConstantPool(),
7136 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7138 // Shift sign bit right or left if the two operands have different types.
7139 if (SrcVT.bitsGT(VT)) {
7140 // Op0 is MVT::f32, Op1 is MVT::f64.
7141 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7142 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7143 DAG.getConstant(32, MVT::i32));
7144 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7145 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7146 DAG.getIntPtrConstant(0));
7149 // Clear first operand sign bit.
7151 if (VT == MVT::f64) {
7152 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7153 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7155 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7156 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7157 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7158 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7160 C = ConstantVector::get(CV);
7161 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7162 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7163 MachinePointerInfo::getConstantPool(),
7165 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7167 // Or the value with the sign bit.
7168 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7171 /// Emit nodes that will be selected as "test Op0,Op0", or something
7173 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7174 SelectionDAG &DAG) const {
7175 DebugLoc dl = Op.getDebugLoc();
7177 // CF and OF aren't always set the way we want. Determine which
7178 // of these we need.
7179 bool NeedCF = false;
7180 bool NeedOF = false;
7183 case X86::COND_A: case X86::COND_AE:
7184 case X86::COND_B: case X86::COND_BE:
7187 case X86::COND_G: case X86::COND_GE:
7188 case X86::COND_L: case X86::COND_LE:
7189 case X86::COND_O: case X86::COND_NO:
7194 // See if we can use the EFLAGS value from the operand instead of
7195 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7196 // we prove that the arithmetic won't overflow, we can't use OF or CF.
7197 if (Op.getResNo() != 0 || NeedOF || NeedCF)
7198 // Emit a CMP with 0, which is the TEST pattern.
7199 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7200 DAG.getConstant(0, Op.getValueType()));
7202 unsigned Opcode = 0;
7203 unsigned NumOperands = 0;
7204 switch (Op.getNode()->getOpcode()) {
7206 // Due to an isel shortcoming, be conservative if this add is likely to be
7207 // selected as part of a load-modify-store instruction. When the root node
7208 // in a match is a store, isel doesn't know how to remap non-chain non-flag
7209 // uses of other nodes in the match, such as the ADD in this case. This
7210 // leads to the ADD being left around and reselected, with the result being
7211 // two adds in the output. Alas, even if none our users are stores, that
7212 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
7213 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
7214 // climbing the DAG back to the root, and it doesn't seem to be worth the
7216 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7217 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7218 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7221 if (ConstantSDNode *C =
7222 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7223 // An add of one will be selected as an INC.
7224 if (C->getAPIntValue() == 1) {
7225 Opcode = X86ISD::INC;
7230 // An add of negative one (subtract of one) will be selected as a DEC.
7231 if (C->getAPIntValue().isAllOnesValue()) {
7232 Opcode = X86ISD::DEC;
7238 // Otherwise use a regular EFLAGS-setting add.
7239 Opcode = X86ISD::ADD;
7243 // If the primary and result isn't used, don't bother using X86ISD::AND,
7244 // because a TEST instruction will be better.
7245 bool NonFlagUse = false;
7246 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7247 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7249 unsigned UOpNo = UI.getOperandNo();
7250 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7251 // Look pass truncate.
7252 UOpNo = User->use_begin().getOperandNo();
7253 User = *User->use_begin();
7256 if (User->getOpcode() != ISD::BRCOND &&
7257 User->getOpcode() != ISD::SETCC &&
7258 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7271 // Due to the ISEL shortcoming noted above, be conservative if this op is
7272 // likely to be selected as part of a load-modify-store instruction.
7273 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7274 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7275 if (UI->getOpcode() == ISD::STORE)
7278 // Otherwise use a regular EFLAGS-setting instruction.
7279 switch (Op.getNode()->getOpcode()) {
7280 default: llvm_unreachable("unexpected operator!");
7281 case ISD::SUB: Opcode = X86ISD::SUB; break;
7282 case ISD::OR: Opcode = X86ISD::OR; break;
7283 case ISD::XOR: Opcode = X86ISD::XOR; break;
7284 case ISD::AND: Opcode = X86ISD::AND; break;
7296 return SDValue(Op.getNode(), 1);
7303 // Emit a CMP with 0, which is the TEST pattern.
7304 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7305 DAG.getConstant(0, Op.getValueType()));
7307 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7308 SmallVector<SDValue, 4> Ops;
7309 for (unsigned i = 0; i != NumOperands; ++i)
7310 Ops.push_back(Op.getOperand(i));
7312 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7313 DAG.ReplaceAllUsesWith(Op, New);
7314 return SDValue(New.getNode(), 1);
7317 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7319 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7320 SelectionDAG &DAG) const {
7321 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7322 if (C->getAPIntValue() == 0)
7323 return EmitTest(Op0, X86CC, DAG);
7325 DebugLoc dl = Op0.getDebugLoc();
7326 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7329 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7330 /// if it's possible.
7331 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7332 DebugLoc dl, SelectionDAG &DAG) const {
7333 SDValue Op0 = And.getOperand(0);
7334 SDValue Op1 = And.getOperand(1);
7335 if (Op0.getOpcode() == ISD::TRUNCATE)
7336 Op0 = Op0.getOperand(0);
7337 if (Op1.getOpcode() == ISD::TRUNCATE)
7338 Op1 = Op1.getOperand(0);
7341 if (Op1.getOpcode() == ISD::SHL)
7342 std::swap(Op0, Op1);
7343 if (Op0.getOpcode() == ISD::SHL) {
7344 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7345 if (And00C->getZExtValue() == 1) {
7346 // If we looked past a truncate, check that it's only truncating away
7348 unsigned BitWidth = Op0.getValueSizeInBits();
7349 unsigned AndBitWidth = And.getValueSizeInBits();
7350 if (BitWidth > AndBitWidth) {
7351 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7352 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7353 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7357 RHS = Op0.getOperand(1);
7359 } else if (Op1.getOpcode() == ISD::Constant) {
7360 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7361 SDValue AndLHS = Op0;
7362 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7363 LHS = AndLHS.getOperand(0);
7364 RHS = AndLHS.getOperand(1);
7368 if (LHS.getNode()) {
7369 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
7370 // instruction. Since the shift amount is in-range-or-undefined, we know
7371 // that doing a bittest on the i32 value is ok. We extend to i32 because
7372 // the encoding for the i16 version is larger than the i32 version.
7373 // Also promote i16 to i32 for performance / code size reason.
7374 if (LHS.getValueType() == MVT::i8 ||
7375 LHS.getValueType() == MVT::i16)
7376 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7378 // If the operand types disagree, extend the shift amount to match. Since
7379 // BT ignores high bits (like shifts) we can use anyextend.
7380 if (LHS.getValueType() != RHS.getValueType())
7381 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7383 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7384 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7385 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7386 DAG.getConstant(Cond, MVT::i8), BT);
7392 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7393 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7394 SDValue Op0 = Op.getOperand(0);
7395 SDValue Op1 = Op.getOperand(1);
7396 DebugLoc dl = Op.getDebugLoc();
7397 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7399 // Optimize to BT if possible.
7400 // Lower (X & (1 << N)) == 0 to BT(X, N).
7401 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7402 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7403 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7404 Op1.getOpcode() == ISD::Constant &&
7405 cast<ConstantSDNode>(Op1)->isNullValue() &&
7406 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7407 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7408 if (NewSetCC.getNode())
7412 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
7414 if (Op1.getOpcode() == ISD::Constant &&
7415 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7416 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7417 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7419 // If the input is a setcc, then reuse the input setcc or use a new one with
7420 // the inverted condition.
7421 if (Op0.getOpcode() == X86ISD::SETCC) {
7422 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7423 bool Invert = (CC == ISD::SETNE) ^
7424 cast<ConstantSDNode>(Op1)->isNullValue();
7425 if (!Invert) return Op0;
7427 CCode = X86::GetOppositeBranchCondition(CCode);
7428 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7429 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7433 bool isFP = Op1.getValueType().isFloatingPoint();
7434 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7435 if (X86CC == X86::COND_INVALID)
7438 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7439 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7440 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7443 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7445 SDValue Op0 = Op.getOperand(0);
7446 SDValue Op1 = Op.getOperand(1);
7447 SDValue CC = Op.getOperand(2);
7448 EVT VT = Op.getValueType();
7449 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7450 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7451 DebugLoc dl = Op.getDebugLoc();
7455 EVT VT0 = Op0.getValueType();
7456 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7457 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7460 switch (SetCCOpcode) {
7463 case ISD::SETEQ: SSECC = 0; break;
7465 case ISD::SETGT: Swap = true; // Fallthrough
7467 case ISD::SETOLT: SSECC = 1; break;
7469 case ISD::SETGE: Swap = true; // Fallthrough
7471 case ISD::SETOLE: SSECC = 2; break;
7472 case ISD::SETUO: SSECC = 3; break;
7474 case ISD::SETNE: SSECC = 4; break;
7475 case ISD::SETULE: Swap = true;
7476 case ISD::SETUGE: SSECC = 5; break;
7477 case ISD::SETULT: Swap = true;
7478 case ISD::SETUGT: SSECC = 6; break;
7479 case ISD::SETO: SSECC = 7; break;
7482 std::swap(Op0, Op1);
7484 // In the two special cases we can't handle, emit two comparisons.
7486 if (SetCCOpcode == ISD::SETUEQ) {
7488 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7489 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7490 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7492 else if (SetCCOpcode == ISD::SETONE) {
7494 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7495 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7496 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7498 llvm_unreachable("Illegal FP comparison");
7500 // Handle all other FP comparisons here.
7501 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7504 // We are handling one of the integer comparisons here. Since SSE only has
7505 // GT and EQ comparisons for integer, swapping operands and multiple
7506 // operations may be required for some comparisons.
7507 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7508 bool Swap = false, Invert = false, FlipSigns = false;
7510 switch (VT.getSimpleVT().SimpleTy) {
7512 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7513 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7514 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7515 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7518 switch (SetCCOpcode) {
7520 case ISD::SETNE: Invert = true;
7521 case ISD::SETEQ: Opc = EQOpc; break;
7522 case ISD::SETLT: Swap = true;
7523 case ISD::SETGT: Opc = GTOpc; break;
7524 case ISD::SETGE: Swap = true;
7525 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7526 case ISD::SETULT: Swap = true;
7527 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7528 case ISD::SETUGE: Swap = true;
7529 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7532 std::swap(Op0, Op1);
7534 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7535 // bits of the inputs before performing those operations.
7537 EVT EltVT = VT.getVectorElementType();
7538 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7540 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7541 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7543 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7544 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7547 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7549 // If the logical-not of the result is required, perform that now.
7551 Result = DAG.getNOT(dl, Result, VT);
7556 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7557 static bool isX86LogicalCmp(SDValue Op) {
7558 unsigned Opc = Op.getNode()->getOpcode();
7559 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7561 if (Op.getResNo() == 1 &&
7562 (Opc == X86ISD::ADD ||
7563 Opc == X86ISD::SUB ||
7564 Opc == X86ISD::ADC ||
7565 Opc == X86ISD::SBB ||
7566 Opc == X86ISD::SMUL ||
7567 Opc == X86ISD::UMUL ||
7568 Opc == X86ISD::INC ||
7569 Opc == X86ISD::DEC ||
7570 Opc == X86ISD::OR ||
7571 Opc == X86ISD::XOR ||
7572 Opc == X86ISD::AND))
7575 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7581 static bool isZero(SDValue V) {
7582 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7583 return C && C->isNullValue();
7586 static bool isAllOnes(SDValue V) {
7587 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7588 return C && C->isAllOnesValue();
7591 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7592 bool addTest = true;
7593 SDValue Cond = Op.getOperand(0);
7594 SDValue Op1 = Op.getOperand(1);
7595 SDValue Op2 = Op.getOperand(2);
7596 DebugLoc DL = Op.getDebugLoc();
7599 if (Cond.getOpcode() == ISD::SETCC) {
7600 SDValue NewCond = LowerSETCC(Cond, DAG);
7601 if (NewCond.getNode())
7605 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7606 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7607 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7608 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7609 if (Cond.getOpcode() == X86ISD::SETCC &&
7610 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7611 isZero(Cond.getOperand(1).getOperand(1))) {
7612 SDValue Cmp = Cond.getOperand(1);
7614 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7616 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7617 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7618 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7620 SDValue CmpOp0 = Cmp.getOperand(0);
7621 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7622 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7624 SDValue Res = // Res = 0 or -1.
7625 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7626 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7628 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7629 Res = DAG.getNOT(DL, Res, Res.getValueType());
7631 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7632 if (N2C == 0 || !N2C->isNullValue())
7633 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7638 // Look past (and (setcc_carry (cmp ...)), 1).
7639 if (Cond.getOpcode() == ISD::AND &&
7640 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7641 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7642 if (C && C->getAPIntValue() == 1)
7643 Cond = Cond.getOperand(0);
7646 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7647 // setting operand in place of the X86ISD::SETCC.
7648 if (Cond.getOpcode() == X86ISD::SETCC ||
7649 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7650 CC = Cond.getOperand(0);
7652 SDValue Cmp = Cond.getOperand(1);
7653 unsigned Opc = Cmp.getOpcode();
7654 EVT VT = Op.getValueType();
7656 bool IllegalFPCMov = false;
7657 if (VT.isFloatingPoint() && !VT.isVector() &&
7658 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7659 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7661 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7662 Opc == X86ISD::BT) { // FIXME
7669 // Look pass the truncate.
7670 if (Cond.getOpcode() == ISD::TRUNCATE)
7671 Cond = Cond.getOperand(0);
7673 // We know the result of AND is compared against zero. Try to match
7675 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7676 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7677 if (NewSetCC.getNode()) {
7678 CC = NewSetCC.getOperand(0);
7679 Cond = NewSetCC.getOperand(1);
7686 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7687 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7690 // a < b ? -1 : 0 -> RES = ~setcc_carry
7691 // a < b ? 0 : -1 -> RES = setcc_carry
7692 // a >= b ? -1 : 0 -> RES = setcc_carry
7693 // a >= b ? 0 : -1 -> RES = ~setcc_carry
7694 if (Cond.getOpcode() == X86ISD::CMP) {
7695 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7697 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7698 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7699 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7700 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7701 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7702 return DAG.getNOT(DL, Res, Res.getValueType());
7707 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7708 // condition is true.
7709 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7710 SDValue Ops[] = { Op2, Op1, CC, Cond };
7711 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7714 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7715 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7716 // from the AND / OR.
7717 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7718 Opc = Op.getOpcode();
7719 if (Opc != ISD::OR && Opc != ISD::AND)
7721 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7722 Op.getOperand(0).hasOneUse() &&
7723 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7724 Op.getOperand(1).hasOneUse());
7727 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7728 // 1 and that the SETCC node has a single use.
7729 static bool isXor1OfSetCC(SDValue Op) {
7730 if (Op.getOpcode() != ISD::XOR)
7732 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7733 if (N1C && N1C->getAPIntValue() == 1) {
7734 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7735 Op.getOperand(0).hasOneUse();
7740 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7741 bool addTest = true;
7742 SDValue Chain = Op.getOperand(0);
7743 SDValue Cond = Op.getOperand(1);
7744 SDValue Dest = Op.getOperand(2);
7745 DebugLoc dl = Op.getDebugLoc();
7748 if (Cond.getOpcode() == ISD::SETCC) {
7749 SDValue NewCond = LowerSETCC(Cond, DAG);
7750 if (NewCond.getNode())
7754 // FIXME: LowerXALUO doesn't handle these!!
7755 else if (Cond.getOpcode() == X86ISD::ADD ||
7756 Cond.getOpcode() == X86ISD::SUB ||
7757 Cond.getOpcode() == X86ISD::SMUL ||
7758 Cond.getOpcode() == X86ISD::UMUL)
7759 Cond = LowerXALUO(Cond, DAG);
7762 // Look pass (and (setcc_carry (cmp ...)), 1).
7763 if (Cond.getOpcode() == ISD::AND &&
7764 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7765 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7766 if (C && C->getAPIntValue() == 1)
7767 Cond = Cond.getOperand(0);
7770 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7771 // setting operand in place of the X86ISD::SETCC.
7772 if (Cond.getOpcode() == X86ISD::SETCC ||
7773 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7774 CC = Cond.getOperand(0);
7776 SDValue Cmp = Cond.getOperand(1);
7777 unsigned Opc = Cmp.getOpcode();
7778 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7779 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7783 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7787 // These can only come from an arithmetic instruction with overflow,
7788 // e.g. SADDO, UADDO.
7789 Cond = Cond.getNode()->getOperand(1);
7796 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7797 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7798 if (CondOpc == ISD::OR) {
7799 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7800 // two branches instead of an explicit OR instruction with a
7802 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7803 isX86LogicalCmp(Cmp)) {
7804 CC = Cond.getOperand(0).getOperand(0);
7805 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7806 Chain, Dest, CC, Cmp);
7807 CC = Cond.getOperand(1).getOperand(0);
7811 } else { // ISD::AND
7812 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7813 // two branches instead of an explicit AND instruction with a
7814 // separate test. However, we only do this if this block doesn't
7815 // have a fall-through edge, because this requires an explicit
7816 // jmp when the condition is false.
7817 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7818 isX86LogicalCmp(Cmp) &&
7819 Op.getNode()->hasOneUse()) {
7820 X86::CondCode CCode =
7821 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7822 CCode = X86::GetOppositeBranchCondition(CCode);
7823 CC = DAG.getConstant(CCode, MVT::i8);
7824 SDNode *User = *Op.getNode()->use_begin();
7825 // Look for an unconditional branch following this conditional branch.
7826 // We need this because we need to reverse the successors in order
7827 // to implement FCMP_OEQ.
7828 if (User->getOpcode() == ISD::BR) {
7829 SDValue FalseBB = User->getOperand(1);
7831 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7832 assert(NewBR == User);
7836 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7837 Chain, Dest, CC, Cmp);
7838 X86::CondCode CCode =
7839 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7840 CCode = X86::GetOppositeBranchCondition(CCode);
7841 CC = DAG.getConstant(CCode, MVT::i8);
7847 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7848 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7849 // It should be transformed during dag combiner except when the condition
7850 // is set by a arithmetics with overflow node.
7851 X86::CondCode CCode =
7852 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7853 CCode = X86::GetOppositeBranchCondition(CCode);
7854 CC = DAG.getConstant(CCode, MVT::i8);
7855 Cond = Cond.getOperand(0).getOperand(1);
7861 // Look pass the truncate.
7862 if (Cond.getOpcode() == ISD::TRUNCATE)
7863 Cond = Cond.getOperand(0);
7865 // We know the result of AND is compared against zero. Try to match
7867 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7868 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7869 if (NewSetCC.getNode()) {
7870 CC = NewSetCC.getOperand(0);
7871 Cond = NewSetCC.getOperand(1);
7878 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7879 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7881 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7882 Chain, Dest, CC, Cond);
7886 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7887 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7888 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7889 // that the guard pages used by the OS virtual memory manager are allocated in
7890 // correct sequence.
7892 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7893 SelectionDAG &DAG) const {
7894 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7895 "This should be used only on Windows targets");
7896 DebugLoc dl = Op.getDebugLoc();
7899 SDValue Chain = Op.getOperand(0);
7900 SDValue Size = Op.getOperand(1);
7901 // FIXME: Ensure alignment here
7905 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7907 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7908 Flag = Chain.getValue(1);
7910 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7912 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7913 Flag = Chain.getValue(1);
7915 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7917 SDValue Ops1[2] = { Chain.getValue(0), Chain };
7918 return DAG.getMergeValues(Ops1, 2, dl);
7921 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7922 MachineFunction &MF = DAG.getMachineFunction();
7923 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7925 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7926 DebugLoc DL = Op.getDebugLoc();
7928 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7929 // vastart just stores the address of the VarArgsFrameIndex slot into the
7930 // memory location argument.
7931 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7933 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7934 MachinePointerInfo(SV), false, false, 0);
7938 // gp_offset (0 - 6 * 8)
7939 // fp_offset (48 - 48 + 8 * 16)
7940 // overflow_arg_area (point to parameters coming in memory).
7942 SmallVector<SDValue, 8> MemOps;
7943 SDValue FIN = Op.getOperand(1);
7945 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7946 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7948 FIN, MachinePointerInfo(SV), false, false, 0);
7949 MemOps.push_back(Store);
7952 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7953 FIN, DAG.getIntPtrConstant(4));
7954 Store = DAG.getStore(Op.getOperand(0), DL,
7955 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7957 FIN, MachinePointerInfo(SV, 4), false, false, 0);
7958 MemOps.push_back(Store);
7960 // Store ptr to overflow_arg_area
7961 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7962 FIN, DAG.getIntPtrConstant(4));
7963 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7965 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7966 MachinePointerInfo(SV, 8),
7968 MemOps.push_back(Store);
7970 // Store ptr to reg_save_area.
7971 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7972 FIN, DAG.getIntPtrConstant(8));
7973 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7975 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7976 MachinePointerInfo(SV, 16), false, false, 0);
7977 MemOps.push_back(Store);
7978 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7979 &MemOps[0], MemOps.size());
7982 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7983 assert(Subtarget->is64Bit() &&
7984 "LowerVAARG only handles 64-bit va_arg!");
7985 assert((Subtarget->isTargetLinux() ||
7986 Subtarget->isTargetDarwin()) &&
7987 "Unhandled target in LowerVAARG");
7988 assert(Op.getNode()->getNumOperands() == 4);
7989 SDValue Chain = Op.getOperand(0);
7990 SDValue SrcPtr = Op.getOperand(1);
7991 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7992 unsigned Align = Op.getConstantOperandVal(3);
7993 DebugLoc dl = Op.getDebugLoc();
7995 EVT ArgVT = Op.getNode()->getValueType(0);
7996 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7997 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8000 // Decide which area this value should be read from.
8001 // TODO: Implement the AMD64 ABI in its entirety. This simple
8002 // selection mechanism works only for the basic types.
8003 if (ArgVT == MVT::f80) {
8004 llvm_unreachable("va_arg for f80 not yet implemented");
8005 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8006 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
8007 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8008 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
8010 llvm_unreachable("Unhandled argument type in LowerVAARG");
8014 // Sanity Check: Make sure using fp_offset makes sense.
8015 assert(!UseSoftFloat &&
8016 !(DAG.getMachineFunction()
8017 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8018 Subtarget->hasXMM());
8021 // Insert VAARG_64 node into the DAG
8022 // VAARG_64 returns two values: Variable Argument Address, Chain
8023 SmallVector<SDValue, 11> InstOps;
8024 InstOps.push_back(Chain);
8025 InstOps.push_back(SrcPtr);
8026 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8027 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8028 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8029 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8030 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8031 VTs, &InstOps[0], InstOps.size(),
8033 MachinePointerInfo(SV),
8038 Chain = VAARG.getValue(1);
8040 // Load the next argument and return it
8041 return DAG.getLoad(ArgVT, dl,
8044 MachinePointerInfo(),
8048 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8049 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8050 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8051 SDValue Chain = Op.getOperand(0);
8052 SDValue DstPtr = Op.getOperand(1);
8053 SDValue SrcPtr = Op.getOperand(2);
8054 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8055 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8056 DebugLoc DL = Op.getDebugLoc();
8058 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8059 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8061 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8065 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8066 DebugLoc dl = Op.getDebugLoc();
8067 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8069 default: return SDValue(); // Don't custom lower most intrinsics.
8070 // Comparison intrinsics.
8071 case Intrinsic::x86_sse_comieq_ss:
8072 case Intrinsic::x86_sse_comilt_ss:
8073 case Intrinsic::x86_sse_comile_ss:
8074 case Intrinsic::x86_sse_comigt_ss:
8075 case Intrinsic::x86_sse_comige_ss:
8076 case Intrinsic::x86_sse_comineq_ss:
8077 case Intrinsic::x86_sse_ucomieq_ss:
8078 case Intrinsic::x86_sse_ucomilt_ss:
8079 case Intrinsic::x86_sse_ucomile_ss:
8080 case Intrinsic::x86_sse_ucomigt_ss:
8081 case Intrinsic::x86_sse_ucomige_ss:
8082 case Intrinsic::x86_sse_ucomineq_ss:
8083 case Intrinsic::x86_sse2_comieq_sd:
8084 case Intrinsic::x86_sse2_comilt_sd:
8085 case Intrinsic::x86_sse2_comile_sd:
8086 case Intrinsic::x86_sse2_comigt_sd:
8087 case Intrinsic::x86_sse2_comige_sd:
8088 case Intrinsic::x86_sse2_comineq_sd:
8089 case Intrinsic::x86_sse2_ucomieq_sd:
8090 case Intrinsic::x86_sse2_ucomilt_sd:
8091 case Intrinsic::x86_sse2_ucomile_sd:
8092 case Intrinsic::x86_sse2_ucomigt_sd:
8093 case Intrinsic::x86_sse2_ucomige_sd:
8094 case Intrinsic::x86_sse2_ucomineq_sd: {
8096 ISD::CondCode CC = ISD::SETCC_INVALID;
8099 case Intrinsic::x86_sse_comieq_ss:
8100 case Intrinsic::x86_sse2_comieq_sd:
8104 case Intrinsic::x86_sse_comilt_ss:
8105 case Intrinsic::x86_sse2_comilt_sd:
8109 case Intrinsic::x86_sse_comile_ss:
8110 case Intrinsic::x86_sse2_comile_sd:
8114 case Intrinsic::x86_sse_comigt_ss:
8115 case Intrinsic::x86_sse2_comigt_sd:
8119 case Intrinsic::x86_sse_comige_ss:
8120 case Intrinsic::x86_sse2_comige_sd:
8124 case Intrinsic::x86_sse_comineq_ss:
8125 case Intrinsic::x86_sse2_comineq_sd:
8129 case Intrinsic::x86_sse_ucomieq_ss:
8130 case Intrinsic::x86_sse2_ucomieq_sd:
8131 Opc = X86ISD::UCOMI;
8134 case Intrinsic::x86_sse_ucomilt_ss:
8135 case Intrinsic::x86_sse2_ucomilt_sd:
8136 Opc = X86ISD::UCOMI;
8139 case Intrinsic::x86_sse_ucomile_ss:
8140 case Intrinsic::x86_sse2_ucomile_sd:
8141 Opc = X86ISD::UCOMI;
8144 case Intrinsic::x86_sse_ucomigt_ss:
8145 case Intrinsic::x86_sse2_ucomigt_sd:
8146 Opc = X86ISD::UCOMI;
8149 case Intrinsic::x86_sse_ucomige_ss:
8150 case Intrinsic::x86_sse2_ucomige_sd:
8151 Opc = X86ISD::UCOMI;
8154 case Intrinsic::x86_sse_ucomineq_ss:
8155 case Intrinsic::x86_sse2_ucomineq_sd:
8156 Opc = X86ISD::UCOMI;
8161 SDValue LHS = Op.getOperand(1);
8162 SDValue RHS = Op.getOperand(2);
8163 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8164 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8165 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8166 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8167 DAG.getConstant(X86CC, MVT::i8), Cond);
8168 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8170 // ptest and testp intrinsics. The intrinsic these come from are designed to
8171 // return an integer value, not just an instruction so lower it to the ptest
8172 // or testp pattern and a setcc for the result.
8173 case Intrinsic::x86_sse41_ptestz:
8174 case Intrinsic::x86_sse41_ptestc:
8175 case Intrinsic::x86_sse41_ptestnzc:
8176 case Intrinsic::x86_avx_ptestz_256:
8177 case Intrinsic::x86_avx_ptestc_256:
8178 case Intrinsic::x86_avx_ptestnzc_256:
8179 case Intrinsic::x86_avx_vtestz_ps:
8180 case Intrinsic::x86_avx_vtestc_ps:
8181 case Intrinsic::x86_avx_vtestnzc_ps:
8182 case Intrinsic::x86_avx_vtestz_pd:
8183 case Intrinsic::x86_avx_vtestc_pd:
8184 case Intrinsic::x86_avx_vtestnzc_pd:
8185 case Intrinsic::x86_avx_vtestz_ps_256:
8186 case Intrinsic::x86_avx_vtestc_ps_256:
8187 case Intrinsic::x86_avx_vtestnzc_ps_256:
8188 case Intrinsic::x86_avx_vtestz_pd_256:
8189 case Intrinsic::x86_avx_vtestc_pd_256:
8190 case Intrinsic::x86_avx_vtestnzc_pd_256: {
8191 bool IsTestPacked = false;
8194 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8195 case Intrinsic::x86_avx_vtestz_ps:
8196 case Intrinsic::x86_avx_vtestz_pd:
8197 case Intrinsic::x86_avx_vtestz_ps_256:
8198 case Intrinsic::x86_avx_vtestz_pd_256:
8199 IsTestPacked = true; // Fallthrough
8200 case Intrinsic::x86_sse41_ptestz:
8201 case Intrinsic::x86_avx_ptestz_256:
8203 X86CC = X86::COND_E;
8205 case Intrinsic::x86_avx_vtestc_ps:
8206 case Intrinsic::x86_avx_vtestc_pd:
8207 case Intrinsic::x86_avx_vtestc_ps_256:
8208 case Intrinsic::x86_avx_vtestc_pd_256:
8209 IsTestPacked = true; // Fallthrough
8210 case Intrinsic::x86_sse41_ptestc:
8211 case Intrinsic::x86_avx_ptestc_256:
8213 X86CC = X86::COND_B;
8215 case Intrinsic::x86_avx_vtestnzc_ps:
8216 case Intrinsic::x86_avx_vtestnzc_pd:
8217 case Intrinsic::x86_avx_vtestnzc_ps_256:
8218 case Intrinsic::x86_avx_vtestnzc_pd_256:
8219 IsTestPacked = true; // Fallthrough
8220 case Intrinsic::x86_sse41_ptestnzc:
8221 case Intrinsic::x86_avx_ptestnzc_256:
8223 X86CC = X86::COND_A;
8227 SDValue LHS = Op.getOperand(1);
8228 SDValue RHS = Op.getOperand(2);
8229 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8230 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8231 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8232 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8233 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8236 // Fix vector shift instructions where the last operand is a non-immediate
8238 case Intrinsic::x86_sse2_pslli_w:
8239 case Intrinsic::x86_sse2_pslli_d:
8240 case Intrinsic::x86_sse2_pslli_q:
8241 case Intrinsic::x86_sse2_psrli_w:
8242 case Intrinsic::x86_sse2_psrli_d:
8243 case Intrinsic::x86_sse2_psrli_q:
8244 case Intrinsic::x86_sse2_psrai_w:
8245 case Intrinsic::x86_sse2_psrai_d:
8246 case Intrinsic::x86_mmx_pslli_w:
8247 case Intrinsic::x86_mmx_pslli_d:
8248 case Intrinsic::x86_mmx_pslli_q:
8249 case Intrinsic::x86_mmx_psrli_w:
8250 case Intrinsic::x86_mmx_psrli_d:
8251 case Intrinsic::x86_mmx_psrli_q:
8252 case Intrinsic::x86_mmx_psrai_w:
8253 case Intrinsic::x86_mmx_psrai_d: {
8254 SDValue ShAmt = Op.getOperand(2);
8255 if (isa<ConstantSDNode>(ShAmt))
8258 unsigned NewIntNo = 0;
8259 EVT ShAmtVT = MVT::v4i32;
8261 case Intrinsic::x86_sse2_pslli_w:
8262 NewIntNo = Intrinsic::x86_sse2_psll_w;
8264 case Intrinsic::x86_sse2_pslli_d:
8265 NewIntNo = Intrinsic::x86_sse2_psll_d;
8267 case Intrinsic::x86_sse2_pslli_q:
8268 NewIntNo = Intrinsic::x86_sse2_psll_q;
8270 case Intrinsic::x86_sse2_psrli_w:
8271 NewIntNo = Intrinsic::x86_sse2_psrl_w;
8273 case Intrinsic::x86_sse2_psrli_d:
8274 NewIntNo = Intrinsic::x86_sse2_psrl_d;
8276 case Intrinsic::x86_sse2_psrli_q:
8277 NewIntNo = Intrinsic::x86_sse2_psrl_q;
8279 case Intrinsic::x86_sse2_psrai_w:
8280 NewIntNo = Intrinsic::x86_sse2_psra_w;
8282 case Intrinsic::x86_sse2_psrai_d:
8283 NewIntNo = Intrinsic::x86_sse2_psra_d;
8286 ShAmtVT = MVT::v2i32;
8288 case Intrinsic::x86_mmx_pslli_w:
8289 NewIntNo = Intrinsic::x86_mmx_psll_w;
8291 case Intrinsic::x86_mmx_pslli_d:
8292 NewIntNo = Intrinsic::x86_mmx_psll_d;
8294 case Intrinsic::x86_mmx_pslli_q:
8295 NewIntNo = Intrinsic::x86_mmx_psll_q;
8297 case Intrinsic::x86_mmx_psrli_w:
8298 NewIntNo = Intrinsic::x86_mmx_psrl_w;
8300 case Intrinsic::x86_mmx_psrli_d:
8301 NewIntNo = Intrinsic::x86_mmx_psrl_d;
8303 case Intrinsic::x86_mmx_psrli_q:
8304 NewIntNo = Intrinsic::x86_mmx_psrl_q;
8306 case Intrinsic::x86_mmx_psrai_w:
8307 NewIntNo = Intrinsic::x86_mmx_psra_w;
8309 case Intrinsic::x86_mmx_psrai_d:
8310 NewIntNo = Intrinsic::x86_mmx_psra_d;
8312 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8318 // The vector shift intrinsics with scalars uses 32b shift amounts but
8319 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8323 ShOps[1] = DAG.getConstant(0, MVT::i32);
8324 if (ShAmtVT == MVT::v4i32) {
8325 ShOps[2] = DAG.getUNDEF(MVT::i32);
8326 ShOps[3] = DAG.getUNDEF(MVT::i32);
8327 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8329 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8330 // FIXME this must be lowered to get rid of the invalid type.
8333 EVT VT = Op.getValueType();
8334 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8335 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8336 DAG.getConstant(NewIntNo, MVT::i32),
8337 Op.getOperand(1), ShAmt);
8342 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8343 SelectionDAG &DAG) const {
8344 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8345 MFI->setReturnAddressIsTaken(true);
8347 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8348 DebugLoc dl = Op.getDebugLoc();
8351 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8353 DAG.getConstant(TD->getPointerSize(),
8354 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8355 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8356 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8358 MachinePointerInfo(), false, false, 0);
8361 // Just load the return address.
8362 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8363 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8364 RetAddrFI, MachinePointerInfo(), false, false, 0);
8367 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8368 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8369 MFI->setFrameAddressIsTaken(true);
8371 EVT VT = Op.getValueType();
8372 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
8373 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8374 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8375 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8377 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8378 MachinePointerInfo(),
8383 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8384 SelectionDAG &DAG) const {
8385 return DAG.getIntPtrConstant(2*TD->getPointerSize());
8388 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8389 MachineFunction &MF = DAG.getMachineFunction();
8390 SDValue Chain = Op.getOperand(0);
8391 SDValue Offset = Op.getOperand(1);
8392 SDValue Handler = Op.getOperand(2);
8393 DebugLoc dl = Op.getDebugLoc();
8395 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8396 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8398 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8400 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8401 DAG.getIntPtrConstant(TD->getPointerSize()));
8402 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8403 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8405 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8406 MF.getRegInfo().addLiveOut(StoreAddrReg);
8408 return DAG.getNode(X86ISD::EH_RETURN, dl,
8410 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8413 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8414 SelectionDAG &DAG) const {
8415 SDValue Root = Op.getOperand(0);
8416 SDValue Trmp = Op.getOperand(1); // trampoline
8417 SDValue FPtr = Op.getOperand(2); // nested function
8418 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8419 DebugLoc dl = Op.getDebugLoc();
8421 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8423 if (Subtarget->is64Bit()) {
8424 SDValue OutChains[6];
8426 // Large code-model.
8427 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8428 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8430 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8431 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8433 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8435 // Load the pointer to the nested function into R11.
8436 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8437 SDValue Addr = Trmp;
8438 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8439 Addr, MachinePointerInfo(TrmpAddr),
8442 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8443 DAG.getConstant(2, MVT::i64));
8444 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8445 MachinePointerInfo(TrmpAddr, 2),
8448 // Load the 'nest' parameter value into R10.
8449 // R10 is specified in X86CallingConv.td
8450 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8451 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8452 DAG.getConstant(10, MVT::i64));
8453 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8454 Addr, MachinePointerInfo(TrmpAddr, 10),
8457 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8458 DAG.getConstant(12, MVT::i64));
8459 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8460 MachinePointerInfo(TrmpAddr, 12),
8463 // Jump to the nested function.
8464 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8465 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8466 DAG.getConstant(20, MVT::i64));
8467 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8468 Addr, MachinePointerInfo(TrmpAddr, 20),
8471 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8472 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8473 DAG.getConstant(22, MVT::i64));
8474 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8475 MachinePointerInfo(TrmpAddr, 22),
8479 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8480 return DAG.getMergeValues(Ops, 2, dl);
8482 const Function *Func =
8483 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8484 CallingConv::ID CC = Func->getCallingConv();
8489 llvm_unreachable("Unsupported calling convention");
8490 case CallingConv::C:
8491 case CallingConv::X86_StdCall: {
8492 // Pass 'nest' parameter in ECX.
8493 // Must be kept in sync with X86CallingConv.td
8496 // Check that ECX wasn't needed by an 'inreg' parameter.
8497 const FunctionType *FTy = Func->getFunctionType();
8498 const AttrListPtr &Attrs = Func->getAttributes();
8500 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8501 unsigned InRegCount = 0;
8504 for (FunctionType::param_iterator I = FTy->param_begin(),
8505 E = FTy->param_end(); I != E; ++I, ++Idx)
8506 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8507 // FIXME: should only count parameters that are lowered to integers.
8508 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8510 if (InRegCount > 2) {
8511 report_fatal_error("Nest register in use - reduce number of inreg"
8517 case CallingConv::X86_FastCall:
8518 case CallingConv::X86_ThisCall:
8519 case CallingConv::Fast:
8520 // Pass 'nest' parameter in EAX.
8521 // Must be kept in sync with X86CallingConv.td
8526 SDValue OutChains[4];
8529 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8530 DAG.getConstant(10, MVT::i32));
8531 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8533 // This is storing the opcode for MOV32ri.
8534 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8535 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8536 OutChains[0] = DAG.getStore(Root, dl,
8537 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8538 Trmp, MachinePointerInfo(TrmpAddr),
8541 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8542 DAG.getConstant(1, MVT::i32));
8543 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8544 MachinePointerInfo(TrmpAddr, 1),
8547 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8548 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8549 DAG.getConstant(5, MVT::i32));
8550 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8551 MachinePointerInfo(TrmpAddr, 5),
8554 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8555 DAG.getConstant(6, MVT::i32));
8556 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8557 MachinePointerInfo(TrmpAddr, 6),
8561 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8562 return DAG.getMergeValues(Ops, 2, dl);
8566 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8567 SelectionDAG &DAG) const {
8569 The rounding mode is in bits 11:10 of FPSR, and has the following
8576 FLT_ROUNDS, on the other hand, expects the following:
8583 To perform the conversion, we do:
8584 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8587 MachineFunction &MF = DAG.getMachineFunction();
8588 const TargetMachine &TM = MF.getTarget();
8589 const TargetFrameLowering &TFI = *TM.getFrameLowering();
8590 unsigned StackAlignment = TFI.getStackAlignment();
8591 EVT VT = Op.getValueType();
8592 DebugLoc DL = Op.getDebugLoc();
8594 // Save FP Control Word to stack slot
8595 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8596 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8599 MachineMemOperand *MMO =
8600 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8601 MachineMemOperand::MOStore, 2, 2);
8603 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8604 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8605 DAG.getVTList(MVT::Other),
8606 Ops, 2, MVT::i16, MMO);
8608 // Load FP Control Word from stack slot
8609 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8610 MachinePointerInfo(), false, false, 0);
8612 // Transform as necessary
8614 DAG.getNode(ISD::SRL, DL, MVT::i16,
8615 DAG.getNode(ISD::AND, DL, MVT::i16,
8616 CWD, DAG.getConstant(0x800, MVT::i16)),
8617 DAG.getConstant(11, MVT::i8));
8619 DAG.getNode(ISD::SRL, DL, MVT::i16,
8620 DAG.getNode(ISD::AND, DL, MVT::i16,
8621 CWD, DAG.getConstant(0x400, MVT::i16)),
8622 DAG.getConstant(9, MVT::i8));
8625 DAG.getNode(ISD::AND, DL, MVT::i16,
8626 DAG.getNode(ISD::ADD, DL, MVT::i16,
8627 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8628 DAG.getConstant(1, MVT::i16)),
8629 DAG.getConstant(3, MVT::i16));
8632 return DAG.getNode((VT.getSizeInBits() < 16 ?
8633 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8636 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8637 EVT VT = Op.getValueType();
8639 unsigned NumBits = VT.getSizeInBits();
8640 DebugLoc dl = Op.getDebugLoc();
8642 Op = Op.getOperand(0);
8643 if (VT == MVT::i8) {
8644 // Zero extend to i32 since there is not an i8 bsr.
8646 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8649 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8650 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8651 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8653 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8656 DAG.getConstant(NumBits+NumBits-1, OpVT),
8657 DAG.getConstant(X86::COND_E, MVT::i8),
8660 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8662 // Finally xor with NumBits-1.
8663 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8666 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8670 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8671 EVT VT = Op.getValueType();
8673 unsigned NumBits = VT.getSizeInBits();
8674 DebugLoc dl = Op.getDebugLoc();
8676 Op = Op.getOperand(0);
8677 if (VT == MVT::i8) {
8679 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8682 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8683 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8684 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8686 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8689 DAG.getConstant(NumBits, OpVT),
8690 DAG.getConstant(X86::COND_E, MVT::i8),
8693 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8696 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8700 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8701 EVT VT = Op.getValueType();
8702 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8703 DebugLoc dl = Op.getDebugLoc();
8705 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8706 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8707 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8708 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8709 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8711 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8712 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8713 // return AloBlo + AloBhi + AhiBlo;
8715 SDValue A = Op.getOperand(0);
8716 SDValue B = Op.getOperand(1);
8718 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8719 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8720 A, DAG.getConstant(32, MVT::i32));
8721 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8722 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8723 B, DAG.getConstant(32, MVT::i32));
8724 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8725 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8727 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8728 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8730 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8731 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8733 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8734 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8735 AloBhi, DAG.getConstant(32, MVT::i32));
8736 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8737 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8738 AhiBlo, DAG.getConstant(32, MVT::i32));
8739 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8740 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8744 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8745 EVT VT = Op.getValueType();
8746 DebugLoc dl = Op.getDebugLoc();
8747 SDValue R = Op.getOperand(0);
8749 LLVMContext *Context = DAG.getContext();
8751 assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8753 if (VT == MVT::v4i32) {
8754 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8755 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8756 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8758 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8760 std::vector<Constant*> CV(4, CI);
8761 Constant *C = ConstantVector::get(CV);
8762 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8763 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8764 MachinePointerInfo::getConstantPool(),
8767 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8768 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8769 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8770 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8772 if (VT == MVT::v16i8) {
8774 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8775 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8776 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8778 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8779 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8781 std::vector<Constant*> CVM1(16, CM1);
8782 std::vector<Constant*> CVM2(16, CM2);
8783 Constant *C = ConstantVector::get(CVM1);
8784 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8785 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8786 MachinePointerInfo::getConstantPool(),
8789 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8790 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8791 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8792 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8793 DAG.getConstant(4, MVT::i32));
8794 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8796 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8798 C = ConstantVector::get(CVM2);
8799 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8800 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8801 MachinePointerInfo::getConstantPool(),
8804 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8805 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8806 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8807 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8808 DAG.getConstant(2, MVT::i32));
8809 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8811 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8813 // return pblendv(r, r+r, a);
8814 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8815 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8821 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8822 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8823 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8824 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8825 // has only one use.
8826 SDNode *N = Op.getNode();
8827 SDValue LHS = N->getOperand(0);
8828 SDValue RHS = N->getOperand(1);
8829 unsigned BaseOp = 0;
8831 DebugLoc DL = Op.getDebugLoc();
8832 switch (Op.getOpcode()) {
8833 default: llvm_unreachable("Unknown ovf instruction!");
8835 // A subtract of one will be selected as a INC. Note that INC doesn't
8836 // set CF, so we can't do this for UADDO.
8837 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8839 BaseOp = X86ISD::INC;
8843 BaseOp = X86ISD::ADD;
8847 BaseOp = X86ISD::ADD;
8851 // A subtract of one will be selected as a DEC. Note that DEC doesn't
8852 // set CF, so we can't do this for USUBO.
8853 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8855 BaseOp = X86ISD::DEC;
8859 BaseOp = X86ISD::SUB;
8863 BaseOp = X86ISD::SUB;
8867 BaseOp = X86ISD::SMUL;
8870 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8871 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8873 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8876 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8877 DAG.getConstant(X86::COND_O, MVT::i32),
8878 SDValue(Sum.getNode(), 2));
8880 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8885 // Also sets EFLAGS.
8886 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8887 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8890 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8891 DAG.getConstant(Cond, MVT::i32),
8892 SDValue(Sum.getNode(), 1));
8894 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8898 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8899 DebugLoc dl = Op.getDebugLoc();
8901 if (!Subtarget->hasSSE2()) {
8902 SDValue Chain = Op.getOperand(0);
8903 SDValue Zero = DAG.getConstant(0,
8904 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8906 DAG.getRegister(X86::ESP, MVT::i32), // Base
8907 DAG.getTargetConstant(1, MVT::i8), // Scale
8908 DAG.getRegister(0, MVT::i32), // Index
8909 DAG.getTargetConstant(0, MVT::i32), // Disp
8910 DAG.getRegister(0, MVT::i32), // Segment.
8915 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8916 array_lengthof(Ops));
8917 return SDValue(Res, 0);
8920 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8922 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8924 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8925 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8926 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8927 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8929 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8930 if (!Op1 && !Op2 && !Op3 && Op4)
8931 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8933 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8934 if (Op1 && !Op2 && !Op3 && !Op4)
8935 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8937 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8939 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8942 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8943 EVT T = Op.getValueType();
8944 DebugLoc DL = Op.getDebugLoc();
8947 switch(T.getSimpleVT().SimpleTy) {
8949 assert(false && "Invalid value type!");
8950 case MVT::i8: Reg = X86::AL; size = 1; break;
8951 case MVT::i16: Reg = X86::AX; size = 2; break;
8952 case MVT::i32: Reg = X86::EAX; size = 4; break;
8954 assert(Subtarget->is64Bit() && "Node not type legal!");
8955 Reg = X86::RAX; size = 8;
8958 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8959 Op.getOperand(2), SDValue());
8960 SDValue Ops[] = { cpIn.getValue(0),
8963 DAG.getTargetConstant(size, MVT::i8),
8965 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8966 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8967 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8970 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8974 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8975 SelectionDAG &DAG) const {
8976 assert(Subtarget->is64Bit() && "Result not type legalized?");
8977 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8978 SDValue TheChain = Op.getOperand(0);
8979 DebugLoc dl = Op.getDebugLoc();
8980 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8981 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8982 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8984 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8985 DAG.getConstant(32, MVT::i8));
8987 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8990 return DAG.getMergeValues(Ops, 2, dl);
8993 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
8994 SelectionDAG &DAG) const {
8995 EVT SrcVT = Op.getOperand(0).getValueType();
8996 EVT DstVT = Op.getValueType();
8997 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8998 Subtarget->hasMMX() && "Unexpected custom BITCAST");
8999 assert((DstVT == MVT::i64 ||
9000 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9001 "Unexpected custom BITCAST");
9002 // i64 <=> MMX conversions are Legal.
9003 if (SrcVT==MVT::i64 && DstVT.isVector())
9005 if (DstVT==MVT::i64 && SrcVT.isVector())
9007 // MMX <=> MMX conversions are Legal.
9008 if (SrcVT.isVector() && DstVT.isVector())
9010 // All other conversions need to be expanded.
9014 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9015 SDNode *Node = Op.getNode();
9016 DebugLoc dl = Node->getDebugLoc();
9017 EVT T = Node->getValueType(0);
9018 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9019 DAG.getConstant(0, T), Node->getOperand(2));
9020 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9021 cast<AtomicSDNode>(Node)->getMemoryVT(),
9022 Node->getOperand(0),
9023 Node->getOperand(1), negOp,
9024 cast<AtomicSDNode>(Node)->getSrcValue(),
9025 cast<AtomicSDNode>(Node)->getAlignment());
9028 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9029 EVT VT = Op.getNode()->getValueType(0);
9031 // Let legalize expand this if it isn't a legal type yet.
9032 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9035 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9038 bool ExtraOp = false;
9039 switch (Op.getOpcode()) {
9040 default: assert(0 && "Invalid code");
9041 case ISD::ADDC: Opc = X86ISD::ADD; break;
9042 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9043 case ISD::SUBC: Opc = X86ISD::SUB; break;
9044 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9048 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9050 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9051 Op.getOperand(1), Op.getOperand(2));
9054 /// LowerOperation - Provide custom lowering hooks for some operations.
9056 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9057 switch (Op.getOpcode()) {
9058 default: llvm_unreachable("Should not custom lower this!");
9059 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
9060 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
9061 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
9062 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
9063 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
9064 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
9065 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9066 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9067 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
9068 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
9069 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
9070 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9071 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9072 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9073 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
9074 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
9075 case ISD::SHL_PARTS:
9076 case ISD::SRA_PARTS:
9077 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
9078 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
9079 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
9080 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
9081 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
9082 case ISD::FABS: return LowerFABS(Op, DAG);
9083 case ISD::FNEG: return LowerFNEG(Op, DAG);
9084 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
9085 case ISD::SETCC: return LowerSETCC(Op, DAG);
9086 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
9087 case ISD::SELECT: return LowerSELECT(Op, DAG);
9088 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
9089 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
9090 case ISD::VASTART: return LowerVASTART(Op, DAG);
9091 case ISD::VAARG: return LowerVAARG(Op, DAG);
9092 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
9093 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9094 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9095 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9096 case ISD::FRAME_TO_ARGS_OFFSET:
9097 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9098 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9099 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
9100 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
9101 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9102 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
9103 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
9104 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
9105 case ISD::SHL: return LowerSHL(Op, DAG);
9111 case ISD::UMULO: return LowerXALUO(Op, DAG);
9112 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
9113 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
9117 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9121 void X86TargetLowering::
9122 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9123 SelectionDAG &DAG, unsigned NewOp) const {
9124 EVT T = Node->getValueType(0);
9125 DebugLoc dl = Node->getDebugLoc();
9126 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9128 SDValue Chain = Node->getOperand(0);
9129 SDValue In1 = Node->getOperand(1);
9130 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9131 Node->getOperand(2), DAG.getIntPtrConstant(0));
9132 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9133 Node->getOperand(2), DAG.getIntPtrConstant(1));
9134 SDValue Ops[] = { Chain, In1, In2L, In2H };
9135 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9137 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9138 cast<MemSDNode>(Node)->getMemOperand());
9139 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9140 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9141 Results.push_back(Result.getValue(2));
9144 /// ReplaceNodeResults - Replace a node with an illegal result type
9145 /// with a new node built out of custom code.
9146 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9147 SmallVectorImpl<SDValue>&Results,
9148 SelectionDAG &DAG) const {
9149 DebugLoc dl = N->getDebugLoc();
9150 switch (N->getOpcode()) {
9152 assert(false && "Do not know how to custom type legalize this operation!");
9158 // We don't want to expand or promote these.
9160 case ISD::FP_TO_SINT: {
9161 std::pair<SDValue,SDValue> Vals =
9162 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9163 SDValue FIST = Vals.first, StackSlot = Vals.second;
9164 if (FIST.getNode() != 0) {
9165 EVT VT = N->getValueType(0);
9166 // Return a load from the stack slot.
9167 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9168 MachinePointerInfo(), false, false, 0));
9172 case ISD::READCYCLECOUNTER: {
9173 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9174 SDValue TheChain = N->getOperand(0);
9175 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9176 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9178 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9180 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9181 SDValue Ops[] = { eax, edx };
9182 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9183 Results.push_back(edx.getValue(1));
9186 case ISD::ATOMIC_CMP_SWAP: {
9187 EVT T = N->getValueType(0);
9188 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9189 SDValue cpInL, cpInH;
9190 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9191 DAG.getConstant(0, MVT::i32));
9192 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9193 DAG.getConstant(1, MVT::i32));
9194 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9195 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9197 SDValue swapInL, swapInH;
9198 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9199 DAG.getConstant(0, MVT::i32));
9200 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9201 DAG.getConstant(1, MVT::i32));
9202 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9204 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9205 swapInL.getValue(1));
9206 SDValue Ops[] = { swapInH.getValue(0),
9208 swapInH.getValue(1) };
9209 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9210 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9211 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9213 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9214 MVT::i32, Result.getValue(1));
9215 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9216 MVT::i32, cpOutL.getValue(2));
9217 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9218 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9219 Results.push_back(cpOutH.getValue(1));
9222 case ISD::ATOMIC_LOAD_ADD:
9223 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9225 case ISD::ATOMIC_LOAD_AND:
9226 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9228 case ISD::ATOMIC_LOAD_NAND:
9229 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9231 case ISD::ATOMIC_LOAD_OR:
9232 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9234 case ISD::ATOMIC_LOAD_SUB:
9235 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9237 case ISD::ATOMIC_LOAD_XOR:
9238 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9240 case ISD::ATOMIC_SWAP:
9241 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9246 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9248 default: return NULL;
9249 case X86ISD::BSF: return "X86ISD::BSF";
9250 case X86ISD::BSR: return "X86ISD::BSR";
9251 case X86ISD::SHLD: return "X86ISD::SHLD";
9252 case X86ISD::SHRD: return "X86ISD::SHRD";
9253 case X86ISD::FAND: return "X86ISD::FAND";
9254 case X86ISD::FOR: return "X86ISD::FOR";
9255 case X86ISD::FXOR: return "X86ISD::FXOR";
9256 case X86ISD::FSRL: return "X86ISD::FSRL";
9257 case X86ISD::FILD: return "X86ISD::FILD";
9258 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
9259 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9260 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9261 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9262 case X86ISD::FLD: return "X86ISD::FLD";
9263 case X86ISD::FST: return "X86ISD::FST";
9264 case X86ISD::CALL: return "X86ISD::CALL";
9265 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
9266 case X86ISD::BT: return "X86ISD::BT";
9267 case X86ISD::CMP: return "X86ISD::CMP";
9268 case X86ISD::COMI: return "X86ISD::COMI";
9269 case X86ISD::UCOMI: return "X86ISD::UCOMI";
9270 case X86ISD::SETCC: return "X86ISD::SETCC";
9271 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
9272 case X86ISD::CMOV: return "X86ISD::CMOV";
9273 case X86ISD::BRCOND: return "X86ISD::BRCOND";
9274 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
9275 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
9276 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
9277 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
9278 case X86ISD::Wrapper: return "X86ISD::Wrapper";
9279 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
9280 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
9281 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
9282 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
9283 case X86ISD::PINSRB: return "X86ISD::PINSRB";
9284 case X86ISD::PINSRW: return "X86ISD::PINSRW";
9285 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
9286 case X86ISD::PANDN: return "X86ISD::PANDN";
9287 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
9288 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
9289 case X86ISD::PSIGND: return "X86ISD::PSIGND";
9290 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB";
9291 case X86ISD::FMAX: return "X86ISD::FMAX";
9292 case X86ISD::FMIN: return "X86ISD::FMIN";
9293 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
9294 case X86ISD::FRCP: return "X86ISD::FRCP";
9295 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
9296 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
9297 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
9298 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
9299 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
9300 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
9301 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
9302 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
9303 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
9304 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
9305 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
9306 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
9307 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
9308 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
9309 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
9310 case X86ISD::VSHL: return "X86ISD::VSHL";
9311 case X86ISD::VSRL: return "X86ISD::VSRL";
9312 case X86ISD::CMPPD: return "X86ISD::CMPPD";
9313 case X86ISD::CMPPS: return "X86ISD::CMPPS";
9314 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
9315 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
9316 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
9317 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
9318 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
9319 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
9320 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
9321 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
9322 case X86ISD::ADD: return "X86ISD::ADD";
9323 case X86ISD::SUB: return "X86ISD::SUB";
9324 case X86ISD::ADC: return "X86ISD::ADC";
9325 case X86ISD::SBB: return "X86ISD::SBB";
9326 case X86ISD::SMUL: return "X86ISD::SMUL";
9327 case X86ISD::UMUL: return "X86ISD::UMUL";
9328 case X86ISD::INC: return "X86ISD::INC";
9329 case X86ISD::DEC: return "X86ISD::DEC";
9330 case X86ISD::OR: return "X86ISD::OR";
9331 case X86ISD::XOR: return "X86ISD::XOR";
9332 case X86ISD::AND: return "X86ISD::AND";
9333 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
9334 case X86ISD::PTEST: return "X86ISD::PTEST";
9335 case X86ISD::TESTP: return "X86ISD::TESTP";
9336 case X86ISD::PALIGN: return "X86ISD::PALIGN";
9337 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
9338 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
9339 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
9340 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
9341 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
9342 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
9343 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
9344 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
9345 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
9346 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
9347 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
9348 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
9349 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
9350 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
9351 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
9352 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
9353 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
9354 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
9355 case X86ISD::MOVSD: return "X86ISD::MOVSD";
9356 case X86ISD::MOVSS: return "X86ISD::MOVSS";
9357 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
9358 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
9359 case X86ISD::VUNPCKLPS: return "X86ISD::VUNPCKLPS";
9360 case X86ISD::VUNPCKLPD: return "X86ISD::VUNPCKLPD";
9361 case X86ISD::VUNPCKLPSY: return "X86ISD::VUNPCKLPSY";
9362 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
9363 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
9364 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
9365 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
9366 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
9367 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
9368 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
9369 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
9370 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
9371 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
9372 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
9373 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9374 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
9375 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
9379 // isLegalAddressingMode - Return true if the addressing mode represented
9380 // by AM is legal for this target, for a load/store of the specified type.
9381 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9382 const Type *Ty) const {
9383 // X86 supports extremely general addressing modes.
9384 CodeModel::Model M = getTargetMachine().getCodeModel();
9385 Reloc::Model R = getTargetMachine().getRelocationModel();
9387 // X86 allows a sign-extended 32-bit immediate field as a displacement.
9388 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9393 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9395 // If a reference to this global requires an extra load, we can't fold it.
9396 if (isGlobalStubReference(GVFlags))
9399 // If BaseGV requires a register for the PIC base, we cannot also have a
9400 // BaseReg specified.
9401 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9404 // If lower 4G is not available, then we must use rip-relative addressing.
9405 if ((M != CodeModel::Small || R != Reloc::Static) &&
9406 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9416 // These scales always work.
9421 // These scales are formed with basereg+scalereg. Only accept if there is
9426 default: // Other stuff never works.
9434 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9435 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9437 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9438 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9439 if (NumBits1 <= NumBits2)
9444 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9445 if (!VT1.isInteger() || !VT2.isInteger())
9447 unsigned NumBits1 = VT1.getSizeInBits();
9448 unsigned NumBits2 = VT2.getSizeInBits();
9449 if (NumBits1 <= NumBits2)
9454 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9455 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9456 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9459 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9460 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9461 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9464 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9465 // i16 instructions are longer (0x66 prefix) and potentially slower.
9466 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9469 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9470 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9471 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9472 /// are assumed to be legal.
9474 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9476 // Very little shuffling can be done for 64-bit vectors right now.
9477 if (VT.getSizeInBits() == 64)
9478 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9480 // FIXME: pshufb, blends, shifts.
9481 return (VT.getVectorNumElements() == 2 ||
9482 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9483 isMOVLMask(M, VT) ||
9484 isSHUFPMask(M, VT) ||
9485 isPSHUFDMask(M, VT) ||
9486 isPSHUFHWMask(M, VT) ||
9487 isPSHUFLWMask(M, VT) ||
9488 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9489 isUNPCKLMask(M, VT) ||
9490 isUNPCKHMask(M, VT) ||
9491 isUNPCKL_v_undef_Mask(M, VT) ||
9492 isUNPCKH_v_undef_Mask(M, VT));
9496 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9498 unsigned NumElts = VT.getVectorNumElements();
9499 // FIXME: This collection of masks seems suspect.
9502 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9503 return (isMOVLMask(Mask, VT) ||
9504 isCommutedMOVLMask(Mask, VT, true) ||
9505 isSHUFPMask(Mask, VT) ||
9506 isCommutedSHUFPMask(Mask, VT));
9511 //===----------------------------------------------------------------------===//
9512 // X86 Scheduler Hooks
9513 //===----------------------------------------------------------------------===//
9515 // private utility function
9517 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9518 MachineBasicBlock *MBB,
9525 TargetRegisterClass *RC,
9526 bool invSrc) const {
9527 // For the atomic bitwise operator, we generate
9530 // ld t1 = [bitinstr.addr]
9531 // op t2 = t1, [bitinstr.val]
9533 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9535 // fallthrough -->nextMBB
9536 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9537 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9538 MachineFunction::iterator MBBIter = MBB;
9541 /// First build the CFG
9542 MachineFunction *F = MBB->getParent();
9543 MachineBasicBlock *thisMBB = MBB;
9544 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9545 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9546 F->insert(MBBIter, newMBB);
9547 F->insert(MBBIter, nextMBB);
9549 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9550 nextMBB->splice(nextMBB->begin(), thisMBB,
9551 llvm::next(MachineBasicBlock::iterator(bInstr)),
9553 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9555 // Update thisMBB to fall through to newMBB
9556 thisMBB->addSuccessor(newMBB);
9558 // newMBB jumps to itself and fall through to nextMBB
9559 newMBB->addSuccessor(nextMBB);
9560 newMBB->addSuccessor(newMBB);
9562 // Insert instructions into newMBB based on incoming instruction
9563 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9564 "unexpected number of operands");
9565 DebugLoc dl = bInstr->getDebugLoc();
9566 MachineOperand& destOper = bInstr->getOperand(0);
9567 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9568 int numArgs = bInstr->getNumOperands() - 1;
9569 for (int i=0; i < numArgs; ++i)
9570 argOpers[i] = &bInstr->getOperand(i+1);
9572 // x86 address has 4 operands: base, index, scale, and displacement
9573 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9574 int valArgIndx = lastAddrIndx + 1;
9576 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9577 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9578 for (int i=0; i <= lastAddrIndx; ++i)
9579 (*MIB).addOperand(*argOpers[i]);
9581 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9583 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9588 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9589 assert((argOpers[valArgIndx]->isReg() ||
9590 argOpers[valArgIndx]->isImm()) &&
9592 if (argOpers[valArgIndx]->isReg())
9593 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9595 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9597 (*MIB).addOperand(*argOpers[valArgIndx]);
9599 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9602 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9603 for (int i=0; i <= lastAddrIndx; ++i)
9604 (*MIB).addOperand(*argOpers[i]);
9606 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9607 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9608 bInstr->memoperands_end());
9610 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9614 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9616 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9620 // private utility function: 64 bit atomics on 32 bit host.
9622 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9623 MachineBasicBlock *MBB,
9628 bool invSrc) const {
9629 // For the atomic bitwise operator, we generate
9630 // thisMBB (instructions are in pairs, except cmpxchg8b)
9631 // ld t1,t2 = [bitinstr.addr]
9633 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9634 // op t5, t6 <- out1, out2, [bitinstr.val]
9635 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9636 // mov ECX, EBX <- t5, t6
9637 // mov EAX, EDX <- t1, t2
9638 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9639 // mov t3, t4 <- EAX, EDX
9641 // result in out1, out2
9642 // fallthrough -->nextMBB
9644 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9645 const unsigned LoadOpc = X86::MOV32rm;
9646 const unsigned NotOpc = X86::NOT32r;
9647 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9648 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9649 MachineFunction::iterator MBBIter = MBB;
9652 /// First build the CFG
9653 MachineFunction *F = MBB->getParent();
9654 MachineBasicBlock *thisMBB = MBB;
9655 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9656 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9657 F->insert(MBBIter, newMBB);
9658 F->insert(MBBIter, nextMBB);
9660 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9661 nextMBB->splice(nextMBB->begin(), thisMBB,
9662 llvm::next(MachineBasicBlock::iterator(bInstr)),
9664 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9666 // Update thisMBB to fall through to newMBB
9667 thisMBB->addSuccessor(newMBB);
9669 // newMBB jumps to itself and fall through to nextMBB
9670 newMBB->addSuccessor(nextMBB);
9671 newMBB->addSuccessor(newMBB);
9673 DebugLoc dl = bInstr->getDebugLoc();
9674 // Insert instructions into newMBB based on incoming instruction
9675 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9676 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9677 "unexpected number of operands");
9678 MachineOperand& dest1Oper = bInstr->getOperand(0);
9679 MachineOperand& dest2Oper = bInstr->getOperand(1);
9680 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9681 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9682 argOpers[i] = &bInstr->getOperand(i+2);
9684 // We use some of the operands multiple times, so conservatively just
9685 // clear any kill flags that might be present.
9686 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9687 argOpers[i]->setIsKill(false);
9690 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9691 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9693 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9694 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9695 for (int i=0; i <= lastAddrIndx; ++i)
9696 (*MIB).addOperand(*argOpers[i]);
9697 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9698 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9699 // add 4 to displacement.
9700 for (int i=0; i <= lastAddrIndx-2; ++i)
9701 (*MIB).addOperand(*argOpers[i]);
9702 MachineOperand newOp3 = *(argOpers[3]);
9704 newOp3.setImm(newOp3.getImm()+4);
9706 newOp3.setOffset(newOp3.getOffset()+4);
9707 (*MIB).addOperand(newOp3);
9708 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9710 // t3/4 are defined later, at the bottom of the loop
9711 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9712 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9713 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9714 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9715 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9716 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9718 // The subsequent operations should be using the destination registers of
9719 //the PHI instructions.
9721 t1 = F->getRegInfo().createVirtualRegister(RC);
9722 t2 = F->getRegInfo().createVirtualRegister(RC);
9723 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9724 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9726 t1 = dest1Oper.getReg();
9727 t2 = dest2Oper.getReg();
9730 int valArgIndx = lastAddrIndx + 1;
9731 assert((argOpers[valArgIndx]->isReg() ||
9732 argOpers[valArgIndx]->isImm()) &&
9734 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9735 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9736 if (argOpers[valArgIndx]->isReg())
9737 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9739 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9740 if (regOpcL != X86::MOV32rr)
9742 (*MIB).addOperand(*argOpers[valArgIndx]);
9743 assert(argOpers[valArgIndx + 1]->isReg() ==
9744 argOpers[valArgIndx]->isReg());
9745 assert(argOpers[valArgIndx + 1]->isImm() ==
9746 argOpers[valArgIndx]->isImm());
9747 if (argOpers[valArgIndx + 1]->isReg())
9748 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9750 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9751 if (regOpcH != X86::MOV32rr)
9753 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9755 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9757 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9760 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9762 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9765 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9766 for (int i=0; i <= lastAddrIndx; ++i)
9767 (*MIB).addOperand(*argOpers[i]);
9769 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9770 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9771 bInstr->memoperands_end());
9773 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9774 MIB.addReg(X86::EAX);
9775 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9776 MIB.addReg(X86::EDX);
9779 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9781 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9785 // private utility function
9787 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9788 MachineBasicBlock *MBB,
9789 unsigned cmovOpc) const {
9790 // For the atomic min/max operator, we generate
9793 // ld t1 = [min/max.addr]
9794 // mov t2 = [min/max.val]
9796 // cmov[cond] t2 = t1
9798 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9800 // fallthrough -->nextMBB
9802 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9803 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9804 MachineFunction::iterator MBBIter = MBB;
9807 /// First build the CFG
9808 MachineFunction *F = MBB->getParent();
9809 MachineBasicBlock *thisMBB = MBB;
9810 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9811 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9812 F->insert(MBBIter, newMBB);
9813 F->insert(MBBIter, nextMBB);
9815 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9816 nextMBB->splice(nextMBB->begin(), thisMBB,
9817 llvm::next(MachineBasicBlock::iterator(mInstr)),
9819 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9821 // Update thisMBB to fall through to newMBB
9822 thisMBB->addSuccessor(newMBB);
9824 // newMBB jumps to newMBB and fall through to nextMBB
9825 newMBB->addSuccessor(nextMBB);
9826 newMBB->addSuccessor(newMBB);
9828 DebugLoc dl = mInstr->getDebugLoc();
9829 // Insert instructions into newMBB based on incoming instruction
9830 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9831 "unexpected number of operands");
9832 MachineOperand& destOper = mInstr->getOperand(0);
9833 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9834 int numArgs = mInstr->getNumOperands() - 1;
9835 for (int i=0; i < numArgs; ++i)
9836 argOpers[i] = &mInstr->getOperand(i+1);
9838 // x86 address has 4 operands: base, index, scale, and displacement
9839 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9840 int valArgIndx = lastAddrIndx + 1;
9842 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9843 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9844 for (int i=0; i <= lastAddrIndx; ++i)
9845 (*MIB).addOperand(*argOpers[i]);
9847 // We only support register and immediate values
9848 assert((argOpers[valArgIndx]->isReg() ||
9849 argOpers[valArgIndx]->isImm()) &&
9852 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9853 if (argOpers[valArgIndx]->isReg())
9854 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9856 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9857 (*MIB).addOperand(*argOpers[valArgIndx]);
9859 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9862 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9867 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9868 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9872 // Cmp and exchange if none has modified the memory location
9873 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9874 for (int i=0; i <= lastAddrIndx; ++i)
9875 (*MIB).addOperand(*argOpers[i]);
9877 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9878 (*MIB).setMemRefs(mInstr->memoperands_begin(),
9879 mInstr->memoperands_end());
9881 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9882 MIB.addReg(X86::EAX);
9885 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9887 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
9891 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9892 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9895 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9896 unsigned numArgs, bool memArg) const {
9897 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9898 "Target must have SSE4.2 or AVX features enabled");
9900 DebugLoc dl = MI->getDebugLoc();
9901 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9903 if (!Subtarget->hasAVX()) {
9905 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9907 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9910 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9912 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9915 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9916 for (unsigned i = 0; i < numArgs; ++i) {
9917 MachineOperand &Op = MI->getOperand(i+1);
9918 if (!(Op.isReg() && Op.isImplicit()))
9921 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9924 MI->eraseFromParent();
9929 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9930 DebugLoc dl = MI->getDebugLoc();
9931 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9933 // Address into RAX/EAX, other two args into ECX, EDX.
9934 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9935 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9936 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9937 for (int i = 0; i < X86::AddrNumOperands; ++i)
9938 MIB.addOperand(MI->getOperand(i));
9940 unsigned ValOps = X86::AddrNumOperands;
9941 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9942 .addReg(MI->getOperand(ValOps).getReg());
9943 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9944 .addReg(MI->getOperand(ValOps+1).getReg());
9946 // The instruction doesn't actually take any operands though.
9947 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9949 MI->eraseFromParent(); // The pseudo is gone now.
9954 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9955 DebugLoc dl = MI->getDebugLoc();
9956 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9958 // First arg in ECX, the second in EAX.
9959 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9960 .addReg(MI->getOperand(0).getReg());
9961 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9962 .addReg(MI->getOperand(1).getReg());
9964 // The instruction doesn't actually take any operands though.
9965 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9967 MI->eraseFromParent(); // The pseudo is gone now.
9972 X86TargetLowering::EmitVAARG64WithCustomInserter(
9974 MachineBasicBlock *MBB) const {
9975 // Emit va_arg instruction on X86-64.
9977 // Operands to this pseudo-instruction:
9978 // 0 ) Output : destination address (reg)
9979 // 1-5) Input : va_list address (addr, i64mem)
9980 // 6 ) ArgSize : Size (in bytes) of vararg type
9981 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
9982 // 8 ) Align : Alignment of type
9983 // 9 ) EFLAGS (implicit-def)
9985 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
9986 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
9988 unsigned DestReg = MI->getOperand(0).getReg();
9989 MachineOperand &Base = MI->getOperand(1);
9990 MachineOperand &Scale = MI->getOperand(2);
9991 MachineOperand &Index = MI->getOperand(3);
9992 MachineOperand &Disp = MI->getOperand(4);
9993 MachineOperand &Segment = MI->getOperand(5);
9994 unsigned ArgSize = MI->getOperand(6).getImm();
9995 unsigned ArgMode = MI->getOperand(7).getImm();
9996 unsigned Align = MI->getOperand(8).getImm();
9999 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10000 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10001 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10003 // Machine Information
10004 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10005 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10006 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10007 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10008 DebugLoc DL = MI->getDebugLoc();
10010 // struct va_list {
10013 // i64 overflow_area (address)
10014 // i64 reg_save_area (address)
10016 // sizeof(va_list) = 24
10017 // alignment(va_list) = 8
10019 unsigned TotalNumIntRegs = 6;
10020 unsigned TotalNumXMMRegs = 8;
10021 bool UseGPOffset = (ArgMode == 1);
10022 bool UseFPOffset = (ArgMode == 2);
10023 unsigned MaxOffset = TotalNumIntRegs * 8 +
10024 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10026 /* Align ArgSize to a multiple of 8 */
10027 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10028 bool NeedsAlign = (Align > 8);
10030 MachineBasicBlock *thisMBB = MBB;
10031 MachineBasicBlock *overflowMBB;
10032 MachineBasicBlock *offsetMBB;
10033 MachineBasicBlock *endMBB;
10035 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
10036 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
10037 unsigned OffsetReg = 0;
10039 if (!UseGPOffset && !UseFPOffset) {
10040 // If we only pull from the overflow region, we don't create a branch.
10041 // We don't need to alter control flow.
10042 OffsetDestReg = 0; // unused
10043 OverflowDestReg = DestReg;
10046 overflowMBB = thisMBB;
10049 // First emit code to check if gp_offset (or fp_offset) is below the bound.
10050 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10051 // If not, pull from overflow_area. (branch to overflowMBB)
10056 // offsetMBB overflowMBB
10061 // Registers for the PHI in endMBB
10062 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10063 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10065 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10066 MachineFunction *MF = MBB->getParent();
10067 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10068 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10069 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10071 MachineFunction::iterator MBBIter = MBB;
10074 // Insert the new basic blocks
10075 MF->insert(MBBIter, offsetMBB);
10076 MF->insert(MBBIter, overflowMBB);
10077 MF->insert(MBBIter, endMBB);
10079 // Transfer the remainder of MBB and its successor edges to endMBB.
10080 endMBB->splice(endMBB->begin(), thisMBB,
10081 llvm::next(MachineBasicBlock::iterator(MI)),
10083 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10085 // Make offsetMBB and overflowMBB successors of thisMBB
10086 thisMBB->addSuccessor(offsetMBB);
10087 thisMBB->addSuccessor(overflowMBB);
10089 // endMBB is a successor of both offsetMBB and overflowMBB
10090 offsetMBB->addSuccessor(endMBB);
10091 overflowMBB->addSuccessor(endMBB);
10093 // Load the offset value into a register
10094 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10095 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10099 .addDisp(Disp, UseFPOffset ? 4 : 0)
10100 .addOperand(Segment)
10101 .setMemRefs(MMOBegin, MMOEnd);
10103 // Check if there is enough room left to pull this argument.
10104 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10106 .addImm(MaxOffset + 8 - ArgSizeA8);
10108 // Branch to "overflowMBB" if offset >= max
10109 // Fall through to "offsetMBB" otherwise
10110 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10111 .addMBB(overflowMBB);
10114 // In offsetMBB, emit code to use the reg_save_area.
10116 assert(OffsetReg != 0);
10118 // Read the reg_save_area address.
10119 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10120 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10125 .addOperand(Segment)
10126 .setMemRefs(MMOBegin, MMOEnd);
10128 // Zero-extend the offset
10129 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10130 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10133 .addImm(X86::sub_32bit);
10135 // Add the offset to the reg_save_area to get the final address.
10136 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10137 .addReg(OffsetReg64)
10138 .addReg(RegSaveReg);
10140 // Compute the offset for the next argument
10141 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10142 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10144 .addImm(UseFPOffset ? 16 : 8);
10146 // Store it back into the va_list.
10147 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10151 .addDisp(Disp, UseFPOffset ? 4 : 0)
10152 .addOperand(Segment)
10153 .addReg(NextOffsetReg)
10154 .setMemRefs(MMOBegin, MMOEnd);
10157 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10162 // Emit code to use overflow area
10165 // Load the overflow_area address into a register.
10166 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10167 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10172 .addOperand(Segment)
10173 .setMemRefs(MMOBegin, MMOEnd);
10175 // If we need to align it, do so. Otherwise, just copy the address
10176 // to OverflowDestReg.
10178 // Align the overflow address
10179 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10180 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10182 // aligned_addr = (addr + (align-1)) & ~(align-1)
10183 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10184 .addReg(OverflowAddrReg)
10187 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10189 .addImm(~(uint64_t)(Align-1));
10191 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10192 .addReg(OverflowAddrReg);
10195 // Compute the next overflow address after this argument.
10196 // (the overflow address should be kept 8-byte aligned)
10197 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10198 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10199 .addReg(OverflowDestReg)
10200 .addImm(ArgSizeA8);
10202 // Store the new overflow address.
10203 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10208 .addOperand(Segment)
10209 .addReg(NextAddrReg)
10210 .setMemRefs(MMOBegin, MMOEnd);
10212 // If we branched, emit the PHI to the front of endMBB.
10214 BuildMI(*endMBB, endMBB->begin(), DL,
10215 TII->get(X86::PHI), DestReg)
10216 .addReg(OffsetDestReg).addMBB(offsetMBB)
10217 .addReg(OverflowDestReg).addMBB(overflowMBB);
10220 // Erase the pseudo instruction
10221 MI->eraseFromParent();
10226 MachineBasicBlock *
10227 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10229 MachineBasicBlock *MBB) const {
10230 // Emit code to save XMM registers to the stack. The ABI says that the
10231 // number of registers to save is given in %al, so it's theoretically
10232 // possible to do an indirect jump trick to avoid saving all of them,
10233 // however this code takes a simpler approach and just executes all
10234 // of the stores if %al is non-zero. It's less code, and it's probably
10235 // easier on the hardware branch predictor, and stores aren't all that
10236 // expensive anyway.
10238 // Create the new basic blocks. One block contains all the XMM stores,
10239 // and one block is the final destination regardless of whether any
10240 // stores were performed.
10241 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10242 MachineFunction *F = MBB->getParent();
10243 MachineFunction::iterator MBBIter = MBB;
10245 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10246 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10247 F->insert(MBBIter, XMMSaveMBB);
10248 F->insert(MBBIter, EndMBB);
10250 // Transfer the remainder of MBB and its successor edges to EndMBB.
10251 EndMBB->splice(EndMBB->begin(), MBB,
10252 llvm::next(MachineBasicBlock::iterator(MI)),
10254 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10256 // The original block will now fall through to the XMM save block.
10257 MBB->addSuccessor(XMMSaveMBB);
10258 // The XMMSaveMBB will fall through to the end block.
10259 XMMSaveMBB->addSuccessor(EndMBB);
10261 // Now add the instructions.
10262 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10263 DebugLoc DL = MI->getDebugLoc();
10265 unsigned CountReg = MI->getOperand(0).getReg();
10266 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10267 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10269 if (!Subtarget->isTargetWin64()) {
10270 // If %al is 0, branch around the XMM save block.
10271 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10272 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10273 MBB->addSuccessor(EndMBB);
10276 // In the XMM save block, save all the XMM argument registers.
10277 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10278 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10279 MachineMemOperand *MMO =
10280 F->getMachineMemOperand(
10281 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10282 MachineMemOperand::MOStore,
10283 /*Size=*/16, /*Align=*/16);
10284 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10285 .addFrameIndex(RegSaveFrameIndex)
10286 .addImm(/*Scale=*/1)
10287 .addReg(/*IndexReg=*/0)
10288 .addImm(/*Disp=*/Offset)
10289 .addReg(/*Segment=*/0)
10290 .addReg(MI->getOperand(i).getReg())
10291 .addMemOperand(MMO);
10294 MI->eraseFromParent(); // The pseudo instruction is gone now.
10299 MachineBasicBlock *
10300 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10301 MachineBasicBlock *BB) const {
10302 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10303 DebugLoc DL = MI->getDebugLoc();
10305 // To "insert" a SELECT_CC instruction, we actually have to insert the
10306 // diamond control-flow pattern. The incoming instruction knows the
10307 // destination vreg to set, the condition code register to branch on, the
10308 // true/false values to select between, and a branch opcode to use.
10309 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10310 MachineFunction::iterator It = BB;
10316 // cmpTY ccX, r1, r2
10318 // fallthrough --> copy0MBB
10319 MachineBasicBlock *thisMBB = BB;
10320 MachineFunction *F = BB->getParent();
10321 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10322 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10323 F->insert(It, copy0MBB);
10324 F->insert(It, sinkMBB);
10326 // If the EFLAGS register isn't dead in the terminator, then claim that it's
10327 // live into the sink and copy blocks.
10328 const MachineFunction *MF = BB->getParent();
10329 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10330 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10332 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10333 const MachineOperand &MO = MI->getOperand(I);
10334 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10335 unsigned Reg = MO.getReg();
10336 if (Reg != X86::EFLAGS) continue;
10337 copy0MBB->addLiveIn(Reg);
10338 sinkMBB->addLiveIn(Reg);
10341 // Transfer the remainder of BB and its successor edges to sinkMBB.
10342 sinkMBB->splice(sinkMBB->begin(), BB,
10343 llvm::next(MachineBasicBlock::iterator(MI)),
10345 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10347 // Add the true and fallthrough blocks as its successors.
10348 BB->addSuccessor(copy0MBB);
10349 BB->addSuccessor(sinkMBB);
10351 // Create the conditional branch instruction.
10353 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10354 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10357 // %FalseValue = ...
10358 // # fallthrough to sinkMBB
10359 copy0MBB->addSuccessor(sinkMBB);
10362 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10364 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10365 TII->get(X86::PHI), MI->getOperand(0).getReg())
10366 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10367 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10369 MI->eraseFromParent(); // The pseudo instruction is gone now.
10373 MachineBasicBlock *
10374 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10375 MachineBasicBlock *BB) const {
10376 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10377 DebugLoc DL = MI->getDebugLoc();
10379 // The lowering is pretty easy: we're just emitting the call to _alloca. The
10380 // non-trivial part is impdef of ESP.
10381 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
10384 const char *StackProbeSymbol =
10385 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10387 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10388 .addExternalSymbol(StackProbeSymbol)
10389 .addReg(X86::EAX, RegState::Implicit)
10390 .addReg(X86::ESP, RegState::Implicit)
10391 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10392 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10393 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10395 MI->eraseFromParent(); // The pseudo instruction is gone now.
10399 MachineBasicBlock *
10400 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10401 MachineBasicBlock *BB) const {
10402 // This is pretty easy. We're taking the value that we received from
10403 // our load from the relocation, sticking it in either RDI (x86-64)
10404 // or EAX and doing an indirect call. The return value will then
10405 // be in the normal return register.
10406 const X86InstrInfo *TII
10407 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10408 DebugLoc DL = MI->getDebugLoc();
10409 MachineFunction *F = BB->getParent();
10411 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10412 assert(MI->getOperand(3).isGlobal() && "This should be a global");
10414 if (Subtarget->is64Bit()) {
10415 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10416 TII->get(X86::MOV64rm), X86::RDI)
10418 .addImm(0).addReg(0)
10419 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10420 MI->getOperand(3).getTargetFlags())
10422 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10423 addDirectMem(MIB, X86::RDI);
10424 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10425 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10426 TII->get(X86::MOV32rm), X86::EAX)
10428 .addImm(0).addReg(0)
10429 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10430 MI->getOperand(3).getTargetFlags())
10432 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10433 addDirectMem(MIB, X86::EAX);
10435 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10436 TII->get(X86::MOV32rm), X86::EAX)
10437 .addReg(TII->getGlobalBaseReg(F))
10438 .addImm(0).addReg(0)
10439 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10440 MI->getOperand(3).getTargetFlags())
10442 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10443 addDirectMem(MIB, X86::EAX);
10446 MI->eraseFromParent(); // The pseudo instruction is gone now.
10450 MachineBasicBlock *
10451 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10452 MachineBasicBlock *BB) const {
10453 switch (MI->getOpcode()) {
10454 default: assert(false && "Unexpected instr type to insert");
10455 case X86::TAILJMPd64:
10456 case X86::TAILJMPr64:
10457 case X86::TAILJMPm64:
10458 assert(!"TAILJMP64 would not be touched here.");
10459 case X86::TCRETURNdi64:
10460 case X86::TCRETURNri64:
10461 case X86::TCRETURNmi64:
10462 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10463 // On AMD64, additional defs should be added before register allocation.
10464 if (!Subtarget->isTargetWin64()) {
10465 MI->addRegisterDefined(X86::RSI);
10466 MI->addRegisterDefined(X86::RDI);
10467 MI->addRegisterDefined(X86::XMM6);
10468 MI->addRegisterDefined(X86::XMM7);
10469 MI->addRegisterDefined(X86::XMM8);
10470 MI->addRegisterDefined(X86::XMM9);
10471 MI->addRegisterDefined(X86::XMM10);
10472 MI->addRegisterDefined(X86::XMM11);
10473 MI->addRegisterDefined(X86::XMM12);
10474 MI->addRegisterDefined(X86::XMM13);
10475 MI->addRegisterDefined(X86::XMM14);
10476 MI->addRegisterDefined(X86::XMM15);
10479 case X86::WIN_ALLOCA:
10480 return EmitLoweredWinAlloca(MI, BB);
10481 case X86::TLSCall_32:
10482 case X86::TLSCall_64:
10483 return EmitLoweredTLSCall(MI, BB);
10484 case X86::CMOV_GR8:
10485 case X86::CMOV_FR32:
10486 case X86::CMOV_FR64:
10487 case X86::CMOV_V4F32:
10488 case X86::CMOV_V2F64:
10489 case X86::CMOV_V2I64:
10490 case X86::CMOV_GR16:
10491 case X86::CMOV_GR32:
10492 case X86::CMOV_RFP32:
10493 case X86::CMOV_RFP64:
10494 case X86::CMOV_RFP80:
10495 return EmitLoweredSelect(MI, BB);
10497 case X86::FP32_TO_INT16_IN_MEM:
10498 case X86::FP32_TO_INT32_IN_MEM:
10499 case X86::FP32_TO_INT64_IN_MEM:
10500 case X86::FP64_TO_INT16_IN_MEM:
10501 case X86::FP64_TO_INT32_IN_MEM:
10502 case X86::FP64_TO_INT64_IN_MEM:
10503 case X86::FP80_TO_INT16_IN_MEM:
10504 case X86::FP80_TO_INT32_IN_MEM:
10505 case X86::FP80_TO_INT64_IN_MEM: {
10506 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10507 DebugLoc DL = MI->getDebugLoc();
10509 // Change the floating point control register to use "round towards zero"
10510 // mode when truncating to an integer value.
10511 MachineFunction *F = BB->getParent();
10512 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10513 addFrameReference(BuildMI(*BB, MI, DL,
10514 TII->get(X86::FNSTCW16m)), CWFrameIdx);
10516 // Load the old value of the high byte of the control word...
10518 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10519 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10522 // Set the high part to be round to zero...
10523 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10526 // Reload the modified control word now...
10527 addFrameReference(BuildMI(*BB, MI, DL,
10528 TII->get(X86::FLDCW16m)), CWFrameIdx);
10530 // Restore the memory image of control word to original value
10531 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10534 // Get the X86 opcode to use.
10536 switch (MI->getOpcode()) {
10537 default: llvm_unreachable("illegal opcode!");
10538 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10539 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10540 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10541 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10542 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10543 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10544 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10545 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10546 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10550 MachineOperand &Op = MI->getOperand(0);
10552 AM.BaseType = X86AddressMode::RegBase;
10553 AM.Base.Reg = Op.getReg();
10555 AM.BaseType = X86AddressMode::FrameIndexBase;
10556 AM.Base.FrameIndex = Op.getIndex();
10558 Op = MI->getOperand(1);
10560 AM.Scale = Op.getImm();
10561 Op = MI->getOperand(2);
10563 AM.IndexReg = Op.getImm();
10564 Op = MI->getOperand(3);
10565 if (Op.isGlobal()) {
10566 AM.GV = Op.getGlobal();
10568 AM.Disp = Op.getImm();
10570 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10571 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10573 // Reload the original control word now.
10574 addFrameReference(BuildMI(*BB, MI, DL,
10575 TII->get(X86::FLDCW16m)), CWFrameIdx);
10577 MI->eraseFromParent(); // The pseudo instruction is gone now.
10580 // String/text processing lowering.
10581 case X86::PCMPISTRM128REG:
10582 case X86::VPCMPISTRM128REG:
10583 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10584 case X86::PCMPISTRM128MEM:
10585 case X86::VPCMPISTRM128MEM:
10586 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10587 case X86::PCMPESTRM128REG:
10588 case X86::VPCMPESTRM128REG:
10589 return EmitPCMP(MI, BB, 5, false /* in mem */);
10590 case X86::PCMPESTRM128MEM:
10591 case X86::VPCMPESTRM128MEM:
10592 return EmitPCMP(MI, BB, 5, true /* in mem */);
10594 // Thread synchronization.
10596 return EmitMonitor(MI, BB);
10598 return EmitMwait(MI, BB);
10600 // Atomic Lowering.
10601 case X86::ATOMAND32:
10602 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10603 X86::AND32ri, X86::MOV32rm,
10605 X86::NOT32r, X86::EAX,
10606 X86::GR32RegisterClass);
10607 case X86::ATOMOR32:
10608 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10609 X86::OR32ri, X86::MOV32rm,
10611 X86::NOT32r, X86::EAX,
10612 X86::GR32RegisterClass);
10613 case X86::ATOMXOR32:
10614 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10615 X86::XOR32ri, X86::MOV32rm,
10617 X86::NOT32r, X86::EAX,
10618 X86::GR32RegisterClass);
10619 case X86::ATOMNAND32:
10620 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10621 X86::AND32ri, X86::MOV32rm,
10623 X86::NOT32r, X86::EAX,
10624 X86::GR32RegisterClass, true);
10625 case X86::ATOMMIN32:
10626 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10627 case X86::ATOMMAX32:
10628 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10629 case X86::ATOMUMIN32:
10630 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10631 case X86::ATOMUMAX32:
10632 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10634 case X86::ATOMAND16:
10635 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10636 X86::AND16ri, X86::MOV16rm,
10638 X86::NOT16r, X86::AX,
10639 X86::GR16RegisterClass);
10640 case X86::ATOMOR16:
10641 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10642 X86::OR16ri, X86::MOV16rm,
10644 X86::NOT16r, X86::AX,
10645 X86::GR16RegisterClass);
10646 case X86::ATOMXOR16:
10647 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10648 X86::XOR16ri, X86::MOV16rm,
10650 X86::NOT16r, X86::AX,
10651 X86::GR16RegisterClass);
10652 case X86::ATOMNAND16:
10653 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10654 X86::AND16ri, X86::MOV16rm,
10656 X86::NOT16r, X86::AX,
10657 X86::GR16RegisterClass, true);
10658 case X86::ATOMMIN16:
10659 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10660 case X86::ATOMMAX16:
10661 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10662 case X86::ATOMUMIN16:
10663 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10664 case X86::ATOMUMAX16:
10665 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10667 case X86::ATOMAND8:
10668 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10669 X86::AND8ri, X86::MOV8rm,
10671 X86::NOT8r, X86::AL,
10672 X86::GR8RegisterClass);
10674 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10675 X86::OR8ri, X86::MOV8rm,
10677 X86::NOT8r, X86::AL,
10678 X86::GR8RegisterClass);
10679 case X86::ATOMXOR8:
10680 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10681 X86::XOR8ri, X86::MOV8rm,
10683 X86::NOT8r, X86::AL,
10684 X86::GR8RegisterClass);
10685 case X86::ATOMNAND8:
10686 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10687 X86::AND8ri, X86::MOV8rm,
10689 X86::NOT8r, X86::AL,
10690 X86::GR8RegisterClass, true);
10691 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10692 // This group is for 64-bit host.
10693 case X86::ATOMAND64:
10694 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10695 X86::AND64ri32, X86::MOV64rm,
10697 X86::NOT64r, X86::RAX,
10698 X86::GR64RegisterClass);
10699 case X86::ATOMOR64:
10700 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10701 X86::OR64ri32, X86::MOV64rm,
10703 X86::NOT64r, X86::RAX,
10704 X86::GR64RegisterClass);
10705 case X86::ATOMXOR64:
10706 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10707 X86::XOR64ri32, X86::MOV64rm,
10709 X86::NOT64r, X86::RAX,
10710 X86::GR64RegisterClass);
10711 case X86::ATOMNAND64:
10712 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10713 X86::AND64ri32, X86::MOV64rm,
10715 X86::NOT64r, X86::RAX,
10716 X86::GR64RegisterClass, true);
10717 case X86::ATOMMIN64:
10718 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10719 case X86::ATOMMAX64:
10720 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10721 case X86::ATOMUMIN64:
10722 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10723 case X86::ATOMUMAX64:
10724 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10726 // This group does 64-bit operations on a 32-bit host.
10727 case X86::ATOMAND6432:
10728 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10729 X86::AND32rr, X86::AND32rr,
10730 X86::AND32ri, X86::AND32ri,
10732 case X86::ATOMOR6432:
10733 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10734 X86::OR32rr, X86::OR32rr,
10735 X86::OR32ri, X86::OR32ri,
10737 case X86::ATOMXOR6432:
10738 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10739 X86::XOR32rr, X86::XOR32rr,
10740 X86::XOR32ri, X86::XOR32ri,
10742 case X86::ATOMNAND6432:
10743 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10744 X86::AND32rr, X86::AND32rr,
10745 X86::AND32ri, X86::AND32ri,
10747 case X86::ATOMADD6432:
10748 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10749 X86::ADD32rr, X86::ADC32rr,
10750 X86::ADD32ri, X86::ADC32ri,
10752 case X86::ATOMSUB6432:
10753 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10754 X86::SUB32rr, X86::SBB32rr,
10755 X86::SUB32ri, X86::SBB32ri,
10757 case X86::ATOMSWAP6432:
10758 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10759 X86::MOV32rr, X86::MOV32rr,
10760 X86::MOV32ri, X86::MOV32ri,
10762 case X86::VASTART_SAVE_XMM_REGS:
10763 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10765 case X86::VAARG_64:
10766 return EmitVAARG64WithCustomInserter(MI, BB);
10770 //===----------------------------------------------------------------------===//
10771 // X86 Optimization Hooks
10772 //===----------------------------------------------------------------------===//
10774 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10778 const SelectionDAG &DAG,
10779 unsigned Depth) const {
10780 unsigned Opc = Op.getOpcode();
10781 assert((Opc >= ISD::BUILTIN_OP_END ||
10782 Opc == ISD::INTRINSIC_WO_CHAIN ||
10783 Opc == ISD::INTRINSIC_W_CHAIN ||
10784 Opc == ISD::INTRINSIC_VOID) &&
10785 "Should use MaskedValueIsZero if you don't know whether Op"
10786 " is a target node!");
10788 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
10802 // These nodes' second result is a boolean.
10803 if (Op.getResNo() == 0)
10806 case X86ISD::SETCC:
10807 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10808 Mask.getBitWidth() - 1);
10813 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10814 unsigned Depth) const {
10815 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10816 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10817 return Op.getValueType().getScalarType().getSizeInBits();
10823 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10824 /// node is a GlobalAddress + offset.
10825 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10826 const GlobalValue* &GA,
10827 int64_t &Offset) const {
10828 if (N->getOpcode() == X86ISD::Wrapper) {
10829 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10830 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10831 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10835 return TargetLowering::isGAPlusOffset(N, GA, Offset);
10838 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10839 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10840 /// if the load addresses are consecutive, non-overlapping, and in the right
10842 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10843 TargetLowering::DAGCombinerInfo &DCI) {
10844 DebugLoc dl = N->getDebugLoc();
10845 EVT VT = N->getValueType(0);
10847 if (VT.getSizeInBits() != 128)
10850 // Don't create instructions with illegal types after legalize types has run.
10851 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10852 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
10855 SmallVector<SDValue, 16> Elts;
10856 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10857 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10859 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10862 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10863 /// generation and convert it from being a bunch of shuffles and extracts
10864 /// to a simple store and scalar loads to extract the elements.
10865 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10866 const TargetLowering &TLI) {
10867 SDValue InputVector = N->getOperand(0);
10869 // Only operate on vectors of 4 elements, where the alternative shuffling
10870 // gets to be more expensive.
10871 if (InputVector.getValueType() != MVT::v4i32)
10874 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10875 // single use which is a sign-extend or zero-extend, and all elements are
10877 SmallVector<SDNode *, 4> Uses;
10878 unsigned ExtractedElements = 0;
10879 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10880 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10881 if (UI.getUse().getResNo() != InputVector.getResNo())
10884 SDNode *Extract = *UI;
10885 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10888 if (Extract->getValueType(0) != MVT::i32)
10890 if (!Extract->hasOneUse())
10892 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10893 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10895 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10898 // Record which element was extracted.
10899 ExtractedElements |=
10900 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10902 Uses.push_back(Extract);
10905 // If not all the elements were used, this may not be worthwhile.
10906 if (ExtractedElements != 15)
10909 // Ok, we've now decided to do the transformation.
10910 DebugLoc dl = InputVector.getDebugLoc();
10912 // Store the value to a temporary stack slot.
10913 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10914 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10915 MachinePointerInfo(), false, false, 0);
10917 // Replace each use (extract) with a load of the appropriate element.
10918 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10919 UE = Uses.end(); UI != UE; ++UI) {
10920 SDNode *Extract = *UI;
10922 // Compute the element's address.
10923 SDValue Idx = Extract->getOperand(1);
10925 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10926 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10927 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10929 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10930 StackPtr, OffsetVal);
10932 // Load the scalar.
10933 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10934 ScalarAddr, MachinePointerInfo(),
10937 // Replace the exact with the load.
10938 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10941 // The replacement was made in place; don't return anything.
10945 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10946 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10947 const X86Subtarget *Subtarget) {
10948 DebugLoc DL = N->getDebugLoc();
10949 SDValue Cond = N->getOperand(0);
10950 // Get the LHS/RHS of the select.
10951 SDValue LHS = N->getOperand(1);
10952 SDValue RHS = N->getOperand(2);
10954 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10955 // instructions match the semantics of the common C idiom x<y?x:y but not
10956 // x<=y?x:y, because of how they handle negative zero (which can be
10957 // ignored in unsafe-math mode).
10958 if (Subtarget->hasSSE2() &&
10959 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10960 Cond.getOpcode() == ISD::SETCC) {
10961 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10963 unsigned Opcode = 0;
10964 // Check for x CC y ? x : y.
10965 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10966 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10970 // Converting this to a min would handle NaNs incorrectly, and swapping
10971 // the operands would cause it to handle comparisons between positive
10972 // and negative zero incorrectly.
10973 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10974 if (!UnsafeFPMath &&
10975 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10977 std::swap(LHS, RHS);
10979 Opcode = X86ISD::FMIN;
10982 // Converting this to a min would handle comparisons between positive
10983 // and negative zero incorrectly.
10984 if (!UnsafeFPMath &&
10985 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10987 Opcode = X86ISD::FMIN;
10990 // Converting this to a min would handle both negative zeros and NaNs
10991 // incorrectly, but we can swap the operands to fix both.
10992 std::swap(LHS, RHS);
10996 Opcode = X86ISD::FMIN;
11000 // Converting this to a max would handle comparisons between positive
11001 // and negative zero incorrectly.
11002 if (!UnsafeFPMath &&
11003 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11005 Opcode = X86ISD::FMAX;
11008 // Converting this to a max would handle NaNs incorrectly, and swapping
11009 // the operands would cause it to handle comparisons between positive
11010 // and negative zero incorrectly.
11011 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11012 if (!UnsafeFPMath &&
11013 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11015 std::swap(LHS, RHS);
11017 Opcode = X86ISD::FMAX;
11020 // Converting this to a max would handle both negative zeros and NaNs
11021 // incorrectly, but we can swap the operands to fix both.
11022 std::swap(LHS, RHS);
11026 Opcode = X86ISD::FMAX;
11029 // Check for x CC y ? y : x -- a min/max with reversed arms.
11030 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11031 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11035 // Converting this to a min would handle comparisons between positive
11036 // and negative zero incorrectly, and swapping the operands would
11037 // cause it to handle NaNs incorrectly.
11038 if (!UnsafeFPMath &&
11039 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11040 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11042 std::swap(LHS, RHS);
11044 Opcode = X86ISD::FMIN;
11047 // Converting this to a min would handle NaNs incorrectly.
11048 if (!UnsafeFPMath &&
11049 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11051 Opcode = X86ISD::FMIN;
11054 // Converting this to a min would handle both negative zeros and NaNs
11055 // incorrectly, but we can swap the operands to fix both.
11056 std::swap(LHS, RHS);
11060 Opcode = X86ISD::FMIN;
11064 // Converting this to a max would handle NaNs incorrectly.
11065 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11067 Opcode = X86ISD::FMAX;
11070 // Converting this to a max would handle comparisons between positive
11071 // and negative zero incorrectly, and swapping the operands would
11072 // cause it to handle NaNs incorrectly.
11073 if (!UnsafeFPMath &&
11074 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11075 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11077 std::swap(LHS, RHS);
11079 Opcode = X86ISD::FMAX;
11082 // Converting this to a max would handle both negative zeros and NaNs
11083 // incorrectly, but we can swap the operands to fix both.
11084 std::swap(LHS, RHS);
11088 Opcode = X86ISD::FMAX;
11094 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11097 // If this is a select between two integer constants, try to do some
11099 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11100 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11101 // Don't do this for crazy integer types.
11102 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11103 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11104 // so that TrueC (the true value) is larger than FalseC.
11105 bool NeedsCondInvert = false;
11107 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11108 // Efficiently invertible.
11109 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
11110 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
11111 isa<ConstantSDNode>(Cond.getOperand(1))))) {
11112 NeedsCondInvert = true;
11113 std::swap(TrueC, FalseC);
11116 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
11117 if (FalseC->getAPIntValue() == 0 &&
11118 TrueC->getAPIntValue().isPowerOf2()) {
11119 if (NeedsCondInvert) // Invert the condition if needed.
11120 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11121 DAG.getConstant(1, Cond.getValueType()));
11123 // Zero extend the condition if needed.
11124 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11126 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11127 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11128 DAG.getConstant(ShAmt, MVT::i8));
11131 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11132 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11133 if (NeedsCondInvert) // Invert the condition if needed.
11134 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11135 DAG.getConstant(1, Cond.getValueType()));
11137 // Zero extend the condition if needed.
11138 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11139 FalseC->getValueType(0), Cond);
11140 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11141 SDValue(FalseC, 0));
11144 // Optimize cases that will turn into an LEA instruction. This requires
11145 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11146 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11147 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11148 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11150 bool isFastMultiplier = false;
11152 switch ((unsigned char)Diff) {
11154 case 1: // result = add base, cond
11155 case 2: // result = lea base( , cond*2)
11156 case 3: // result = lea base(cond, cond*2)
11157 case 4: // result = lea base( , cond*4)
11158 case 5: // result = lea base(cond, cond*4)
11159 case 8: // result = lea base( , cond*8)
11160 case 9: // result = lea base(cond, cond*8)
11161 isFastMultiplier = true;
11166 if (isFastMultiplier) {
11167 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11168 if (NeedsCondInvert) // Invert the condition if needed.
11169 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11170 DAG.getConstant(1, Cond.getValueType()));
11172 // Zero extend the condition if needed.
11173 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11175 // Scale the condition by the difference.
11177 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11178 DAG.getConstant(Diff, Cond.getValueType()));
11180 // Add the base if non-zero.
11181 if (FalseC->getAPIntValue() != 0)
11182 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11183 SDValue(FalseC, 0));
11193 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11194 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11195 TargetLowering::DAGCombinerInfo &DCI) {
11196 DebugLoc DL = N->getDebugLoc();
11198 // If the flag operand isn't dead, don't touch this CMOV.
11199 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11202 // If this is a select between two integer constants, try to do some
11203 // optimizations. Note that the operands are ordered the opposite of SELECT
11205 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
11206 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11207 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11208 // larger than FalseC (the false value).
11209 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11211 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11212 CC = X86::GetOppositeBranchCondition(CC);
11213 std::swap(TrueC, FalseC);
11216 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
11217 // This is efficient for any integer data type (including i8/i16) and
11219 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11220 SDValue Cond = N->getOperand(3);
11221 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11222 DAG.getConstant(CC, MVT::i8), Cond);
11224 // Zero extend the condition if needed.
11225 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11227 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11228 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11229 DAG.getConstant(ShAmt, MVT::i8));
11230 if (N->getNumValues() == 2) // Dead flag value?
11231 return DCI.CombineTo(N, Cond, SDValue());
11235 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
11236 // for any integer data type, including i8/i16.
11237 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11238 SDValue Cond = N->getOperand(3);
11239 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11240 DAG.getConstant(CC, MVT::i8), Cond);
11242 // Zero extend the condition if needed.
11243 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11244 FalseC->getValueType(0), Cond);
11245 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11246 SDValue(FalseC, 0));
11248 if (N->getNumValues() == 2) // Dead flag value?
11249 return DCI.CombineTo(N, Cond, SDValue());
11253 // Optimize cases that will turn into an LEA instruction. This requires
11254 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11255 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11256 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11257 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11259 bool isFastMultiplier = false;
11261 switch ((unsigned char)Diff) {
11263 case 1: // result = add base, cond
11264 case 2: // result = lea base( , cond*2)
11265 case 3: // result = lea base(cond, cond*2)
11266 case 4: // result = lea base( , cond*4)
11267 case 5: // result = lea base(cond, cond*4)
11268 case 8: // result = lea base( , cond*8)
11269 case 9: // result = lea base(cond, cond*8)
11270 isFastMultiplier = true;
11275 if (isFastMultiplier) {
11276 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11277 SDValue Cond = N->getOperand(3);
11278 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11279 DAG.getConstant(CC, MVT::i8), Cond);
11280 // Zero extend the condition if needed.
11281 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11283 // Scale the condition by the difference.
11285 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11286 DAG.getConstant(Diff, Cond.getValueType()));
11288 // Add the base if non-zero.
11289 if (FalseC->getAPIntValue() != 0)
11290 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11291 SDValue(FalseC, 0));
11292 if (N->getNumValues() == 2) // Dead flag value?
11293 return DCI.CombineTo(N, Cond, SDValue());
11303 /// PerformMulCombine - Optimize a single multiply with constant into two
11304 /// in order to implement it with two cheaper instructions, e.g.
11305 /// LEA + SHL, LEA + LEA.
11306 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11307 TargetLowering::DAGCombinerInfo &DCI) {
11308 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11311 EVT VT = N->getValueType(0);
11312 if (VT != MVT::i64)
11315 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11318 uint64_t MulAmt = C->getZExtValue();
11319 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11322 uint64_t MulAmt1 = 0;
11323 uint64_t MulAmt2 = 0;
11324 if ((MulAmt % 9) == 0) {
11326 MulAmt2 = MulAmt / 9;
11327 } else if ((MulAmt % 5) == 0) {
11329 MulAmt2 = MulAmt / 5;
11330 } else if ((MulAmt % 3) == 0) {
11332 MulAmt2 = MulAmt / 3;
11335 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11336 DebugLoc DL = N->getDebugLoc();
11338 if (isPowerOf2_64(MulAmt2) &&
11339 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11340 // If second multiplifer is pow2, issue it first. We want the multiply by
11341 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11343 std::swap(MulAmt1, MulAmt2);
11346 if (isPowerOf2_64(MulAmt1))
11347 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11348 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11350 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11351 DAG.getConstant(MulAmt1, VT));
11353 if (isPowerOf2_64(MulAmt2))
11354 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11355 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11357 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11358 DAG.getConstant(MulAmt2, VT));
11360 // Do not add new nodes to DAG combiner worklist.
11361 DCI.CombineTo(N, NewMul, false);
11366 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11367 SDValue N0 = N->getOperand(0);
11368 SDValue N1 = N->getOperand(1);
11369 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11370 EVT VT = N0.getValueType();
11372 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11373 // since the result of setcc_c is all zero's or all ones.
11374 if (N1C && N0.getOpcode() == ISD::AND &&
11375 N0.getOperand(1).getOpcode() == ISD::Constant) {
11376 SDValue N00 = N0.getOperand(0);
11377 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11378 ((N00.getOpcode() == ISD::ANY_EXTEND ||
11379 N00.getOpcode() == ISD::ZERO_EXTEND) &&
11380 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11381 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11382 APInt ShAmt = N1C->getAPIntValue();
11383 Mask = Mask.shl(ShAmt);
11385 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11386 N00, DAG.getConstant(Mask, VT));
11393 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11395 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11396 const X86Subtarget *Subtarget) {
11397 EVT VT = N->getValueType(0);
11398 if (!VT.isVector() && VT.isInteger() &&
11399 N->getOpcode() == ISD::SHL)
11400 return PerformSHLCombine(N, DAG);
11402 // On X86 with SSE2 support, we can transform this to a vector shift if
11403 // all elements are shifted by the same amount. We can't do this in legalize
11404 // because the a constant vector is typically transformed to a constant pool
11405 // so we have no knowledge of the shift amount.
11406 if (!Subtarget->hasSSE2())
11409 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11412 SDValue ShAmtOp = N->getOperand(1);
11413 EVT EltVT = VT.getVectorElementType();
11414 DebugLoc DL = N->getDebugLoc();
11415 SDValue BaseShAmt = SDValue();
11416 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11417 unsigned NumElts = VT.getVectorNumElements();
11419 for (; i != NumElts; ++i) {
11420 SDValue Arg = ShAmtOp.getOperand(i);
11421 if (Arg.getOpcode() == ISD::UNDEF) continue;
11425 for (; i != NumElts; ++i) {
11426 SDValue Arg = ShAmtOp.getOperand(i);
11427 if (Arg.getOpcode() == ISD::UNDEF) continue;
11428 if (Arg != BaseShAmt) {
11432 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11433 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11434 SDValue InVec = ShAmtOp.getOperand(0);
11435 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11436 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11438 for (; i != NumElts; ++i) {
11439 SDValue Arg = InVec.getOperand(i);
11440 if (Arg.getOpcode() == ISD::UNDEF) continue;
11444 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11445 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11446 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11447 if (C->getZExtValue() == SplatIdx)
11448 BaseShAmt = InVec.getOperand(1);
11451 if (BaseShAmt.getNode() == 0)
11452 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11453 DAG.getIntPtrConstant(0));
11457 // The shift amount is an i32.
11458 if (EltVT.bitsGT(MVT::i32))
11459 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11460 else if (EltVT.bitsLT(MVT::i32))
11461 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11463 // The shift amount is identical so we can do a vector shift.
11464 SDValue ValOp = N->getOperand(0);
11465 switch (N->getOpcode()) {
11467 llvm_unreachable("Unknown shift opcode!");
11470 if (VT == MVT::v2i64)
11471 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11472 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11474 if (VT == MVT::v4i32)
11475 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11476 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11478 if (VT == MVT::v8i16)
11479 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11480 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11484 if (VT == MVT::v4i32)
11485 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11486 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11488 if (VT == MVT::v8i16)
11489 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11490 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11494 if (VT == MVT::v2i64)
11495 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11496 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11498 if (VT == MVT::v4i32)
11499 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11500 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11502 if (VT == MVT::v8i16)
11503 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11504 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11512 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11513 TargetLowering::DAGCombinerInfo &DCI,
11514 const X86Subtarget *Subtarget) {
11515 if (DCI.isBeforeLegalizeOps())
11518 // Want to form PANDN nodes, in the hopes of then easily combining them with
11519 // OR and AND nodes to form PBLEND/PSIGN.
11520 EVT VT = N->getValueType(0);
11521 if (VT != MVT::v2i64)
11524 SDValue N0 = N->getOperand(0);
11525 SDValue N1 = N->getOperand(1);
11526 DebugLoc DL = N->getDebugLoc();
11528 // Check LHS for vnot
11529 if (N0.getOpcode() == ISD::XOR &&
11530 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11531 return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11533 // Check RHS for vnot
11534 if (N1.getOpcode() == ISD::XOR &&
11535 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11536 return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11541 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11542 TargetLowering::DAGCombinerInfo &DCI,
11543 const X86Subtarget *Subtarget) {
11544 if (DCI.isBeforeLegalizeOps())
11547 EVT VT = N->getValueType(0);
11548 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11551 SDValue N0 = N->getOperand(0);
11552 SDValue N1 = N->getOperand(1);
11554 // look for psign/blend
11555 if (Subtarget->hasSSSE3()) {
11556 if (VT == MVT::v2i64) {
11557 // Canonicalize pandn to RHS
11558 if (N0.getOpcode() == X86ISD::PANDN)
11560 // or (and (m, x), (pandn m, y))
11561 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11562 SDValue Mask = N1.getOperand(0);
11563 SDValue X = N1.getOperand(1);
11565 if (N0.getOperand(0) == Mask)
11566 Y = N0.getOperand(1);
11567 if (N0.getOperand(1) == Mask)
11568 Y = N0.getOperand(0);
11570 // Check to see if the mask appeared in both the AND and PANDN and
11574 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11575 if (Mask.getOpcode() != ISD::BITCAST ||
11576 X.getOpcode() != ISD::BITCAST ||
11577 Y.getOpcode() != ISD::BITCAST)
11580 // Look through mask bitcast.
11581 Mask = Mask.getOperand(0);
11582 EVT MaskVT = Mask.getValueType();
11584 // Validate that the Mask operand is a vector sra node. The sra node
11585 // will be an intrinsic.
11586 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11589 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11590 // there is no psrai.b
11591 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11592 case Intrinsic::x86_sse2_psrai_w:
11593 case Intrinsic::x86_sse2_psrai_d:
11595 default: return SDValue();
11598 // Check that the SRA is all signbits.
11599 SDValue SraC = Mask.getOperand(2);
11600 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
11601 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11602 if ((SraAmt + 1) != EltBits)
11605 DebugLoc DL = N->getDebugLoc();
11607 // Now we know we at least have a plendvb with the mask val. See if
11608 // we can form a psignb/w/d.
11609 // psign = x.type == y.type == mask.type && y = sub(0, x);
11610 X = X.getOperand(0);
11611 Y = Y.getOperand(0);
11612 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11613 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11614 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11617 case 8: Opc = X86ISD::PSIGNB; break;
11618 case 16: Opc = X86ISD::PSIGNW; break;
11619 case 32: Opc = X86ISD::PSIGND; break;
11623 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11624 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11627 // PBLENDVB only available on SSE 4.1
11628 if (!Subtarget->hasSSE41())
11631 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11632 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11633 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11634 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11635 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11640 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11641 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11643 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11645 if (!N0.hasOneUse() || !N1.hasOneUse())
11648 SDValue ShAmt0 = N0.getOperand(1);
11649 if (ShAmt0.getValueType() != MVT::i8)
11651 SDValue ShAmt1 = N1.getOperand(1);
11652 if (ShAmt1.getValueType() != MVT::i8)
11654 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11655 ShAmt0 = ShAmt0.getOperand(0);
11656 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11657 ShAmt1 = ShAmt1.getOperand(0);
11659 DebugLoc DL = N->getDebugLoc();
11660 unsigned Opc = X86ISD::SHLD;
11661 SDValue Op0 = N0.getOperand(0);
11662 SDValue Op1 = N1.getOperand(0);
11663 if (ShAmt0.getOpcode() == ISD::SUB) {
11664 Opc = X86ISD::SHRD;
11665 std::swap(Op0, Op1);
11666 std::swap(ShAmt0, ShAmt1);
11669 unsigned Bits = VT.getSizeInBits();
11670 if (ShAmt1.getOpcode() == ISD::SUB) {
11671 SDValue Sum = ShAmt1.getOperand(0);
11672 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11673 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11674 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11675 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11676 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11677 return DAG.getNode(Opc, DL, VT,
11679 DAG.getNode(ISD::TRUNCATE, DL,
11682 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11683 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11685 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11686 return DAG.getNode(Opc, DL, VT,
11687 N0.getOperand(0), N1.getOperand(0),
11688 DAG.getNode(ISD::TRUNCATE, DL,
11695 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11696 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11697 const X86Subtarget *Subtarget) {
11698 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
11699 // the FP state in cases where an emms may be missing.
11700 // A preferable solution to the general problem is to figure out the right
11701 // places to insert EMMS. This qualifies as a quick hack.
11703 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11704 StoreSDNode *St = cast<StoreSDNode>(N);
11705 EVT VT = St->getValue().getValueType();
11706 if (VT.getSizeInBits() != 64)
11709 const Function *F = DAG.getMachineFunction().getFunction();
11710 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11711 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11712 && Subtarget->hasSSE2();
11713 if ((VT.isVector() ||
11714 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11715 isa<LoadSDNode>(St->getValue()) &&
11716 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11717 St->getChain().hasOneUse() && !St->isVolatile()) {
11718 SDNode* LdVal = St->getValue().getNode();
11719 LoadSDNode *Ld = 0;
11720 int TokenFactorIndex = -1;
11721 SmallVector<SDValue, 8> Ops;
11722 SDNode* ChainVal = St->getChain().getNode();
11723 // Must be a store of a load. We currently handle two cases: the load
11724 // is a direct child, and it's under an intervening TokenFactor. It is
11725 // possible to dig deeper under nested TokenFactors.
11726 if (ChainVal == LdVal)
11727 Ld = cast<LoadSDNode>(St->getChain());
11728 else if (St->getValue().hasOneUse() &&
11729 ChainVal->getOpcode() == ISD::TokenFactor) {
11730 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11731 if (ChainVal->getOperand(i).getNode() == LdVal) {
11732 TokenFactorIndex = i;
11733 Ld = cast<LoadSDNode>(St->getValue());
11735 Ops.push_back(ChainVal->getOperand(i));
11739 if (!Ld || !ISD::isNormalLoad(Ld))
11742 // If this is not the MMX case, i.e. we are just turning i64 load/store
11743 // into f64 load/store, avoid the transformation if there are multiple
11744 // uses of the loaded value.
11745 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11748 DebugLoc LdDL = Ld->getDebugLoc();
11749 DebugLoc StDL = N->getDebugLoc();
11750 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11751 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11753 if (Subtarget->is64Bit() || F64IsLegal) {
11754 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11755 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11756 Ld->getPointerInfo(), Ld->isVolatile(),
11757 Ld->isNonTemporal(), Ld->getAlignment());
11758 SDValue NewChain = NewLd.getValue(1);
11759 if (TokenFactorIndex != -1) {
11760 Ops.push_back(NewChain);
11761 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11764 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11765 St->getPointerInfo(),
11766 St->isVolatile(), St->isNonTemporal(),
11767 St->getAlignment());
11770 // Otherwise, lower to two pairs of 32-bit loads / stores.
11771 SDValue LoAddr = Ld->getBasePtr();
11772 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11773 DAG.getConstant(4, MVT::i32));
11775 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11776 Ld->getPointerInfo(),
11777 Ld->isVolatile(), Ld->isNonTemporal(),
11778 Ld->getAlignment());
11779 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11780 Ld->getPointerInfo().getWithOffset(4),
11781 Ld->isVolatile(), Ld->isNonTemporal(),
11782 MinAlign(Ld->getAlignment(), 4));
11784 SDValue NewChain = LoLd.getValue(1);
11785 if (TokenFactorIndex != -1) {
11786 Ops.push_back(LoLd);
11787 Ops.push_back(HiLd);
11788 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11792 LoAddr = St->getBasePtr();
11793 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11794 DAG.getConstant(4, MVT::i32));
11796 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11797 St->getPointerInfo(),
11798 St->isVolatile(), St->isNonTemporal(),
11799 St->getAlignment());
11800 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11801 St->getPointerInfo().getWithOffset(4),
11803 St->isNonTemporal(),
11804 MinAlign(St->getAlignment(), 4));
11805 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11810 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11811 /// X86ISD::FXOR nodes.
11812 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11813 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11814 // F[X]OR(0.0, x) -> x
11815 // F[X]OR(x, 0.0) -> x
11816 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11817 if (C->getValueAPF().isPosZero())
11818 return N->getOperand(1);
11819 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11820 if (C->getValueAPF().isPosZero())
11821 return N->getOperand(0);
11825 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11826 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11827 // FAND(0.0, x) -> 0.0
11828 // FAND(x, 0.0) -> 0.0
11829 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11830 if (C->getValueAPF().isPosZero())
11831 return N->getOperand(0);
11832 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11833 if (C->getValueAPF().isPosZero())
11834 return N->getOperand(1);
11838 static SDValue PerformBTCombine(SDNode *N,
11840 TargetLowering::DAGCombinerInfo &DCI) {
11841 // BT ignores high bits in the bit index operand.
11842 SDValue Op1 = N->getOperand(1);
11843 if (Op1.hasOneUse()) {
11844 unsigned BitWidth = Op1.getValueSizeInBits();
11845 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11846 APInt KnownZero, KnownOne;
11847 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11848 !DCI.isBeforeLegalizeOps());
11849 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11850 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11851 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11852 DCI.CommitTargetLoweringOpt(TLO);
11857 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11858 SDValue Op = N->getOperand(0);
11859 if (Op.getOpcode() == ISD::BITCAST)
11860 Op = Op.getOperand(0);
11861 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11862 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11863 VT.getVectorElementType().getSizeInBits() ==
11864 OpVT.getVectorElementType().getSizeInBits()) {
11865 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11870 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11871 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
11872 // (and (i32 x86isd::setcc_carry), 1)
11873 // This eliminates the zext. This transformation is necessary because
11874 // ISD::SETCC is always legalized to i8.
11875 DebugLoc dl = N->getDebugLoc();
11876 SDValue N0 = N->getOperand(0);
11877 EVT VT = N->getValueType(0);
11878 if (N0.getOpcode() == ISD::AND &&
11880 N0.getOperand(0).hasOneUse()) {
11881 SDValue N00 = N0.getOperand(0);
11882 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11884 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11885 if (!C || C->getZExtValue() != 1)
11887 return DAG.getNode(ISD::AND, dl, VT,
11888 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11889 N00.getOperand(0), N00.getOperand(1)),
11890 DAG.getConstant(1, VT));
11896 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
11897 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
11898 unsigned X86CC = N->getConstantOperandVal(0);
11899 SDValue EFLAG = N->getOperand(1);
11900 DebugLoc DL = N->getDebugLoc();
11902 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
11903 // a zext and produces an all-ones bit which is more useful than 0/1 in some
11905 if (X86CC == X86::COND_B)
11906 return DAG.getNode(ISD::AND, DL, MVT::i8,
11907 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
11908 DAG.getConstant(X86CC, MVT::i8), EFLAG),
11909 DAG.getConstant(1, MVT::i8));
11914 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
11915 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
11916 X86TargetLowering::DAGCombinerInfo &DCI) {
11917 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
11918 // the result is either zero or one (depending on the input carry bit).
11919 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
11920 if (X86::isZeroNode(N->getOperand(0)) &&
11921 X86::isZeroNode(N->getOperand(1)) &&
11922 // We don't have a good way to replace an EFLAGS use, so only do this when
11924 SDValue(N, 1).use_empty()) {
11925 DebugLoc DL = N->getDebugLoc();
11926 EVT VT = N->getValueType(0);
11927 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
11928 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
11929 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
11930 DAG.getConstant(X86::COND_B,MVT::i8),
11932 DAG.getConstant(1, VT));
11933 return DCI.CombineTo(N, Res1, CarryOut);
11939 // fold (add Y, (sete X, 0)) -> adc 0, Y
11940 // (add Y, (setne X, 0)) -> sbb -1, Y
11941 // (sub (sete X, 0), Y) -> sbb 0, Y
11942 // (sub (setne X, 0), Y) -> adc -1, Y
11943 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
11944 DebugLoc DL = N->getDebugLoc();
11946 // Look through ZExts.
11947 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
11948 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
11951 SDValue SetCC = Ext.getOperand(0);
11952 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
11955 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
11956 if (CC != X86::COND_E && CC != X86::COND_NE)
11959 SDValue Cmp = SetCC.getOperand(1);
11960 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
11961 !X86::isZeroNode(Cmp.getOperand(1)) ||
11962 !Cmp.getOperand(0).getValueType().isInteger())
11965 SDValue CmpOp0 = Cmp.getOperand(0);
11966 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
11967 DAG.getConstant(1, CmpOp0.getValueType()));
11969 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
11970 if (CC == X86::COND_NE)
11971 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
11972 DL, OtherVal.getValueType(), OtherVal,
11973 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
11974 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
11975 DL, OtherVal.getValueType(), OtherVal,
11976 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
11979 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
11980 DAGCombinerInfo &DCI) const {
11981 SelectionDAG &DAG = DCI.DAG;
11982 switch (N->getOpcode()) {
11984 case ISD::EXTRACT_VECTOR_ELT:
11985 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11986 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
11987 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
11989 case ISD::SUB: return OptimizeConditonalInDecrement(N, DAG);
11990 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
11991 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
11994 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
11995 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
11996 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
11997 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
11999 case X86ISD::FOR: return PerformFORCombine(N, DAG);
12000 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
12001 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
12002 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
12003 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
12004 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
12005 case X86ISD::SHUFPS: // Handle all target specific shuffles
12006 case X86ISD::SHUFPD:
12007 case X86ISD::PALIGN:
12008 case X86ISD::PUNPCKHBW:
12009 case X86ISD::PUNPCKHWD:
12010 case X86ISD::PUNPCKHDQ:
12011 case X86ISD::PUNPCKHQDQ:
12012 case X86ISD::UNPCKHPS:
12013 case X86ISD::UNPCKHPD:
12014 case X86ISD::PUNPCKLBW:
12015 case X86ISD::PUNPCKLWD:
12016 case X86ISD::PUNPCKLDQ:
12017 case X86ISD::PUNPCKLQDQ:
12018 case X86ISD::UNPCKLPS:
12019 case X86ISD::UNPCKLPD:
12020 case X86ISD::VUNPCKLPS:
12021 case X86ISD::VUNPCKLPD:
12022 case X86ISD::VUNPCKLPSY:
12023 case X86ISD::VUNPCKLPDY:
12024 case X86ISD::MOVHLPS:
12025 case X86ISD::MOVLHPS:
12026 case X86ISD::PSHUFD:
12027 case X86ISD::PSHUFHW:
12028 case X86ISD::PSHUFLW:
12029 case X86ISD::MOVSS:
12030 case X86ISD::MOVSD:
12031 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12037 /// isTypeDesirableForOp - Return true if the target has native support for
12038 /// the specified value type and it is 'desirable' to use the type for the
12039 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12040 /// instruction encodings are longer and some i16 instructions are slow.
12041 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12042 if (!isTypeLegal(VT))
12044 if (VT != MVT::i16)
12051 case ISD::SIGN_EXTEND:
12052 case ISD::ZERO_EXTEND:
12053 case ISD::ANY_EXTEND:
12066 /// IsDesirableToPromoteOp - This method query the target whether it is
12067 /// beneficial for dag combiner to promote the specified node. If true, it
12068 /// should return the desired promotion type by reference.
12069 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12070 EVT VT = Op.getValueType();
12071 if (VT != MVT::i16)
12074 bool Promote = false;
12075 bool Commute = false;
12076 switch (Op.getOpcode()) {
12079 LoadSDNode *LD = cast<LoadSDNode>(Op);
12080 // If the non-extending load has a single use and it's not live out, then it
12081 // might be folded.
12082 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12083 Op.hasOneUse()*/) {
12084 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12085 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12086 // The only case where we'd want to promote LOAD (rather then it being
12087 // promoted as an operand is when it's only use is liveout.
12088 if (UI->getOpcode() != ISD::CopyToReg)
12095 case ISD::SIGN_EXTEND:
12096 case ISD::ZERO_EXTEND:
12097 case ISD::ANY_EXTEND:
12102 SDValue N0 = Op.getOperand(0);
12103 // Look out for (store (shl (load), x)).
12104 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12117 SDValue N0 = Op.getOperand(0);
12118 SDValue N1 = Op.getOperand(1);
12119 if (!Commute && MayFoldLoad(N1))
12121 // Avoid disabling potential load folding opportunities.
12122 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12124 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12134 //===----------------------------------------------------------------------===//
12135 // X86 Inline Assembly Support
12136 //===----------------------------------------------------------------------===//
12138 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12139 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12141 std::string AsmStr = IA->getAsmString();
12143 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12144 SmallVector<StringRef, 4> AsmPieces;
12145 SplitString(AsmStr, AsmPieces, ";\n");
12147 switch (AsmPieces.size()) {
12148 default: return false;
12150 AsmStr = AsmPieces[0];
12152 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
12154 // FIXME: this should verify that we are targetting a 486 or better. If not,
12155 // we will turn this bswap into something that will be lowered to logical ops
12156 // instead of emitting the bswap asm. For now, we don't support 486 or lower
12157 // so don't worry about this.
12159 if (AsmPieces.size() == 2 &&
12160 (AsmPieces[0] == "bswap" ||
12161 AsmPieces[0] == "bswapq" ||
12162 AsmPieces[0] == "bswapl") &&
12163 (AsmPieces[1] == "$0" ||
12164 AsmPieces[1] == "${0:q}")) {
12165 // No need to check constraints, nothing other than the equivalent of
12166 // "=r,0" would be valid here.
12167 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12168 if (!Ty || Ty->getBitWidth() % 16 != 0)
12170 return IntrinsicLowering::LowerToByteSwap(CI);
12172 // rorw $$8, ${0:w} --> llvm.bswap.i16
12173 if (CI->getType()->isIntegerTy(16) &&
12174 AsmPieces.size() == 3 &&
12175 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12176 AsmPieces[1] == "$$8," &&
12177 AsmPieces[2] == "${0:w}" &&
12178 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12180 const std::string &ConstraintsStr = IA->getConstraintString();
12181 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12182 std::sort(AsmPieces.begin(), AsmPieces.end());
12183 if (AsmPieces.size() == 4 &&
12184 AsmPieces[0] == "~{cc}" &&
12185 AsmPieces[1] == "~{dirflag}" &&
12186 AsmPieces[2] == "~{flags}" &&
12187 AsmPieces[3] == "~{fpsr}") {
12188 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12189 if (!Ty || Ty->getBitWidth() % 16 != 0)
12191 return IntrinsicLowering::LowerToByteSwap(CI);
12196 if (CI->getType()->isIntegerTy(32) &&
12197 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12198 SmallVector<StringRef, 4> Words;
12199 SplitString(AsmPieces[0], Words, " \t,");
12200 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12201 Words[2] == "${0:w}") {
12203 SplitString(AsmPieces[1], Words, " \t,");
12204 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12205 Words[2] == "$0") {
12207 SplitString(AsmPieces[2], Words, " \t,");
12208 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12209 Words[2] == "${0:w}") {
12211 const std::string &ConstraintsStr = IA->getConstraintString();
12212 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12213 std::sort(AsmPieces.begin(), AsmPieces.end());
12214 if (AsmPieces.size() == 4 &&
12215 AsmPieces[0] == "~{cc}" &&
12216 AsmPieces[1] == "~{dirflag}" &&
12217 AsmPieces[2] == "~{flags}" &&
12218 AsmPieces[3] == "~{fpsr}") {
12219 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12220 if (!Ty || Ty->getBitWidth() % 16 != 0)
12222 return IntrinsicLowering::LowerToByteSwap(CI);
12229 if (CI->getType()->isIntegerTy(64)) {
12230 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12231 if (Constraints.size() >= 2 &&
12232 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12233 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12234 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
12235 SmallVector<StringRef, 4> Words;
12236 SplitString(AsmPieces[0], Words, " \t");
12237 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12239 SplitString(AsmPieces[1], Words, " \t");
12240 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12242 SplitString(AsmPieces[2], Words, " \t,");
12243 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12244 Words[2] == "%edx") {
12245 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12246 if (!Ty || Ty->getBitWidth() % 16 != 0)
12248 return IntrinsicLowering::LowerToByteSwap(CI);
12261 /// getConstraintType - Given a constraint letter, return the type of
12262 /// constraint it is for this target.
12263 X86TargetLowering::ConstraintType
12264 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12265 if (Constraint.size() == 1) {
12266 switch (Constraint[0]) {
12276 return C_RegisterClass;
12300 return TargetLowering::getConstraintType(Constraint);
12303 /// Examine constraint type and operand type and determine a weight value.
12304 /// This object must already have been set up with the operand type
12305 /// and the current alternative constraint selected.
12306 TargetLowering::ConstraintWeight
12307 X86TargetLowering::getSingleConstraintMatchWeight(
12308 AsmOperandInfo &info, const char *constraint) const {
12309 ConstraintWeight weight = CW_Invalid;
12310 Value *CallOperandVal = info.CallOperandVal;
12311 // If we don't have a value, we can't do a match,
12312 // but allow it at the lowest weight.
12313 if (CallOperandVal == NULL)
12315 const Type *type = CallOperandVal->getType();
12316 // Look at the constraint type.
12317 switch (*constraint) {
12319 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12330 if (CallOperandVal->getType()->isIntegerTy())
12331 weight = CW_SpecificReg;
12336 if (type->isFloatingPointTy())
12337 weight = CW_SpecificReg;
12340 if (type->isX86_MMXTy() && Subtarget->hasMMX())
12341 weight = CW_SpecificReg;
12345 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12346 weight = CW_Register;
12349 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12350 if (C->getZExtValue() <= 31)
12351 weight = CW_Constant;
12355 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12356 if (C->getZExtValue() <= 63)
12357 weight = CW_Constant;
12361 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12362 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12363 weight = CW_Constant;
12367 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12368 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12369 weight = CW_Constant;
12373 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12374 if (C->getZExtValue() <= 3)
12375 weight = CW_Constant;
12379 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12380 if (C->getZExtValue() <= 0xff)
12381 weight = CW_Constant;
12386 if (dyn_cast<ConstantFP>(CallOperandVal)) {
12387 weight = CW_Constant;
12391 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12392 if ((C->getSExtValue() >= -0x80000000LL) &&
12393 (C->getSExtValue() <= 0x7fffffffLL))
12394 weight = CW_Constant;
12398 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12399 if (C->getZExtValue() <= 0xffffffff)
12400 weight = CW_Constant;
12407 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12408 /// with another that has more specific requirements based on the type of the
12409 /// corresponding operand.
12410 const char *X86TargetLowering::
12411 LowerXConstraint(EVT ConstraintVT) const {
12412 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12413 // 'f' like normal targets.
12414 if (ConstraintVT.isFloatingPoint()) {
12415 if (Subtarget->hasXMMInt())
12417 if (Subtarget->hasXMM())
12421 return TargetLowering::LowerXConstraint(ConstraintVT);
12424 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12425 /// vector. If it is invalid, don't add anything to Ops.
12426 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12428 std::vector<SDValue>&Ops,
12429 SelectionDAG &DAG) const {
12430 SDValue Result(0, 0);
12432 switch (Constraint) {
12435 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12436 if (C->getZExtValue() <= 31) {
12437 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12443 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12444 if (C->getZExtValue() <= 63) {
12445 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12451 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12452 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12453 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12459 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12460 if (C->getZExtValue() <= 255) {
12461 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12467 // 32-bit signed value
12468 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12469 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12470 C->getSExtValue())) {
12471 // Widen to 64 bits here to get it sign extended.
12472 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12475 // FIXME gcc accepts some relocatable values here too, but only in certain
12476 // memory models; it's complicated.
12481 // 32-bit unsigned value
12482 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12483 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12484 C->getZExtValue())) {
12485 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12489 // FIXME gcc accepts some relocatable values here too, but only in certain
12490 // memory models; it's complicated.
12494 // Literal immediates are always ok.
12495 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12496 // Widen to 64 bits here to get it sign extended.
12497 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12501 // In any sort of PIC mode addresses need to be computed at runtime by
12502 // adding in a register or some sort of table lookup. These can't
12503 // be used as immediates.
12504 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12507 // If we are in non-pic codegen mode, we allow the address of a global (with
12508 // an optional displacement) to be used with 'i'.
12509 GlobalAddressSDNode *GA = 0;
12510 int64_t Offset = 0;
12512 // Match either (GA), (GA+C), (GA+C1+C2), etc.
12514 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12515 Offset += GA->getOffset();
12517 } else if (Op.getOpcode() == ISD::ADD) {
12518 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12519 Offset += C->getZExtValue();
12520 Op = Op.getOperand(0);
12523 } else if (Op.getOpcode() == ISD::SUB) {
12524 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12525 Offset += -C->getZExtValue();
12526 Op = Op.getOperand(0);
12531 // Otherwise, this isn't something we can handle, reject it.
12535 const GlobalValue *GV = GA->getGlobal();
12536 // If we require an extra load to get this address, as in PIC mode, we
12537 // can't accept it.
12538 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12539 getTargetMachine())))
12542 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12543 GA->getValueType(0), Offset);
12548 if (Result.getNode()) {
12549 Ops.push_back(Result);
12552 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12555 std::vector<unsigned> X86TargetLowering::
12556 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12558 if (Constraint.size() == 1) {
12559 // FIXME: not handling fp-stack yet!
12560 switch (Constraint[0]) { // GCC X86 Constraint Letters
12561 default: break; // Unknown constraint letter
12562 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12563 if (Subtarget->is64Bit()) {
12564 if (VT == MVT::i32)
12565 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12566 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12567 X86::R10D,X86::R11D,X86::R12D,
12568 X86::R13D,X86::R14D,X86::R15D,
12569 X86::EBP, X86::ESP, 0);
12570 else if (VT == MVT::i16)
12571 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
12572 X86::SI, X86::DI, X86::R8W,X86::R9W,
12573 X86::R10W,X86::R11W,X86::R12W,
12574 X86::R13W,X86::R14W,X86::R15W,
12575 X86::BP, X86::SP, 0);
12576 else if (VT == MVT::i8)
12577 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
12578 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12579 X86::R10B,X86::R11B,X86::R12B,
12580 X86::R13B,X86::R14B,X86::R15B,
12581 X86::BPL, X86::SPL, 0);
12583 else if (VT == MVT::i64)
12584 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12585 X86::RSI, X86::RDI, X86::R8, X86::R9,
12586 X86::R10, X86::R11, X86::R12,
12587 X86::R13, X86::R14, X86::R15,
12588 X86::RBP, X86::RSP, 0);
12592 // 32-bit fallthrough
12593 case 'Q': // Q_REGS
12594 if (VT == MVT::i32)
12595 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12596 else if (VT == MVT::i16)
12597 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12598 else if (VT == MVT::i8)
12599 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12600 else if (VT == MVT::i64)
12601 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12606 return std::vector<unsigned>();
12609 std::pair<unsigned, const TargetRegisterClass*>
12610 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12612 // First, see if this is a constraint that directly corresponds to an LLVM
12614 if (Constraint.size() == 1) {
12615 // GCC Constraint Letters
12616 switch (Constraint[0]) {
12618 case 'r': // GENERAL_REGS
12619 case 'l': // INDEX_REGS
12621 return std::make_pair(0U, X86::GR8RegisterClass);
12622 if (VT == MVT::i16)
12623 return std::make_pair(0U, X86::GR16RegisterClass);
12624 if (VT == MVT::i32 || !Subtarget->is64Bit())
12625 return std::make_pair(0U, X86::GR32RegisterClass);
12626 return std::make_pair(0U, X86::GR64RegisterClass);
12627 case 'R': // LEGACY_REGS
12629 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12630 if (VT == MVT::i16)
12631 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12632 if (VT == MVT::i32 || !Subtarget->is64Bit())
12633 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12634 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12635 case 'f': // FP Stack registers.
12636 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12637 // value to the correct fpstack register class.
12638 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12639 return std::make_pair(0U, X86::RFP32RegisterClass);
12640 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12641 return std::make_pair(0U, X86::RFP64RegisterClass);
12642 return std::make_pair(0U, X86::RFP80RegisterClass);
12643 case 'y': // MMX_REGS if MMX allowed.
12644 if (!Subtarget->hasMMX()) break;
12645 return std::make_pair(0U, X86::VR64RegisterClass);
12646 case 'Y': // SSE_REGS if SSE2 allowed
12647 if (!Subtarget->hasXMMInt()) break;
12649 case 'x': // SSE_REGS if SSE1 allowed
12650 if (!Subtarget->hasXMM()) break;
12652 switch (VT.getSimpleVT().SimpleTy) {
12654 // Scalar SSE types.
12657 return std::make_pair(0U, X86::FR32RegisterClass);
12660 return std::make_pair(0U, X86::FR64RegisterClass);
12668 return std::make_pair(0U, X86::VR128RegisterClass);
12674 // Use the default implementation in TargetLowering to convert the register
12675 // constraint into a member of a register class.
12676 std::pair<unsigned, const TargetRegisterClass*> Res;
12677 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12679 // Not found as a standard register?
12680 if (Res.second == 0) {
12681 // Map st(0) -> st(7) -> ST0
12682 if (Constraint.size() == 7 && Constraint[0] == '{' &&
12683 tolower(Constraint[1]) == 's' &&
12684 tolower(Constraint[2]) == 't' &&
12685 Constraint[3] == '(' &&
12686 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12687 Constraint[5] == ')' &&
12688 Constraint[6] == '}') {
12690 Res.first = X86::ST0+Constraint[4]-'0';
12691 Res.second = X86::RFP80RegisterClass;
12695 // GCC allows "st(0)" to be called just plain "st".
12696 if (StringRef("{st}").equals_lower(Constraint)) {
12697 Res.first = X86::ST0;
12698 Res.second = X86::RFP80RegisterClass;
12703 if (StringRef("{flags}").equals_lower(Constraint)) {
12704 Res.first = X86::EFLAGS;
12705 Res.second = X86::CCRRegisterClass;
12709 // 'A' means EAX + EDX.
12710 if (Constraint == "A") {
12711 Res.first = X86::EAX;
12712 Res.second = X86::GR32_ADRegisterClass;
12718 // Otherwise, check to see if this is a register class of the wrong value
12719 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12720 // turn into {ax},{dx}.
12721 if (Res.second->hasType(VT))
12722 return Res; // Correct type already, nothing to do.
12724 // All of the single-register GCC register classes map their values onto
12725 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
12726 // really want an 8-bit or 32-bit register, map to the appropriate register
12727 // class and return the appropriate register.
12728 if (Res.second == X86::GR16RegisterClass) {
12729 if (VT == MVT::i8) {
12730 unsigned DestReg = 0;
12731 switch (Res.first) {
12733 case X86::AX: DestReg = X86::AL; break;
12734 case X86::DX: DestReg = X86::DL; break;
12735 case X86::CX: DestReg = X86::CL; break;
12736 case X86::BX: DestReg = X86::BL; break;
12739 Res.first = DestReg;
12740 Res.second = X86::GR8RegisterClass;
12742 } else if (VT == MVT::i32) {
12743 unsigned DestReg = 0;
12744 switch (Res.first) {
12746 case X86::AX: DestReg = X86::EAX; break;
12747 case X86::DX: DestReg = X86::EDX; break;
12748 case X86::CX: DestReg = X86::ECX; break;
12749 case X86::BX: DestReg = X86::EBX; break;
12750 case X86::SI: DestReg = X86::ESI; break;
12751 case X86::DI: DestReg = X86::EDI; break;
12752 case X86::BP: DestReg = X86::EBP; break;
12753 case X86::SP: DestReg = X86::ESP; break;
12756 Res.first = DestReg;
12757 Res.second = X86::GR32RegisterClass;
12759 } else if (VT == MVT::i64) {
12760 unsigned DestReg = 0;
12761 switch (Res.first) {
12763 case X86::AX: DestReg = X86::RAX; break;
12764 case X86::DX: DestReg = X86::RDX; break;
12765 case X86::CX: DestReg = X86::RCX; break;
12766 case X86::BX: DestReg = X86::RBX; break;
12767 case X86::SI: DestReg = X86::RSI; break;
12768 case X86::DI: DestReg = X86::RDI; break;
12769 case X86::BP: DestReg = X86::RBP; break;
12770 case X86::SP: DestReg = X86::RSP; break;
12773 Res.first = DestReg;
12774 Res.second = X86::GR64RegisterClass;
12777 } else if (Res.second == X86::FR32RegisterClass ||
12778 Res.second == X86::FR64RegisterClass ||
12779 Res.second == X86::VR128RegisterClass) {
12780 // Handle references to XMM physical registers that got mapped into the
12781 // wrong class. This can happen with constraints like {xmm0} where the
12782 // target independent register mapper will just pick the first match it can
12783 // find, ignoring the required type.
12784 if (VT == MVT::f32)
12785 Res.second = X86::FR32RegisterClass;
12786 else if (VT == MVT::f64)
12787 Res.second = X86::FR64RegisterClass;
12788 else if (X86::VR128RegisterClass->hasType(VT))
12789 Res.second = X86::VR128RegisterClass;