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 "X86ShuffleDecode.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.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/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
55 using namespace dwarf;
57 STATISTIC(NumTailCalls, "Number of tail calls");
60 Disable256Bit("disable-256bit", cl::Hidden,
61 cl::desc("Disable use of 256-bit vectors"));
63 // Forward declarations.
64 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
67 static SDValue Insert128BitVector(SDValue Result,
73 static SDValue Extract128BitVector(SDValue Vec,
78 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
81 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
82 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
83 /// simple subregister reference.
84 static SDValue Extract128BitVector(SDValue Vec,
88 EVT VT = Vec.getValueType();
89 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
91 EVT ElVT = VT.getVectorElementType();
93 int Factor = VT.getSizeInBits() / 128;
95 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(),
97 VT.getVectorNumElements() / Factor);
99 // Extract from UNDEF is UNDEF.
100 if (Vec.getOpcode() == ISD::UNDEF)
101 return DAG.getNode(ISD::UNDEF, dl, ResultVT);
103 if (isa<ConstantSDNode>(Idx)) {
104 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
106 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
107 // we can match to VEXTRACTF128.
108 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
110 // This is the index of the first element of the 128-bit chunk
112 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
115 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
117 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
126 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
127 /// sets things up to match to an AVX VINSERTF128 instruction or a
128 /// simple superregister reference.
129 static SDValue Insert128BitVector(SDValue Result,
134 if (isa<ConstantSDNode>(Idx)) {
135 EVT VT = Vec.getValueType();
136 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
138 EVT ElVT = VT.getVectorElementType();
140 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
142 EVT ResultVT = Result.getValueType();
144 // Insert the relevant 128 bits.
145 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
147 // This is the index of the first element of the 128-bit chunk
149 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
152 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
154 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
162 /// Given two vectors, concat them.
163 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
164 DebugLoc dl = Lower.getDebugLoc();
166 assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
168 EVT VT = EVT::getVectorVT(*DAG.getContext(),
169 Lower.getValueType().getVectorElementType(),
170 Lower.getValueType().getVectorNumElements() * 2);
172 // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
173 assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
175 // Insert the upper subvector.
176 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
178 // This is half the length of the result
179 // vector. Start inserting the upper 128
181 Lower.getValueType().getVectorNumElements(),
185 // Insert the lower subvector.
186 Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
190 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
191 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
192 bool is64Bit = Subtarget->is64Bit();
194 if (Subtarget->isTargetEnvMacho()) {
196 return new X8664_MachoTargetObjectFile();
197 return new TargetLoweringObjectFileMachO();
200 if (Subtarget->isTargetELF()) {
202 return new X8664_ELFTargetObjectFile(TM);
203 return new X8632_ELFTargetObjectFile(TM);
205 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
206 return new TargetLoweringObjectFileCOFF();
207 llvm_unreachable("unknown subtarget type");
210 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
211 : TargetLowering(TM, createTLOF(TM)) {
212 Subtarget = &TM.getSubtarget<X86Subtarget>();
213 X86ScalarSSEf64 = Subtarget->hasXMMInt();
214 X86ScalarSSEf32 = Subtarget->hasXMM();
215 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
217 RegInfo = TM.getRegisterInfo();
218 TD = getTargetData();
220 // Set up the TargetLowering object.
221 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
223 // X86 is weird, it always uses i8 for shift amounts and setcc results.
224 setShiftAmountType(MVT::i8);
225 setBooleanContents(ZeroOrOneBooleanContent);
226 setSchedulingPreference(Sched::RegPressure);
227 setStackPointerRegisterToSaveRestore(X86StackPtr);
229 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
230 // Setup Windows compiler runtime calls.
231 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
232 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
233 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
234 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
235 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
236 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
237 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
238 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
241 if (Subtarget->isTargetDarwin()) {
242 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
243 setUseUnderscoreSetJmp(false);
244 setUseUnderscoreLongJmp(false);
245 } else if (Subtarget->isTargetMingw()) {
246 // MS runtime is weird: it exports _setjmp, but longjmp!
247 setUseUnderscoreSetJmp(true);
248 setUseUnderscoreLongJmp(false);
250 setUseUnderscoreSetJmp(true);
251 setUseUnderscoreLongJmp(true);
254 // Set up the register classes.
255 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
256 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
257 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
258 if (Subtarget->is64Bit())
259 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
261 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
263 // We don't accept any truncstore of integer registers.
264 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
265 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
266 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
267 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
268 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
269 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
271 // SETOEQ and SETUNE require checking two conditions.
272 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
273 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
274 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
275 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
276 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
277 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
279 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
281 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
282 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
283 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
285 if (Subtarget->is64Bit()) {
286 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
287 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
288 } else if (!UseSoftFloat) {
289 // We have an algorithm for SSE2->double, and we turn this into a
290 // 64-bit FILD followed by conditional FADD for other targets.
291 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
292 // We have an algorithm for SSE2, and we turn this into a 64-bit
293 // FILD for other targets.
294 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
297 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
299 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
300 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
303 // SSE has no i16 to fp conversion, only i32
304 if (X86ScalarSSEf32) {
305 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
306 // f32 and f64 cases are Legal, f80 case is not
307 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
309 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
310 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
313 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
314 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
317 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
318 // are Legal, f80 is custom lowered.
319 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
320 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
322 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
324 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
325 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
327 if (X86ScalarSSEf32) {
328 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
329 // f32 and f64 cases are Legal, f80 case is not
330 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
332 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
333 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
336 // Handle FP_TO_UINT by promoting the destination to a larger signed
338 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
339 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
340 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
342 if (Subtarget->is64Bit()) {
343 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
344 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
345 } else if (!UseSoftFloat) {
346 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
347 // Expand FP_TO_UINT into a select.
348 // FIXME: We would like to use a Custom expander here eventually to do
349 // the optimal thing for SSE vs. the default expansion in the legalizer.
350 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
352 // With SSE3 we can use fisttpll to convert to a signed i64; without
353 // SSE, we're stuck with a fistpll.
354 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
357 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
358 if (!X86ScalarSSEf64) {
359 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
360 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
361 if (Subtarget->is64Bit()) {
362 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
363 // Without SSE, i64->f64 goes through memory.
364 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
368 // Scalar integer divide and remainder are lowered to use operations that
369 // produce two results, to match the available instructions. This exposes
370 // the two-result form to trivial CSE, which is able to combine x/y and x%y
371 // into a single instruction.
373 // Scalar integer multiply-high is also lowered to use two-result
374 // operations, to match the available instructions. However, plain multiply
375 // (low) operations are left as Legal, as there are single-result
376 // instructions for this in x86. Using the two-result multiply instructions
377 // when both high and low results are needed must be arranged by dagcombine.
378 for (unsigned i = 0, e = 4; i != e; ++i) {
380 setOperationAction(ISD::MULHS, VT, Expand);
381 setOperationAction(ISD::MULHU, VT, Expand);
382 setOperationAction(ISD::SDIV, VT, Expand);
383 setOperationAction(ISD::UDIV, VT, Expand);
384 setOperationAction(ISD::SREM, VT, Expand);
385 setOperationAction(ISD::UREM, VT, Expand);
387 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
388 setOperationAction(ISD::ADDC, VT, Custom);
389 setOperationAction(ISD::ADDE, VT, Custom);
390 setOperationAction(ISD::SUBC, VT, Custom);
391 setOperationAction(ISD::SUBE, VT, Custom);
394 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
395 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
396 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
397 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
398 if (Subtarget->is64Bit())
399 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
400 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
401 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
402 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
403 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
404 setOperationAction(ISD::FREM , MVT::f32 , Expand);
405 setOperationAction(ISD::FREM , MVT::f64 , Expand);
406 setOperationAction(ISD::FREM , MVT::f80 , Expand);
407 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
409 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
410 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
411 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
412 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
413 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
414 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
415 if (Subtarget->is64Bit()) {
416 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
417 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
420 if (Subtarget->hasPOPCNT()) {
421 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
423 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
424 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
425 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
426 if (Subtarget->is64Bit())
427 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
430 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
431 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
433 // These should be promoted to a larger select which is supported.
434 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
435 // X86 wants to expand cmov itself.
436 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
437 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
438 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
439 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
440 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
441 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
442 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
443 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
444 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
445 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
446 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
447 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
448 if (Subtarget->is64Bit()) {
449 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
450 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
452 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
455 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
456 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
457 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
458 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
459 if (Subtarget->is64Bit())
460 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
461 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
462 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
463 if (Subtarget->is64Bit()) {
464 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
465 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
466 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
467 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
468 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
470 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
471 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
472 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
473 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
474 if (Subtarget->is64Bit()) {
475 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
476 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
477 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
480 if (Subtarget->hasXMM())
481 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
483 // We may not have a libcall for MEMBARRIER so we should lower this.
484 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
486 // On X86 and X86-64, atomic operations are lowered to locked instructions.
487 // Locked instructions, in turn, have implicit fence semantics (all memory
488 // operations are flushed before issuing the locked instruction, and they
489 // are not buffered), so we can fold away the common pattern of
490 // fence-atomic-fence.
491 setShouldFoldAtomicFences(true);
493 // Expand certain atomics
494 for (unsigned i = 0, e = 4; i != e; ++i) {
496 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
497 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
500 if (!Subtarget->is64Bit()) {
501 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
502 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
503 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
504 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
505 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
506 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
507 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
510 // FIXME - use subtarget debug flags
511 if (!Subtarget->isTargetDarwin() &&
512 !Subtarget->isTargetELF() &&
513 !Subtarget->isTargetCygMing()) {
514 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
517 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
518 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
519 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
520 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
521 if (Subtarget->is64Bit()) {
522 setExceptionPointerRegister(X86::RAX);
523 setExceptionSelectorRegister(X86::RDX);
525 setExceptionPointerRegister(X86::EAX);
526 setExceptionSelectorRegister(X86::EDX);
528 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
529 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
531 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
533 setOperationAction(ISD::TRAP, MVT::Other, Legal);
535 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
536 setOperationAction(ISD::VASTART , MVT::Other, Custom);
537 setOperationAction(ISD::VAEND , MVT::Other, Expand);
538 if (Subtarget->is64Bit()) {
539 setOperationAction(ISD::VAARG , MVT::Other, Custom);
540 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
542 setOperationAction(ISD::VAARG , MVT::Other, Expand);
543 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
546 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
547 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
548 if (Subtarget->is64Bit())
549 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
550 if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
551 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
553 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
555 if (!UseSoftFloat && X86ScalarSSEf64) {
556 // f32 and f64 use SSE.
557 // Set up the FP register classes.
558 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
559 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
561 // Use ANDPD to simulate FABS.
562 setOperationAction(ISD::FABS , MVT::f64, Custom);
563 setOperationAction(ISD::FABS , MVT::f32, Custom);
565 // Use XORP to simulate FNEG.
566 setOperationAction(ISD::FNEG , MVT::f64, Custom);
567 setOperationAction(ISD::FNEG , MVT::f32, Custom);
569 // Use ANDPD and ORPD to simulate FCOPYSIGN.
570 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
571 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
573 // We don't support sin/cos/fmod
574 setOperationAction(ISD::FSIN , MVT::f64, Expand);
575 setOperationAction(ISD::FCOS , MVT::f64, Expand);
576 setOperationAction(ISD::FSIN , MVT::f32, Expand);
577 setOperationAction(ISD::FCOS , MVT::f32, Expand);
579 // Expand FP immediates into loads from the stack, except for the special
581 addLegalFPImmediate(APFloat(+0.0)); // xorpd
582 addLegalFPImmediate(APFloat(+0.0f)); // xorps
583 } else if (!UseSoftFloat && X86ScalarSSEf32) {
584 // Use SSE for f32, x87 for f64.
585 // Set up the FP register classes.
586 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
587 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
589 // Use ANDPS to simulate FABS.
590 setOperationAction(ISD::FABS , MVT::f32, Custom);
592 // Use XORP to simulate FNEG.
593 setOperationAction(ISD::FNEG , MVT::f32, Custom);
595 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
597 // Use ANDPS and ORPS to simulate FCOPYSIGN.
598 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
599 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
601 // We don't support sin/cos/fmod
602 setOperationAction(ISD::FSIN , MVT::f32, Expand);
603 setOperationAction(ISD::FCOS , MVT::f32, Expand);
605 // Special cases we handle for FP constants.
606 addLegalFPImmediate(APFloat(+0.0f)); // xorps
607 addLegalFPImmediate(APFloat(+0.0)); // FLD0
608 addLegalFPImmediate(APFloat(+1.0)); // FLD1
609 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
610 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
613 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
614 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
616 } else if (!UseSoftFloat) {
617 // f32 and f64 in x87.
618 // Set up the FP register classes.
619 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
620 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
622 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
623 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
624 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
625 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
628 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
629 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
631 addLegalFPImmediate(APFloat(+0.0)); // FLD0
632 addLegalFPImmediate(APFloat(+1.0)); // FLD1
633 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
634 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
635 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
636 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
637 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
638 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
641 // Long double always uses X87.
643 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
644 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
645 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
647 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
648 addLegalFPImmediate(TmpFlt); // FLD0
650 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
653 APFloat TmpFlt2(+1.0);
654 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
656 addLegalFPImmediate(TmpFlt2); // FLD1
657 TmpFlt2.changeSign();
658 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
662 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
663 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
667 // Always use a library call for pow.
668 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
669 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
670 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
672 setOperationAction(ISD::FLOG, MVT::f80, Expand);
673 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
674 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
675 setOperationAction(ISD::FEXP, MVT::f80, Expand);
676 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
678 // First set operation action for all vector types to either promote
679 // (for widening) or expand (for scalarization). Then we will selectively
680 // turn on ones that can be effectively codegen'd.
681 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
682 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
683 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
684 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
685 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
686 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
687 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
688 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
689 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
690 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
691 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
692 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
693 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
694 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
695 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
696 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
698 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
699 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
700 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
701 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
702 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
703 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
704 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
705 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
733 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
737 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
738 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
739 setTruncStoreAction((MVT::SimpleValueType)VT,
740 (MVT::SimpleValueType)InnerVT, Expand);
741 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
742 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
743 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
746 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
747 // with -msoft-float, disable use of MMX as well.
748 if (!UseSoftFloat && Subtarget->hasMMX()) {
749 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
750 // No operations on x86mmx supported, everything uses intrinsics.
753 // MMX-sized vectors (other than x86mmx) are expected to be expanded
754 // into smaller operations.
755 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
756 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
757 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
758 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
759 setOperationAction(ISD::AND, MVT::v8i8, Expand);
760 setOperationAction(ISD::AND, MVT::v4i16, Expand);
761 setOperationAction(ISD::AND, MVT::v2i32, Expand);
762 setOperationAction(ISD::AND, MVT::v1i64, Expand);
763 setOperationAction(ISD::OR, MVT::v8i8, Expand);
764 setOperationAction(ISD::OR, MVT::v4i16, Expand);
765 setOperationAction(ISD::OR, MVT::v2i32, Expand);
766 setOperationAction(ISD::OR, MVT::v1i64, Expand);
767 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
768 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
769 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
770 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
771 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
772 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
773 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
774 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
775 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
776 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
777 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
778 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
779 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
780 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
781 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
782 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
783 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
785 if (!UseSoftFloat && Subtarget->hasXMM()) {
786 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
788 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
789 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
790 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
791 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
792 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
793 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
794 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
795 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
796 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
797 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
798 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
799 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
802 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
803 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
805 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
806 // registers cannot be used even for integer operations.
807 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
808 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
809 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
810 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
812 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
813 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
814 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
815 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
816 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
817 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
818 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
819 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
820 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
821 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
822 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
823 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
824 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
825 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
826 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
827 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
829 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
830 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
831 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
832 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
834 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
835 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
836 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
837 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
838 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
840 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
841 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
842 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
843 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
844 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
846 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
847 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
848 EVT VT = (MVT::SimpleValueType)i;
849 // Do not attempt to custom lower non-power-of-2 vectors
850 if (!isPowerOf2_32(VT.getVectorNumElements()))
852 // Do not attempt to custom lower non-128-bit vectors
853 if (!VT.is128BitVector())
855 setOperationAction(ISD::BUILD_VECTOR,
856 VT.getSimpleVT().SimpleTy, Custom);
857 setOperationAction(ISD::VECTOR_SHUFFLE,
858 VT.getSimpleVT().SimpleTy, Custom);
859 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
860 VT.getSimpleVT().SimpleTy, Custom);
863 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
864 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
865 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
866 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
867 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
868 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
870 if (Subtarget->is64Bit()) {
871 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
872 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
875 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
876 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
877 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
880 // Do not attempt to promote non-128-bit vectors
881 if (!VT.is128BitVector())
884 setOperationAction(ISD::AND, SVT, Promote);
885 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
886 setOperationAction(ISD::OR, SVT, Promote);
887 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
888 setOperationAction(ISD::XOR, SVT, Promote);
889 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
890 setOperationAction(ISD::LOAD, SVT, Promote);
891 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
892 setOperationAction(ISD::SELECT, SVT, Promote);
893 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
896 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
898 // Custom lower v2i64 and v2f64 selects.
899 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
900 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
901 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
902 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
904 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
905 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
908 if (Subtarget->hasSSE41()) {
909 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
910 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
911 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
912 setOperationAction(ISD::FRINT, MVT::f32, Legal);
913 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
914 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
915 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
916 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
917 setOperationAction(ISD::FRINT, MVT::f64, Legal);
918 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
920 // FIXME: Do we need to handle scalar-to-vector here?
921 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
923 // Can turn SHL into an integer multiply.
924 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
925 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
927 // i8 and i16 vectors are custom , because the source register and source
928 // source memory operand types are not the same width. f32 vectors are
929 // custom since the immediate controlling the insert encodes additional
931 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
932 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
933 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
934 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
936 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
937 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
938 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
939 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
941 if (Subtarget->is64Bit()) {
942 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
943 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
947 if (Subtarget->hasSSE42())
948 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
950 if (!UseSoftFloat && Subtarget->hasAVX()) {
951 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
952 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
953 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
954 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
955 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
957 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
958 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
959 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
960 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
962 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
963 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
964 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
965 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
966 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
967 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
969 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
970 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
971 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
972 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
973 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
974 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
976 // Custom lower build_vector, vector_shuffle, scalar_to_vector,
977 // insert_vector_elt extract_subvector and extract_vector_elt for
979 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
980 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
982 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
983 // Do not attempt to custom lower non-256-bit vectors
984 if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
985 || (MVT(VT).getSizeInBits() < 256))
987 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
988 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
989 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
991 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
993 // Custom-lower insert_subvector and extract_subvector based on
995 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
996 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
998 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
999 // Do not attempt to custom lower non-256-bit vectors
1000 if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1003 if (MVT(VT).getSizeInBits() == 128) {
1004 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1006 else if (MVT(VT).getSizeInBits() == 256) {
1007 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1011 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1012 // Don't promote loads because we need them for VPERM vector index versions.
1014 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1015 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1017 if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1018 || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1020 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
1021 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v4i64);
1022 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
1023 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v4i64);
1024 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
1025 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v4i64);
1026 //setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
1027 //AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v4i64);
1028 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1029 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1033 // We want to custom lower some of our intrinsics.
1034 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1037 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1038 // handle type legalization for these operations here.
1040 // FIXME: We really should do custom legalization for addition and
1041 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1042 // than generic legalization for 64-bit multiplication-with-overflow, though.
1043 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1044 // Add/Sub/Mul with overflow operations are custom lowered.
1046 setOperationAction(ISD::SADDO, VT, Custom);
1047 setOperationAction(ISD::UADDO, VT, Custom);
1048 setOperationAction(ISD::SSUBO, VT, Custom);
1049 setOperationAction(ISD::USUBO, VT, Custom);
1050 setOperationAction(ISD::SMULO, VT, Custom);
1051 setOperationAction(ISD::UMULO, VT, Custom);
1054 // There are no 8-bit 3-address imul/mul instructions
1055 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1056 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1058 if (!Subtarget->is64Bit()) {
1059 // These libcalls are not available in 32-bit.
1060 setLibcallName(RTLIB::SHL_I128, 0);
1061 setLibcallName(RTLIB::SRL_I128, 0);
1062 setLibcallName(RTLIB::SRA_I128, 0);
1065 // We have target-specific dag combine patterns for the following nodes:
1066 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1067 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1068 setTargetDAGCombine(ISD::BUILD_VECTOR);
1069 setTargetDAGCombine(ISD::SELECT);
1070 setTargetDAGCombine(ISD::SHL);
1071 setTargetDAGCombine(ISD::SRA);
1072 setTargetDAGCombine(ISD::SRL);
1073 setTargetDAGCombine(ISD::OR);
1074 setTargetDAGCombine(ISD::AND);
1075 setTargetDAGCombine(ISD::ADD);
1076 setTargetDAGCombine(ISD::SUB);
1077 setTargetDAGCombine(ISD::STORE);
1078 setTargetDAGCombine(ISD::ZERO_EXTEND);
1079 if (Subtarget->is64Bit())
1080 setTargetDAGCombine(ISD::MUL);
1082 computeRegisterProperties();
1084 // On Darwin, -Os means optimize for size without hurting performance,
1085 // do not reduce the limit.
1086 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1087 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1088 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1089 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1090 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1091 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1092 setPrefLoopAlignment(16);
1093 benefitFromCodePlacementOpt = true;
1097 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1102 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1103 /// the desired ByVal argument alignment.
1104 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1107 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1108 if (VTy->getBitWidth() == 128)
1110 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1111 unsigned EltAlign = 0;
1112 getMaxByValAlign(ATy->getElementType(), EltAlign);
1113 if (EltAlign > MaxAlign)
1114 MaxAlign = EltAlign;
1115 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1116 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1117 unsigned EltAlign = 0;
1118 getMaxByValAlign(STy->getElementType(i), EltAlign);
1119 if (EltAlign > MaxAlign)
1120 MaxAlign = EltAlign;
1128 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1129 /// function arguments in the caller parameter area. For X86, aggregates
1130 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1131 /// are at 4-byte boundaries.
1132 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1133 if (Subtarget->is64Bit()) {
1134 // Max of 8 and alignment of type.
1135 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1142 if (Subtarget->hasXMM())
1143 getMaxByValAlign(Ty, Align);
1147 /// getOptimalMemOpType - Returns the target specific optimal type for load
1148 /// and store operations as a result of memset, memcpy, and memmove
1149 /// lowering. If DstAlign is zero that means it's safe to destination
1150 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1151 /// means there isn't a need to check it against alignment requirement,
1152 /// probably because the source does not need to be loaded. If
1153 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1154 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1155 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1156 /// constant so it does not need to be loaded.
1157 /// It returns EVT::Other if the type should be determined using generic
1158 /// target-independent logic.
1160 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1161 unsigned DstAlign, unsigned SrcAlign,
1162 bool NonScalarIntSafe,
1164 MachineFunction &MF) const {
1165 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1166 // linux. This is because the stack realignment code can't handle certain
1167 // cases like PR2962. This should be removed when PR2962 is fixed.
1168 const Function *F = MF.getFunction();
1169 if (NonScalarIntSafe &&
1170 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1172 (Subtarget->isUnalignedMemAccessFast() ||
1173 ((DstAlign == 0 || DstAlign >= 16) &&
1174 (SrcAlign == 0 || SrcAlign >= 16))) &&
1175 Subtarget->getStackAlignment() >= 16) {
1176 if (Subtarget->hasSSE2())
1178 if (Subtarget->hasSSE1())
1180 } else if (!MemcpyStrSrc && Size >= 8 &&
1181 !Subtarget->is64Bit() &&
1182 Subtarget->getStackAlignment() >= 8 &&
1183 Subtarget->hasXMMInt()) {
1184 // Do not use f64 to lower memcpy if source is string constant. It's
1185 // better to use i32 to avoid the loads.
1189 if (Subtarget->is64Bit() && Size >= 8)
1194 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1195 /// current function. The returned value is a member of the
1196 /// MachineJumpTableInfo::JTEntryKind enum.
1197 unsigned X86TargetLowering::getJumpTableEncoding() const {
1198 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1200 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1201 Subtarget->isPICStyleGOT())
1202 return MachineJumpTableInfo::EK_Custom32;
1204 // Otherwise, use the normal jump table encoding heuristics.
1205 return TargetLowering::getJumpTableEncoding();
1209 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1210 const MachineBasicBlock *MBB,
1211 unsigned uid,MCContext &Ctx) const{
1212 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1213 Subtarget->isPICStyleGOT());
1214 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1216 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1217 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1220 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1222 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1223 SelectionDAG &DAG) const {
1224 if (!Subtarget->is64Bit())
1225 // This doesn't have DebugLoc associated with it, but is not really the
1226 // same as a Register.
1227 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1231 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1232 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1234 const MCExpr *X86TargetLowering::
1235 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1236 MCContext &Ctx) const {
1237 // X86-64 uses RIP relative addressing based on the jump table label.
1238 if (Subtarget->isPICStyleRIPRel())
1239 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1241 // Otherwise, the reference is relative to the PIC base.
1242 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1245 /// getFunctionAlignment - Return the Log2 alignment of this function.
1246 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1247 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1250 // FIXME: Why this routine is here? Move to RegInfo!
1251 std::pair<const TargetRegisterClass*, uint8_t>
1252 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1253 const TargetRegisterClass *RRC = 0;
1255 switch (VT.getSimpleVT().SimpleTy) {
1257 return TargetLowering::findRepresentativeClass(VT);
1258 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1259 RRC = (Subtarget->is64Bit()
1260 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1263 RRC = X86::VR64RegisterClass;
1265 case MVT::f32: case MVT::f64:
1266 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1267 case MVT::v4f32: case MVT::v2f64:
1268 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1270 RRC = X86::VR128RegisterClass;
1273 return std::make_pair(RRC, Cost);
1276 // FIXME: Why this routine is here? Move to RegInfo!
1278 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1279 MachineFunction &MF) const {
1280 const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
1282 unsigned FPDiff = TFI->hasFP(MF) ? 1 : 0;
1283 switch (RC->getID()) {
1286 case X86::GR32RegClassID:
1288 case X86::GR64RegClassID:
1290 case X86::VR128RegClassID:
1291 return Subtarget->is64Bit() ? 10 : 4;
1292 case X86::VR64RegClassID:
1297 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1298 unsigned &Offset) const {
1299 if (!Subtarget->isTargetLinux())
1302 if (Subtarget->is64Bit()) {
1303 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1305 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1318 //===----------------------------------------------------------------------===//
1319 // Return Value Calling Convention Implementation
1320 //===----------------------------------------------------------------------===//
1322 #include "X86GenCallingConv.inc"
1325 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1326 const SmallVectorImpl<ISD::OutputArg> &Outs,
1327 LLVMContext &Context) const {
1328 SmallVector<CCValAssign, 16> RVLocs;
1329 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1331 return CCInfo.CheckReturn(Outs, RetCC_X86);
1335 X86TargetLowering::LowerReturn(SDValue Chain,
1336 CallingConv::ID CallConv, bool isVarArg,
1337 const SmallVectorImpl<ISD::OutputArg> &Outs,
1338 const SmallVectorImpl<SDValue> &OutVals,
1339 DebugLoc dl, SelectionDAG &DAG) const {
1340 MachineFunction &MF = DAG.getMachineFunction();
1341 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1343 SmallVector<CCValAssign, 16> RVLocs;
1344 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1345 RVLocs, *DAG.getContext());
1346 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1348 // Add the regs to the liveout set for the function.
1349 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1350 for (unsigned i = 0; i != RVLocs.size(); ++i)
1351 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1352 MRI.addLiveOut(RVLocs[i].getLocReg());
1356 SmallVector<SDValue, 6> RetOps;
1357 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1358 // Operand #1 = Bytes To Pop
1359 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1362 // Copy the result values into the output registers.
1363 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1364 CCValAssign &VA = RVLocs[i];
1365 assert(VA.isRegLoc() && "Can only return in registers!");
1366 SDValue ValToCopy = OutVals[i];
1367 EVT ValVT = ValToCopy.getValueType();
1369 // If this is x86-64, and we disabled SSE, we can't return FP values,
1370 // or SSE or MMX vectors.
1371 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1372 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1373 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1374 report_fatal_error("SSE register return with SSE disabled");
1376 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1377 // llvm-gcc has never done it right and no one has noticed, so this
1378 // should be OK for now.
1379 if (ValVT == MVT::f64 &&
1380 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1381 report_fatal_error("SSE2 register return with SSE2 disabled");
1383 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1384 // the RET instruction and handled by the FP Stackifier.
1385 if (VA.getLocReg() == X86::ST0 ||
1386 VA.getLocReg() == X86::ST1) {
1387 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1388 // change the value to the FP stack register class.
1389 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1390 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1391 RetOps.push_back(ValToCopy);
1392 // Don't emit a copytoreg.
1396 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1397 // which is returned in RAX / RDX.
1398 if (Subtarget->is64Bit()) {
1399 if (ValVT == MVT::x86mmx) {
1400 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1401 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1402 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1404 // If we don't have SSE2 available, convert to v4f32 so the generated
1405 // register is legal.
1406 if (!Subtarget->hasSSE2())
1407 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1412 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1413 Flag = Chain.getValue(1);
1416 // The x86-64 ABI for returning structs by value requires that we copy
1417 // the sret argument into %rax for the return. We saved the argument into
1418 // a virtual register in the entry block, so now we copy the value out
1420 if (Subtarget->is64Bit() &&
1421 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1422 MachineFunction &MF = DAG.getMachineFunction();
1423 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1424 unsigned Reg = FuncInfo->getSRetReturnReg();
1426 "SRetReturnReg should have been set in LowerFormalArguments().");
1427 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1429 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1430 Flag = Chain.getValue(1);
1432 // RAX now acts like a return value.
1433 MRI.addLiveOut(X86::RAX);
1436 RetOps[0] = Chain; // Update chain.
1438 // Add the flag if we have it.
1440 RetOps.push_back(Flag);
1442 return DAG.getNode(X86ISD::RET_FLAG, dl,
1443 MVT::Other, &RetOps[0], RetOps.size());
1446 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1447 if (N->getNumValues() != 1)
1449 if (!N->hasNUsesOfValue(1, 0))
1452 SDNode *Copy = *N->use_begin();
1453 if (Copy->getOpcode() != ISD::CopyToReg &&
1454 Copy->getOpcode() != ISD::FP_EXTEND)
1457 bool HasRet = false;
1458 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1460 if (UI->getOpcode() != X86ISD::RET_FLAG)
1468 /// LowerCallResult - Lower the result values of a call into the
1469 /// appropriate copies out of appropriate physical registers.
1472 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1473 CallingConv::ID CallConv, bool isVarArg,
1474 const SmallVectorImpl<ISD::InputArg> &Ins,
1475 DebugLoc dl, SelectionDAG &DAG,
1476 SmallVectorImpl<SDValue> &InVals) const {
1478 // Assign locations to each value returned by this call.
1479 SmallVector<CCValAssign, 16> RVLocs;
1480 bool Is64Bit = Subtarget->is64Bit();
1481 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1482 RVLocs, *DAG.getContext());
1483 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1485 // Copy all of the result registers out of their specified physreg.
1486 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1487 CCValAssign &VA = RVLocs[i];
1488 EVT CopyVT = VA.getValVT();
1490 // If this is x86-64, and we disabled SSE, we can't return FP values
1491 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1492 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1493 report_fatal_error("SSE register return with SSE disabled");
1498 // If this is a call to a function that returns an fp value on the floating
1499 // point stack, we must guarantee the the value is popped from the stack, so
1500 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1501 // if the return value is not used. We use the FpGET_ST0 instructions
1503 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1504 // If we prefer to use the value in xmm registers, copy it out as f80 and
1505 // use a truncate to move it from fp stack reg to xmm reg.
1506 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1507 bool isST0 = VA.getLocReg() == X86::ST0;
1509 if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1510 if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1511 if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1512 SDValue Ops[] = { Chain, InFlag };
1513 Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1515 Val = Chain.getValue(0);
1517 // Round the f80 to the right size, which also moves it to the appropriate
1519 if (CopyVT != VA.getValVT())
1520 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1521 // This truncation won't change the value.
1522 DAG.getIntPtrConstant(1));
1523 } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1524 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1525 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1526 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1527 MVT::v2i64, InFlag).getValue(1);
1528 Val = Chain.getValue(0);
1529 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1530 Val, DAG.getConstant(0, MVT::i64));
1532 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1533 MVT::i64, InFlag).getValue(1);
1534 Val = Chain.getValue(0);
1536 Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1538 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1539 CopyVT, InFlag).getValue(1);
1540 Val = Chain.getValue(0);
1542 InFlag = Chain.getValue(2);
1543 InVals.push_back(Val);
1550 //===----------------------------------------------------------------------===//
1551 // C & StdCall & Fast Calling Convention implementation
1552 //===----------------------------------------------------------------------===//
1553 // StdCall calling convention seems to be standard for many Windows' API
1554 // routines and around. It differs from C calling convention just a little:
1555 // callee should clean up the stack, not caller. Symbols should be also
1556 // decorated in some fancy way :) It doesn't support any vector arguments.
1557 // For info on fast calling convention see Fast Calling Convention (tail call)
1558 // implementation LowerX86_32FastCCCallTo.
1560 /// CallIsStructReturn - Determines whether a call uses struct return
1562 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1566 return Outs[0].Flags.isSRet();
1569 /// ArgsAreStructReturn - Determines whether a function uses struct
1570 /// return semantics.
1572 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1576 return Ins[0].Flags.isSRet();
1579 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1580 /// by "Src" to address "Dst" with size and alignment information specified by
1581 /// the specific parameter attribute. The copy will be passed as a byval
1582 /// function parameter.
1584 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1585 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1587 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1589 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1590 /*isVolatile*/false, /*AlwaysInline=*/true,
1591 MachinePointerInfo(), MachinePointerInfo());
1594 /// IsTailCallConvention - Return true if the calling convention is one that
1595 /// supports tail call optimization.
1596 static bool IsTailCallConvention(CallingConv::ID CC) {
1597 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1600 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1601 /// a tailcall target by changing its ABI.
1602 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1603 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1607 X86TargetLowering::LowerMemArgument(SDValue Chain,
1608 CallingConv::ID CallConv,
1609 const SmallVectorImpl<ISD::InputArg> &Ins,
1610 DebugLoc dl, SelectionDAG &DAG,
1611 const CCValAssign &VA,
1612 MachineFrameInfo *MFI,
1614 // Create the nodes corresponding to a load from this parameter slot.
1615 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1616 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1617 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1620 // If value is passed by pointer we have address passed instead of the value
1622 if (VA.getLocInfo() == CCValAssign::Indirect)
1623 ValVT = VA.getLocVT();
1625 ValVT = VA.getValVT();
1627 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1628 // changed with more analysis.
1629 // In case of tail call optimization mark all arguments mutable. Since they
1630 // could be overwritten by lowering of arguments in case of a tail call.
1631 if (Flags.isByVal()) {
1632 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1633 VA.getLocMemOffset(), isImmutable);
1634 return DAG.getFrameIndex(FI, getPointerTy());
1636 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1637 VA.getLocMemOffset(), isImmutable);
1638 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1639 return DAG.getLoad(ValVT, dl, Chain, FIN,
1640 MachinePointerInfo::getFixedStack(FI),
1646 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1647 CallingConv::ID CallConv,
1649 const SmallVectorImpl<ISD::InputArg> &Ins,
1652 SmallVectorImpl<SDValue> &InVals)
1654 MachineFunction &MF = DAG.getMachineFunction();
1655 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1657 const Function* Fn = MF.getFunction();
1658 if (Fn->hasExternalLinkage() &&
1659 Subtarget->isTargetCygMing() &&
1660 Fn->getName() == "main")
1661 FuncInfo->setForceFramePointer(true);
1663 MachineFrameInfo *MFI = MF.getFrameInfo();
1664 bool Is64Bit = Subtarget->is64Bit();
1665 bool IsWin64 = Subtarget->isTargetWin64();
1667 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1668 "Var args not supported with calling convention fastcc or ghc");
1670 // Assign locations to all of the incoming arguments.
1671 SmallVector<CCValAssign, 16> ArgLocs;
1672 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1673 ArgLocs, *DAG.getContext());
1675 // Allocate shadow area for Win64
1677 CCInfo.AllocateStack(32, 8);
1680 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1682 unsigned LastVal = ~0U;
1684 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1685 CCValAssign &VA = ArgLocs[i];
1686 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1688 assert(VA.getValNo() != LastVal &&
1689 "Don't support value assigned to multiple locs yet");
1690 LastVal = VA.getValNo();
1692 if (VA.isRegLoc()) {
1693 EVT RegVT = VA.getLocVT();
1694 TargetRegisterClass *RC = NULL;
1695 if (RegVT == MVT::i32)
1696 RC = X86::GR32RegisterClass;
1697 else if (Is64Bit && RegVT == MVT::i64)
1698 RC = X86::GR64RegisterClass;
1699 else if (RegVT == MVT::f32)
1700 RC = X86::FR32RegisterClass;
1701 else if (RegVT == MVT::f64)
1702 RC = X86::FR64RegisterClass;
1703 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1704 RC = X86::VR256RegisterClass;
1705 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1706 RC = X86::VR128RegisterClass;
1707 else if (RegVT == MVT::x86mmx)
1708 RC = X86::VR64RegisterClass;
1710 llvm_unreachable("Unknown argument type!");
1712 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC, dl);
1713 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1715 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1716 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1718 if (VA.getLocInfo() == CCValAssign::SExt)
1719 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1720 DAG.getValueType(VA.getValVT()));
1721 else if (VA.getLocInfo() == CCValAssign::ZExt)
1722 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1723 DAG.getValueType(VA.getValVT()));
1724 else if (VA.getLocInfo() == CCValAssign::BCvt)
1725 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1727 if (VA.isExtInLoc()) {
1728 // Handle MMX values passed in XMM regs.
1729 if (RegVT.isVector()) {
1730 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1733 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1736 assert(VA.isMemLoc());
1737 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1740 // If value is passed via pointer - do a load.
1741 if (VA.getLocInfo() == CCValAssign::Indirect)
1742 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1743 MachinePointerInfo(), false, false, 0);
1745 InVals.push_back(ArgValue);
1748 // The x86-64 ABI for returning structs by value requires that we copy
1749 // the sret argument into %rax for the return. Save the argument into
1750 // a virtual register so that we can access it from the return points.
1751 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1752 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1753 unsigned Reg = FuncInfo->getSRetReturnReg();
1755 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1756 FuncInfo->setSRetReturnReg(Reg);
1758 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1759 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1762 unsigned StackSize = CCInfo.getNextStackOffset();
1763 // Align stack specially for tail calls.
1764 if (FuncIsMadeTailCallSafe(CallConv))
1765 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1767 // If the function takes variable number of arguments, make a frame index for
1768 // the start of the first vararg value... for expansion of llvm.va_start.
1770 if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1771 CallConv != CallingConv::X86_ThisCall))) {
1772 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1775 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1777 // FIXME: We should really autogenerate these arrays
1778 static const unsigned GPR64ArgRegsWin64[] = {
1779 X86::RCX, X86::RDX, X86::R8, X86::R9
1781 static const unsigned GPR64ArgRegs64Bit[] = {
1782 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1784 static const unsigned XMMArgRegs64Bit[] = {
1785 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1786 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1788 const unsigned *GPR64ArgRegs;
1789 unsigned NumXMMRegs = 0;
1792 // The XMM registers which might contain var arg parameters are shadowed
1793 // in their paired GPR. So we only need to save the GPR to their home
1795 TotalNumIntRegs = 4;
1796 GPR64ArgRegs = GPR64ArgRegsWin64;
1798 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1799 GPR64ArgRegs = GPR64ArgRegs64Bit;
1801 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1803 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1806 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1807 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1808 "SSE register cannot be used when SSE is disabled!");
1809 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1810 "SSE register cannot be used when SSE is disabled!");
1811 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1812 // Kernel mode asks for SSE to be disabled, so don't push them
1814 TotalNumXMMRegs = 0;
1817 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1818 // Get to the caller-allocated home save location. Add 8 to account
1819 // for the return address.
1820 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1821 FuncInfo->setRegSaveFrameIndex(
1822 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1823 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1825 // For X86-64, if there are vararg parameters that are passed via
1826 // registers, then we must store them to their spots on the stack so they
1827 // may be loaded by deferencing the result of va_next.
1828 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1829 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1830 FuncInfo->setRegSaveFrameIndex(
1831 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1835 // Store the integer parameter registers.
1836 SmallVector<SDValue, 8> MemOps;
1837 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1839 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1840 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1841 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1842 DAG.getIntPtrConstant(Offset));
1843 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1844 X86::GR64RegisterClass, dl);
1845 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1847 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1848 MachinePointerInfo::getFixedStack(
1849 FuncInfo->getRegSaveFrameIndex(), Offset),
1851 MemOps.push_back(Store);
1855 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1856 // Now store the XMM (fp + vector) parameter registers.
1857 SmallVector<SDValue, 11> SaveXMMOps;
1858 SaveXMMOps.push_back(Chain);
1860 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass, dl);
1861 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1862 SaveXMMOps.push_back(ALVal);
1864 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1865 FuncInfo->getRegSaveFrameIndex()));
1866 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1867 FuncInfo->getVarArgsFPOffset()));
1869 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1870 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1871 X86::VR128RegisterClass, dl);
1872 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1873 SaveXMMOps.push_back(Val);
1875 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1877 &SaveXMMOps[0], SaveXMMOps.size()));
1880 if (!MemOps.empty())
1881 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1882 &MemOps[0], MemOps.size());
1886 // Some CCs need callee pop.
1887 if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1888 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1890 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1891 // If this is an sret function, the return should pop the hidden pointer.
1892 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1893 FuncInfo->setBytesToPopOnReturn(4);
1897 // RegSaveFrameIndex is X86-64 only.
1898 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1899 if (CallConv == CallingConv::X86_FastCall ||
1900 CallConv == CallingConv::X86_ThisCall)
1901 // fastcc functions can't have varargs.
1902 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1909 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1910 SDValue StackPtr, SDValue Arg,
1911 DebugLoc dl, SelectionDAG &DAG,
1912 const CCValAssign &VA,
1913 ISD::ArgFlagsTy Flags) const {
1914 unsigned LocMemOffset = VA.getLocMemOffset();
1915 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1916 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1917 if (Flags.isByVal())
1918 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1920 return DAG.getStore(Chain, dl, Arg, PtrOff,
1921 MachinePointerInfo::getStack(LocMemOffset),
1925 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1926 /// optimization is performed and it is required.
1928 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1929 SDValue &OutRetAddr, SDValue Chain,
1930 bool IsTailCall, bool Is64Bit,
1931 int FPDiff, DebugLoc dl) const {
1932 // Adjust the Return address stack slot.
1933 EVT VT = getPointerTy();
1934 OutRetAddr = getReturnAddressFrameIndex(DAG);
1936 // Load the "old" Return address.
1937 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1939 return SDValue(OutRetAddr.getNode(), 1);
1942 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1943 /// optimization is performed and it is required (FPDiff!=0).
1945 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1946 SDValue Chain, SDValue RetAddrFrIdx,
1947 bool Is64Bit, int FPDiff, DebugLoc dl) {
1948 // Store the return address to the appropriate stack slot.
1949 if (!FPDiff) return Chain;
1950 // Calculate the new stack slot for the return address.
1951 int SlotSize = Is64Bit ? 8 : 4;
1952 int NewReturnAddrFI =
1953 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1954 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1955 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1956 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1957 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1963 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1964 CallingConv::ID CallConv, bool isVarArg,
1966 const SmallVectorImpl<ISD::OutputArg> &Outs,
1967 const SmallVectorImpl<SDValue> &OutVals,
1968 const SmallVectorImpl<ISD::InputArg> &Ins,
1969 DebugLoc dl, SelectionDAG &DAG,
1970 SmallVectorImpl<SDValue> &InVals) const {
1971 MachineFunction &MF = DAG.getMachineFunction();
1972 bool Is64Bit = Subtarget->is64Bit();
1973 bool IsWin64 = Subtarget->isTargetWin64();
1974 bool IsStructRet = CallIsStructReturn(Outs);
1975 bool IsSibcall = false;
1978 // Check if it's really possible to do a tail call.
1979 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1980 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1981 Outs, OutVals, Ins, DAG);
1983 // Sibcalls are automatically detected tailcalls which do not require
1985 if (!GuaranteedTailCallOpt && isTailCall)
1992 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1993 "Var args not supported with calling convention fastcc or ghc");
1995 // Analyze operands of the call, assigning locations to each operand.
1996 SmallVector<CCValAssign, 16> ArgLocs;
1997 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1998 ArgLocs, *DAG.getContext());
2000 // Allocate shadow area for Win64
2002 CCInfo.AllocateStack(32, 8);
2005 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2007 // Get a count of how many bytes are to be pushed on the stack.
2008 unsigned NumBytes = CCInfo.getNextStackOffset();
2010 // This is a sibcall. The memory operands are available in caller's
2011 // own caller's stack.
2013 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2014 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2017 if (isTailCall && !IsSibcall) {
2018 // Lower arguments at fp - stackoffset + fpdiff.
2019 unsigned NumBytesCallerPushed =
2020 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2021 FPDiff = NumBytesCallerPushed - NumBytes;
2023 // Set the delta of movement of the returnaddr stackslot.
2024 // But only set if delta is greater than previous delta.
2025 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2026 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2030 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2032 SDValue RetAddrFrIdx;
2033 // Load return adress for tail calls.
2034 if (isTailCall && FPDiff)
2035 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2036 Is64Bit, FPDiff, dl);
2038 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2039 SmallVector<SDValue, 8> MemOpChains;
2042 // Walk the register/memloc assignments, inserting copies/loads. In the case
2043 // of tail call optimization arguments are handle later.
2044 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2045 CCValAssign &VA = ArgLocs[i];
2046 EVT RegVT = VA.getLocVT();
2047 SDValue Arg = OutVals[i];
2048 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2049 bool isByVal = Flags.isByVal();
2051 // Promote the value if needed.
2052 switch (VA.getLocInfo()) {
2053 default: llvm_unreachable("Unknown loc info!");
2054 case CCValAssign::Full: break;
2055 case CCValAssign::SExt:
2056 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2058 case CCValAssign::ZExt:
2059 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2061 case CCValAssign::AExt:
2062 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2063 // Special case: passing MMX values in XMM registers.
2064 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2065 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2066 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2068 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2070 case CCValAssign::BCvt:
2071 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2073 case CCValAssign::Indirect: {
2074 // Store the argument.
2075 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2076 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2077 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2078 MachinePointerInfo::getFixedStack(FI),
2085 if (VA.isRegLoc()) {
2086 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2087 if (isVarArg && IsWin64) {
2088 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2089 // shadow reg if callee is a varargs function.
2090 unsigned ShadowReg = 0;
2091 switch (VA.getLocReg()) {
2092 case X86::XMM0: ShadowReg = X86::RCX; break;
2093 case X86::XMM1: ShadowReg = X86::RDX; break;
2094 case X86::XMM2: ShadowReg = X86::R8; break;
2095 case X86::XMM3: ShadowReg = X86::R9; break;
2098 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2100 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2101 assert(VA.isMemLoc());
2102 if (StackPtr.getNode() == 0)
2103 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2104 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2105 dl, DAG, VA, Flags));
2109 if (!MemOpChains.empty())
2110 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2111 &MemOpChains[0], MemOpChains.size());
2113 // Build a sequence of copy-to-reg nodes chained together with token chain
2114 // and flag operands which copy the outgoing args into registers.
2116 // Tail call byval lowering might overwrite argument registers so in case of
2117 // tail call optimization the copies to registers are lowered later.
2119 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2120 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2121 RegsToPass[i].second, InFlag);
2122 InFlag = Chain.getValue(1);
2125 if (Subtarget->isPICStyleGOT()) {
2126 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2129 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2130 DAG.getNode(X86ISD::GlobalBaseReg,
2131 DebugLoc(), getPointerTy()),
2133 InFlag = Chain.getValue(1);
2135 // If we are tail calling and generating PIC/GOT style code load the
2136 // address of the callee into ECX. The value in ecx is used as target of
2137 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2138 // for tail calls on PIC/GOT architectures. Normally we would just put the
2139 // address of GOT into ebx and then call target@PLT. But for tail calls
2140 // ebx would be restored (since ebx is callee saved) before jumping to the
2143 // Note: The actual moving to ECX is done further down.
2144 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2145 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2146 !G->getGlobal()->hasProtectedVisibility())
2147 Callee = LowerGlobalAddress(Callee, DAG);
2148 else if (isa<ExternalSymbolSDNode>(Callee))
2149 Callee = LowerExternalSymbol(Callee, DAG);
2153 if (Is64Bit && isVarArg && !IsWin64) {
2154 // From AMD64 ABI document:
2155 // For calls that may call functions that use varargs or stdargs
2156 // (prototype-less calls or calls to functions containing ellipsis (...) in
2157 // the declaration) %al is used as hidden argument to specify the number
2158 // of SSE registers used. The contents of %al do not need to match exactly
2159 // the number of registers, but must be an ubound on the number of SSE
2160 // registers used and is in the range 0 - 8 inclusive.
2162 // Count the number of XMM registers allocated.
2163 static const unsigned XMMArgRegs[] = {
2164 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2165 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2167 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2168 assert((Subtarget->hasXMM() || !NumXMMRegs)
2169 && "SSE registers cannot be used when SSE is disabled");
2171 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2172 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2173 InFlag = Chain.getValue(1);
2177 // For tail calls lower the arguments to the 'real' stack slot.
2179 // Force all the incoming stack arguments to be loaded from the stack
2180 // before any new outgoing arguments are stored to the stack, because the
2181 // outgoing stack slots may alias the incoming argument stack slots, and
2182 // the alias isn't otherwise explicit. This is slightly more conservative
2183 // than necessary, because it means that each store effectively depends
2184 // on every argument instead of just those arguments it would clobber.
2185 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2187 SmallVector<SDValue, 8> MemOpChains2;
2190 // Do not flag preceeding copytoreg stuff together with the following stuff.
2192 if (GuaranteedTailCallOpt) {
2193 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2194 CCValAssign &VA = ArgLocs[i];
2197 assert(VA.isMemLoc());
2198 SDValue Arg = OutVals[i];
2199 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2200 // Create frame index.
2201 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2202 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2203 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2204 FIN = DAG.getFrameIndex(FI, getPointerTy());
2206 if (Flags.isByVal()) {
2207 // Copy relative to framepointer.
2208 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2209 if (StackPtr.getNode() == 0)
2210 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2212 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2214 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2218 // Store relative to framepointer.
2219 MemOpChains2.push_back(
2220 DAG.getStore(ArgChain, dl, Arg, FIN,
2221 MachinePointerInfo::getFixedStack(FI),
2227 if (!MemOpChains2.empty())
2228 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2229 &MemOpChains2[0], MemOpChains2.size());
2231 // Copy arguments to their registers.
2232 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2233 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2234 RegsToPass[i].second, InFlag);
2235 InFlag = Chain.getValue(1);
2239 // Store the return address to the appropriate stack slot.
2240 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2244 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2245 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2246 // In the 64-bit large code model, we have to make all calls
2247 // through a register, since the call instruction's 32-bit
2248 // pc-relative offset may not be large enough to hold the whole
2250 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2251 // If the callee is a GlobalAddress node (quite common, every direct call
2252 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2255 // We should use extra load for direct calls to dllimported functions in
2257 const GlobalValue *GV = G->getGlobal();
2258 if (!GV->hasDLLImportLinkage()) {
2259 unsigned char OpFlags = 0;
2261 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2262 // external symbols most go through the PLT in PIC mode. If the symbol
2263 // has hidden or protected visibility, or if it is static or local, then
2264 // we don't need to use the PLT - we can directly call it.
2265 if (Subtarget->isTargetELF() &&
2266 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2267 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2268 OpFlags = X86II::MO_PLT;
2269 } else if (Subtarget->isPICStyleStubAny() &&
2270 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2271 Subtarget->getDarwinVers() < 9) {
2272 // PC-relative references to external symbols should go through $stub,
2273 // unless we're building with the leopard linker or later, which
2274 // automatically synthesizes these stubs.
2275 OpFlags = X86II::MO_DARWIN_STUB;
2278 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2279 G->getOffset(), OpFlags);
2281 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2282 unsigned char OpFlags = 0;
2284 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2285 // external symbols should go through the PLT.
2286 if (Subtarget->isTargetELF() &&
2287 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2288 OpFlags = X86II::MO_PLT;
2289 } else if (Subtarget->isPICStyleStubAny() &&
2290 Subtarget->getDarwinVers() < 9) {
2291 // PC-relative references to external symbols should go through $stub,
2292 // unless we're building with the leopard linker or later, which
2293 // automatically synthesizes these stubs.
2294 OpFlags = X86II::MO_DARWIN_STUB;
2297 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2301 // Returns a chain & a flag for retval copy to use.
2302 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2303 SmallVector<SDValue, 8> Ops;
2305 if (!IsSibcall && isTailCall) {
2306 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2307 DAG.getIntPtrConstant(0, true), InFlag);
2308 InFlag = Chain.getValue(1);
2311 Ops.push_back(Chain);
2312 Ops.push_back(Callee);
2315 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2317 // Add argument registers to the end of the list so that they are known live
2319 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2320 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2321 RegsToPass[i].second.getValueType()));
2323 // Add an implicit use GOT pointer in EBX.
2324 if (!isTailCall && Subtarget->isPICStyleGOT())
2325 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2327 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2328 if (Is64Bit && isVarArg && !IsWin64)
2329 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2331 if (InFlag.getNode())
2332 Ops.push_back(InFlag);
2336 //// If this is the first return lowered for this function, add the regs
2337 //// to the liveout set for the function.
2338 // This isn't right, although it's probably harmless on x86; liveouts
2339 // should be computed from returns not tail calls. Consider a void
2340 // function making a tail call to a function returning int.
2341 return DAG.getNode(X86ISD::TC_RETURN, dl,
2342 NodeTys, &Ops[0], Ops.size());
2345 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2346 InFlag = Chain.getValue(1);
2348 // Create the CALLSEQ_END node.
2349 unsigned NumBytesForCalleeToPush;
2350 if (Subtarget->IsCalleePop(isVarArg, CallConv))
2351 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2352 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2353 // If this is a call to a struct-return function, the callee
2354 // pops the hidden struct pointer, so we have to push it back.
2355 // This is common for Darwin/X86, Linux & Mingw32 targets.
2356 NumBytesForCalleeToPush = 4;
2358 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2360 // Returns a flag for retval copy to use.
2362 Chain = DAG.getCALLSEQ_END(Chain,
2363 DAG.getIntPtrConstant(NumBytes, true),
2364 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2367 InFlag = Chain.getValue(1);
2370 // Handle result values, copying them out of physregs into vregs that we
2372 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2373 Ins, dl, DAG, InVals);
2377 //===----------------------------------------------------------------------===//
2378 // Fast Calling Convention (tail call) implementation
2379 //===----------------------------------------------------------------------===//
2381 // Like std call, callee cleans arguments, convention except that ECX is
2382 // reserved for storing the tail called function address. Only 2 registers are
2383 // free for argument passing (inreg). Tail call optimization is performed
2385 // * tailcallopt is enabled
2386 // * caller/callee are fastcc
2387 // On X86_64 architecture with GOT-style position independent code only local
2388 // (within module) calls are supported at the moment.
2389 // To keep the stack aligned according to platform abi the function
2390 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2391 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2392 // If a tail called function callee has more arguments than the caller the
2393 // caller needs to make sure that there is room to move the RETADDR to. This is
2394 // achieved by reserving an area the size of the argument delta right after the
2395 // original REtADDR, but before the saved framepointer or the spilled registers
2396 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2408 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2409 /// for a 16 byte align requirement.
2411 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2412 SelectionDAG& DAG) const {
2413 MachineFunction &MF = DAG.getMachineFunction();
2414 const TargetMachine &TM = MF.getTarget();
2415 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2416 unsigned StackAlignment = TFI.getStackAlignment();
2417 uint64_t AlignMask = StackAlignment - 1;
2418 int64_t Offset = StackSize;
2419 uint64_t SlotSize = TD->getPointerSize();
2420 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2421 // Number smaller than 12 so just add the difference.
2422 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2424 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2425 Offset = ((~AlignMask) & Offset) + StackAlignment +
2426 (StackAlignment-SlotSize);
2431 /// MatchingStackOffset - Return true if the given stack call argument is
2432 /// already available in the same position (relatively) of the caller's
2433 /// incoming argument stack.
2435 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2436 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2437 const X86InstrInfo *TII) {
2438 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2440 if (Arg.getOpcode() == ISD::CopyFromReg) {
2441 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2442 if (!TargetRegisterInfo::isVirtualRegister(VR))
2444 MachineInstr *Def = MRI->getVRegDef(VR);
2447 if (!Flags.isByVal()) {
2448 if (!TII->isLoadFromStackSlot(Def, FI))
2451 unsigned Opcode = Def->getOpcode();
2452 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2453 Def->getOperand(1).isFI()) {
2454 FI = Def->getOperand(1).getIndex();
2455 Bytes = Flags.getByValSize();
2459 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2460 if (Flags.isByVal())
2461 // ByVal argument is passed in as a pointer but it's now being
2462 // dereferenced. e.g.
2463 // define @foo(%struct.X* %A) {
2464 // tail call @bar(%struct.X* byval %A)
2467 SDValue Ptr = Ld->getBasePtr();
2468 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2471 FI = FINode->getIndex();
2475 assert(FI != INT_MAX);
2476 if (!MFI->isFixedObjectIndex(FI))
2478 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2481 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2482 /// for tail call optimization. Targets which want to do tail call
2483 /// optimization should implement this function.
2485 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2486 CallingConv::ID CalleeCC,
2488 bool isCalleeStructRet,
2489 bool isCallerStructRet,
2490 const SmallVectorImpl<ISD::OutputArg> &Outs,
2491 const SmallVectorImpl<SDValue> &OutVals,
2492 const SmallVectorImpl<ISD::InputArg> &Ins,
2493 SelectionDAG& DAG) const {
2494 if (!IsTailCallConvention(CalleeCC) &&
2495 CalleeCC != CallingConv::C)
2498 // If -tailcallopt is specified, make fastcc functions tail-callable.
2499 const MachineFunction &MF = DAG.getMachineFunction();
2500 const Function *CallerF = DAG.getMachineFunction().getFunction();
2501 CallingConv::ID CallerCC = CallerF->getCallingConv();
2502 bool CCMatch = CallerCC == CalleeCC;
2504 if (GuaranteedTailCallOpt) {
2505 if (IsTailCallConvention(CalleeCC) && CCMatch)
2510 // Look for obvious safe cases to perform tail call optimization that do not
2511 // require ABI changes. This is what gcc calls sibcall.
2513 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2514 // emit a special epilogue.
2515 if (RegInfo->needsStackRealignment(MF))
2518 // Do not sibcall optimize vararg calls unless the call site is not passing
2520 if (isVarArg && !Outs.empty())
2523 // Also avoid sibcall optimization if either caller or callee uses struct
2524 // return semantics.
2525 if (isCalleeStructRet || isCallerStructRet)
2528 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2529 // Therefore if it's not used by the call it is not safe to optimize this into
2531 bool Unused = false;
2532 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2539 SmallVector<CCValAssign, 16> RVLocs;
2540 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2541 RVLocs, *DAG.getContext());
2542 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2543 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2544 CCValAssign &VA = RVLocs[i];
2545 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2550 // If the calling conventions do not match, then we'd better make sure the
2551 // results are returned in the same way as what the caller expects.
2553 SmallVector<CCValAssign, 16> RVLocs1;
2554 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2555 RVLocs1, *DAG.getContext());
2556 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2558 SmallVector<CCValAssign, 16> RVLocs2;
2559 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2560 RVLocs2, *DAG.getContext());
2561 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2563 if (RVLocs1.size() != RVLocs2.size())
2565 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2566 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2568 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2570 if (RVLocs1[i].isRegLoc()) {
2571 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2574 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2580 // If the callee takes no arguments then go on to check the results of the
2582 if (!Outs.empty()) {
2583 // Check if stack adjustment is needed. For now, do not do this if any
2584 // argument is passed on the stack.
2585 SmallVector<CCValAssign, 16> ArgLocs;
2586 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2587 ArgLocs, *DAG.getContext());
2589 // Allocate shadow area for Win64
2590 if (Subtarget->isTargetWin64()) {
2591 CCInfo.AllocateStack(32, 8);
2594 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2595 if (CCInfo.getNextStackOffset()) {
2596 MachineFunction &MF = DAG.getMachineFunction();
2597 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2600 // Check if the arguments are already laid out in the right way as
2601 // the caller's fixed stack objects.
2602 MachineFrameInfo *MFI = MF.getFrameInfo();
2603 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2604 const X86InstrInfo *TII =
2605 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2606 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2607 CCValAssign &VA = ArgLocs[i];
2608 SDValue Arg = OutVals[i];
2609 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2610 if (VA.getLocInfo() == CCValAssign::Indirect)
2612 if (!VA.isRegLoc()) {
2613 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2620 // If the tailcall address may be in a register, then make sure it's
2621 // possible to register allocate for it. In 32-bit, the call address can
2622 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2623 // callee-saved registers are restored. These happen to be the same
2624 // registers used to pass 'inreg' arguments so watch out for those.
2625 if (!Subtarget->is64Bit() &&
2626 !isa<GlobalAddressSDNode>(Callee) &&
2627 !isa<ExternalSymbolSDNode>(Callee)) {
2628 unsigned NumInRegs = 0;
2629 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2630 CCValAssign &VA = ArgLocs[i];
2633 unsigned Reg = VA.getLocReg();
2636 case X86::EAX: case X86::EDX: case X86::ECX:
2637 if (++NumInRegs == 3)
2645 // An stdcall caller is expected to clean up its arguments; the callee
2646 // isn't going to do that.
2647 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2654 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2655 return X86::createFastISel(funcInfo);
2659 //===----------------------------------------------------------------------===//
2660 // Other Lowering Hooks
2661 //===----------------------------------------------------------------------===//
2663 static bool MayFoldLoad(SDValue Op) {
2664 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2667 static bool MayFoldIntoStore(SDValue Op) {
2668 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2671 static bool isTargetShuffle(unsigned Opcode) {
2673 default: return false;
2674 case X86ISD::PSHUFD:
2675 case X86ISD::PSHUFHW:
2676 case X86ISD::PSHUFLW:
2677 case X86ISD::SHUFPD:
2678 case X86ISD::PALIGN:
2679 case X86ISD::SHUFPS:
2680 case X86ISD::MOVLHPS:
2681 case X86ISD::MOVLHPD:
2682 case X86ISD::MOVHLPS:
2683 case X86ISD::MOVLPS:
2684 case X86ISD::MOVLPD:
2685 case X86ISD::MOVSHDUP:
2686 case X86ISD::MOVSLDUP:
2687 case X86ISD::MOVDDUP:
2690 case X86ISD::UNPCKLPS:
2691 case X86ISD::UNPCKLPD:
2692 case X86ISD::PUNPCKLWD:
2693 case X86ISD::PUNPCKLBW:
2694 case X86ISD::PUNPCKLDQ:
2695 case X86ISD::PUNPCKLQDQ:
2696 case X86ISD::UNPCKHPS:
2697 case X86ISD::UNPCKHPD:
2698 case X86ISD::PUNPCKHWD:
2699 case X86ISD::PUNPCKHBW:
2700 case X86ISD::PUNPCKHDQ:
2701 case X86ISD::PUNPCKHQDQ:
2707 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2708 SDValue V1, SelectionDAG &DAG) {
2710 default: llvm_unreachable("Unknown x86 shuffle node");
2711 case X86ISD::MOVSHDUP:
2712 case X86ISD::MOVSLDUP:
2713 case X86ISD::MOVDDUP:
2714 return DAG.getNode(Opc, dl, VT, V1);
2720 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2721 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2723 default: llvm_unreachable("Unknown x86 shuffle node");
2724 case X86ISD::PSHUFD:
2725 case X86ISD::PSHUFHW:
2726 case X86ISD::PSHUFLW:
2727 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2733 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2734 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2736 default: llvm_unreachable("Unknown x86 shuffle node");
2737 case X86ISD::PALIGN:
2738 case X86ISD::SHUFPD:
2739 case X86ISD::SHUFPS:
2740 return DAG.getNode(Opc, dl, VT, V1, V2,
2741 DAG.getConstant(TargetMask, MVT::i8));
2746 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2747 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2749 default: llvm_unreachable("Unknown x86 shuffle node");
2750 case X86ISD::MOVLHPS:
2751 case X86ISD::MOVLHPD:
2752 case X86ISD::MOVHLPS:
2753 case X86ISD::MOVLPS:
2754 case X86ISD::MOVLPD:
2757 case X86ISD::UNPCKLPS:
2758 case X86ISD::UNPCKLPD:
2759 case X86ISD::PUNPCKLWD:
2760 case X86ISD::PUNPCKLBW:
2761 case X86ISD::PUNPCKLDQ:
2762 case X86ISD::PUNPCKLQDQ:
2763 case X86ISD::UNPCKHPS:
2764 case X86ISD::UNPCKHPD:
2765 case X86ISD::PUNPCKHWD:
2766 case X86ISD::PUNPCKHBW:
2767 case X86ISD::PUNPCKHDQ:
2768 case X86ISD::PUNPCKHQDQ:
2769 return DAG.getNode(Opc, dl, VT, V1, V2);
2774 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2775 MachineFunction &MF = DAG.getMachineFunction();
2776 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2777 int ReturnAddrIndex = FuncInfo->getRAIndex();
2779 if (ReturnAddrIndex == 0) {
2780 // Set up a frame object for the return address.
2781 uint64_t SlotSize = TD->getPointerSize();
2782 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2784 FuncInfo->setRAIndex(ReturnAddrIndex);
2787 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2791 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2792 bool hasSymbolicDisplacement) {
2793 // Offset should fit into 32 bit immediate field.
2794 if (!isInt<32>(Offset))
2797 // If we don't have a symbolic displacement - we don't have any extra
2799 if (!hasSymbolicDisplacement)
2802 // FIXME: Some tweaks might be needed for medium code model.
2803 if (M != CodeModel::Small && M != CodeModel::Kernel)
2806 // For small code model we assume that latest object is 16MB before end of 31
2807 // bits boundary. We may also accept pretty large negative constants knowing
2808 // that all objects are in the positive half of address space.
2809 if (M == CodeModel::Small && Offset < 16*1024*1024)
2812 // For kernel code model we know that all object resist in the negative half
2813 // of 32bits address space. We may not accept negative offsets, since they may
2814 // be just off and we may accept pretty large positive ones.
2815 if (M == CodeModel::Kernel && Offset > 0)
2821 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2822 /// specific condition code, returning the condition code and the LHS/RHS of the
2823 /// comparison to make.
2824 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2825 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2827 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2828 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2829 // X > -1 -> X == 0, jump !sign.
2830 RHS = DAG.getConstant(0, RHS.getValueType());
2831 return X86::COND_NS;
2832 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2833 // X < 0 -> X == 0, jump on sign.
2835 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2837 RHS = DAG.getConstant(0, RHS.getValueType());
2838 return X86::COND_LE;
2842 switch (SetCCOpcode) {
2843 default: llvm_unreachable("Invalid integer condition!");
2844 case ISD::SETEQ: return X86::COND_E;
2845 case ISD::SETGT: return X86::COND_G;
2846 case ISD::SETGE: return X86::COND_GE;
2847 case ISD::SETLT: return X86::COND_L;
2848 case ISD::SETLE: return X86::COND_LE;
2849 case ISD::SETNE: return X86::COND_NE;
2850 case ISD::SETULT: return X86::COND_B;
2851 case ISD::SETUGT: return X86::COND_A;
2852 case ISD::SETULE: return X86::COND_BE;
2853 case ISD::SETUGE: return X86::COND_AE;
2857 // First determine if it is required or is profitable to flip the operands.
2859 // If LHS is a foldable load, but RHS is not, flip the condition.
2860 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2861 !ISD::isNON_EXTLoad(RHS.getNode())) {
2862 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2863 std::swap(LHS, RHS);
2866 switch (SetCCOpcode) {
2872 std::swap(LHS, RHS);
2876 // On a floating point condition, the flags are set as follows:
2878 // 0 | 0 | 0 | X > Y
2879 // 0 | 0 | 1 | X < Y
2880 // 1 | 0 | 0 | X == Y
2881 // 1 | 1 | 1 | unordered
2882 switch (SetCCOpcode) {
2883 default: llvm_unreachable("Condcode should be pre-legalized away");
2885 case ISD::SETEQ: return X86::COND_E;
2886 case ISD::SETOLT: // flipped
2888 case ISD::SETGT: return X86::COND_A;
2889 case ISD::SETOLE: // flipped
2891 case ISD::SETGE: return X86::COND_AE;
2892 case ISD::SETUGT: // flipped
2894 case ISD::SETLT: return X86::COND_B;
2895 case ISD::SETUGE: // flipped
2897 case ISD::SETLE: return X86::COND_BE;
2899 case ISD::SETNE: return X86::COND_NE;
2900 case ISD::SETUO: return X86::COND_P;
2901 case ISD::SETO: return X86::COND_NP;
2903 case ISD::SETUNE: return X86::COND_INVALID;
2907 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2908 /// code. Current x86 isa includes the following FP cmov instructions:
2909 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2910 static bool hasFPCMov(unsigned X86CC) {
2926 /// isFPImmLegal - Returns true if the target can instruction select the
2927 /// specified FP immediate natively. If false, the legalizer will
2928 /// materialize the FP immediate as a load from a constant pool.
2929 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2930 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2931 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2937 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2938 /// the specified range (L, H].
2939 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2940 return (Val < 0) || (Val >= Low && Val < Hi);
2943 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2944 /// specified value.
2945 static bool isUndefOrEqual(int Val, int CmpVal) {
2946 if (Val < 0 || Val == CmpVal)
2951 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2952 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2953 /// the second operand.
2954 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2955 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2956 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2957 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2958 return (Mask[0] < 2 && Mask[1] < 2);
2962 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2963 SmallVector<int, 8> M;
2965 return ::isPSHUFDMask(M, N->getValueType(0));
2968 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2969 /// is suitable for input to PSHUFHW.
2970 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2971 if (VT != MVT::v8i16)
2974 // Lower quadword copied in order or undef.
2975 for (int i = 0; i != 4; ++i)
2976 if (Mask[i] >= 0 && Mask[i] != i)
2979 // Upper quadword shuffled.
2980 for (int i = 4; i != 8; ++i)
2981 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2987 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2988 SmallVector<int, 8> M;
2990 return ::isPSHUFHWMask(M, N->getValueType(0));
2993 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2994 /// is suitable for input to PSHUFLW.
2995 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2996 if (VT != MVT::v8i16)
2999 // Upper quadword copied in order.
3000 for (int i = 4; i != 8; ++i)
3001 if (Mask[i] >= 0 && Mask[i] != i)
3004 // Lower quadword shuffled.
3005 for (int i = 0; i != 4; ++i)
3012 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3013 SmallVector<int, 8> M;
3015 return ::isPSHUFLWMask(M, N->getValueType(0));
3018 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3019 /// is suitable for input to PALIGNR.
3020 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3022 int i, e = VT.getVectorNumElements();
3024 // Do not handle v2i64 / v2f64 shuffles with palignr.
3025 if (e < 4 || !hasSSSE3)
3028 for (i = 0; i != e; ++i)
3032 // All undef, not a palignr.
3036 // Determine if it's ok to perform a palignr with only the LHS, since we
3037 // don't have access to the actual shuffle elements to see if RHS is undef.
3038 bool Unary = Mask[i] < (int)e;
3039 bool NeedsUnary = false;
3041 int s = Mask[i] - i;
3043 // Check the rest of the elements to see if they are consecutive.
3044 for (++i; i != e; ++i) {
3049 Unary = Unary && (m < (int)e);
3050 NeedsUnary = NeedsUnary || (m < s);
3052 if (NeedsUnary && !Unary)
3054 if (Unary && m != ((s+i) & (e-1)))
3056 if (!Unary && m != (s+i))
3062 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3063 SmallVector<int, 8> M;
3065 return ::isPALIGNRMask(M, N->getValueType(0), true);
3068 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3069 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3070 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3071 int NumElems = VT.getVectorNumElements();
3072 if (NumElems != 2 && NumElems != 4)
3075 int Half = NumElems / 2;
3076 for (int i = 0; i < Half; ++i)
3077 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3079 for (int i = Half; i < NumElems; ++i)
3080 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3086 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3087 SmallVector<int, 8> M;
3089 return ::isSHUFPMask(M, N->getValueType(0));
3092 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3093 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3094 /// half elements to come from vector 1 (which would equal the dest.) and
3095 /// the upper half to come from vector 2.
3096 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3097 int NumElems = VT.getVectorNumElements();
3099 if (NumElems != 2 && NumElems != 4)
3102 int Half = NumElems / 2;
3103 for (int i = 0; i < Half; ++i)
3104 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3106 for (int i = Half; i < NumElems; ++i)
3107 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3112 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3113 SmallVector<int, 8> M;
3115 return isCommutedSHUFPMask(M, N->getValueType(0));
3118 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3119 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3120 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3121 if (N->getValueType(0).getVectorNumElements() != 4)
3124 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3125 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3126 isUndefOrEqual(N->getMaskElt(1), 7) &&
3127 isUndefOrEqual(N->getMaskElt(2), 2) &&
3128 isUndefOrEqual(N->getMaskElt(3), 3);
3131 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3132 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3134 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3135 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3140 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3141 isUndefOrEqual(N->getMaskElt(1), 3) &&
3142 isUndefOrEqual(N->getMaskElt(2), 2) &&
3143 isUndefOrEqual(N->getMaskElt(3), 3);
3146 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3147 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3148 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3149 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3151 if (NumElems != 2 && NumElems != 4)
3154 for (unsigned i = 0; i < NumElems/2; ++i)
3155 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3158 for (unsigned i = NumElems/2; i < NumElems; ++i)
3159 if (!isUndefOrEqual(N->getMaskElt(i), i))
3165 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3166 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3167 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3168 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3170 if (NumElems != 2 && NumElems != 4)
3173 for (unsigned i = 0; i < NumElems/2; ++i)
3174 if (!isUndefOrEqual(N->getMaskElt(i), i))
3177 for (unsigned i = 0; i < NumElems/2; ++i)
3178 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3184 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3185 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3186 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3187 bool V2IsSplat = false) {
3188 int NumElts = VT.getVectorNumElements();
3189 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3192 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3194 int BitI1 = Mask[i+1];
3195 if (!isUndefOrEqual(BitI, j))
3198 if (!isUndefOrEqual(BitI1, NumElts))
3201 if (!isUndefOrEqual(BitI1, j + NumElts))
3208 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3209 SmallVector<int, 8> M;
3211 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3214 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3215 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3216 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3217 bool V2IsSplat = false) {
3218 int NumElts = VT.getVectorNumElements();
3219 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3222 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3224 int BitI1 = Mask[i+1];
3225 if (!isUndefOrEqual(BitI, j + NumElts/2))
3228 if (isUndefOrEqual(BitI1, NumElts))
3231 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3238 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3239 SmallVector<int, 8> M;
3241 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3244 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3245 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3247 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3248 int NumElems = VT.getVectorNumElements();
3249 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3252 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3254 int BitI1 = Mask[i+1];
3255 if (!isUndefOrEqual(BitI, j))
3257 if (!isUndefOrEqual(BitI1, j))
3263 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3264 SmallVector<int, 8> M;
3266 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3269 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3270 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3272 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3273 int NumElems = VT.getVectorNumElements();
3274 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3277 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3279 int BitI1 = Mask[i+1];
3280 if (!isUndefOrEqual(BitI, j))
3282 if (!isUndefOrEqual(BitI1, j))
3288 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3289 SmallVector<int, 8> M;
3291 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3294 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3295 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3296 /// MOVSD, and MOVD, i.e. setting the lowest element.
3297 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3298 if (VT.getVectorElementType().getSizeInBits() < 32)
3301 int NumElts = VT.getVectorNumElements();
3303 if (!isUndefOrEqual(Mask[0], NumElts))
3306 for (int i = 1; i < NumElts; ++i)
3307 if (!isUndefOrEqual(Mask[i], i))
3313 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3314 SmallVector<int, 8> M;
3316 return ::isMOVLMask(M, N->getValueType(0));
3319 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3320 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3321 /// element of vector 2 and the other elements to come from vector 1 in order.
3322 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3323 bool V2IsSplat = false, bool V2IsUndef = false) {
3324 int NumOps = VT.getVectorNumElements();
3325 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3328 if (!isUndefOrEqual(Mask[0], 0))
3331 for (int i = 1; i < NumOps; ++i)
3332 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3333 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3334 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3340 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3341 bool V2IsUndef = false) {
3342 SmallVector<int, 8> M;
3344 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3347 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3348 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3349 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3350 if (N->getValueType(0).getVectorNumElements() != 4)
3353 // Expect 1, 1, 3, 3
3354 for (unsigned i = 0; i < 2; ++i) {
3355 int Elt = N->getMaskElt(i);
3356 if (Elt >= 0 && Elt != 1)
3361 for (unsigned i = 2; i < 4; ++i) {
3362 int Elt = N->getMaskElt(i);
3363 if (Elt >= 0 && Elt != 3)
3368 // Don't use movshdup if it can be done with a shufps.
3369 // FIXME: verify that matching u, u, 3, 3 is what we want.
3373 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3374 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3375 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3376 if (N->getValueType(0).getVectorNumElements() != 4)
3379 // Expect 0, 0, 2, 2
3380 for (unsigned i = 0; i < 2; ++i)
3381 if (N->getMaskElt(i) > 0)
3385 for (unsigned i = 2; i < 4; ++i) {
3386 int Elt = N->getMaskElt(i);
3387 if (Elt >= 0 && Elt != 2)
3392 // Don't use movsldup if it can be done with a shufps.
3396 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3397 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3398 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3399 int e = N->getValueType(0).getVectorNumElements() / 2;
3401 for (int i = 0; i < e; ++i)
3402 if (!isUndefOrEqual(N->getMaskElt(i), i))
3404 for (int i = 0; i < e; ++i)
3405 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3410 /// isVEXTRACTF128Index - Return true if the specified
3411 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3412 /// suitable for input to VEXTRACTF128.
3413 bool X86::isVEXTRACTF128Index(SDNode *N) {
3414 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3417 // The index should be aligned on a 128-bit boundary.
3419 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3421 unsigned VL = N->getValueType(0).getVectorNumElements();
3422 unsigned VBits = N->getValueType(0).getSizeInBits();
3423 unsigned ElSize = VBits / VL;
3424 bool Result = (Index * ElSize) % 128 == 0;
3429 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3430 /// operand specifies a subvector insert that is suitable for input to
3432 bool X86::isVINSERTF128Index(SDNode *N) {
3433 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3436 // The index should be aligned on a 128-bit boundary.
3438 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3440 unsigned VL = N->getValueType(0).getVectorNumElements();
3441 unsigned VBits = N->getValueType(0).getSizeInBits();
3442 unsigned ElSize = VBits / VL;
3443 bool Result = (Index * ElSize) % 128 == 0;
3448 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3449 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3450 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3451 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3452 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3454 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3456 for (int i = 0; i < NumOperands; ++i) {
3457 int Val = SVOp->getMaskElt(NumOperands-i-1);
3458 if (Val < 0) Val = 0;
3459 if (Val >= NumOperands) Val -= NumOperands;
3461 if (i != NumOperands - 1)
3467 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3468 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3469 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3470 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3472 // 8 nodes, but we only care about the last 4.
3473 for (unsigned i = 7; i >= 4; --i) {
3474 int Val = SVOp->getMaskElt(i);
3483 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3484 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3485 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3486 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3488 // 8 nodes, but we only care about the first 4.
3489 for (int i = 3; i >= 0; --i) {
3490 int Val = SVOp->getMaskElt(i);
3499 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3500 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3501 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3502 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3503 EVT VVT = N->getValueType(0);
3504 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3508 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3509 Val = SVOp->getMaskElt(i);
3513 return (Val - i) * EltSize;
3516 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3517 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3519 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3520 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3521 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3524 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3526 EVT VecVT = N->getOperand(0).getValueType();
3527 EVT ElVT = VecVT.getVectorElementType();
3529 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3531 return Index / NumElemsPerChunk;
3534 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3535 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3537 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3538 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3539 llvm_unreachable("Illegal insert subvector for VINSERTF128");
3542 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3544 EVT VecVT = N->getValueType(0);
3545 EVT ElVT = VecVT.getVectorElementType();
3547 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3549 return Index / NumElemsPerChunk;
3552 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3554 bool X86::isZeroNode(SDValue Elt) {
3555 return ((isa<ConstantSDNode>(Elt) &&
3556 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3557 (isa<ConstantFPSDNode>(Elt) &&
3558 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3561 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3562 /// their permute mask.
3563 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3564 SelectionDAG &DAG) {
3565 EVT VT = SVOp->getValueType(0);
3566 unsigned NumElems = VT.getVectorNumElements();
3567 SmallVector<int, 8> MaskVec;
3569 for (unsigned i = 0; i != NumElems; ++i) {
3570 int idx = SVOp->getMaskElt(i);
3572 MaskVec.push_back(idx);
3573 else if (idx < (int)NumElems)
3574 MaskVec.push_back(idx + NumElems);
3576 MaskVec.push_back(idx - NumElems);
3578 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3579 SVOp->getOperand(0), &MaskVec[0]);
3582 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3583 /// the two vector operands have swapped position.
3584 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3585 unsigned NumElems = VT.getVectorNumElements();
3586 for (unsigned i = 0; i != NumElems; ++i) {
3590 else if (idx < (int)NumElems)
3591 Mask[i] = idx + NumElems;
3593 Mask[i] = idx - NumElems;
3597 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3598 /// match movhlps. The lower half elements should come from upper half of
3599 /// V1 (and in order), and the upper half elements should come from the upper
3600 /// half of V2 (and in order).
3601 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3602 if (Op->getValueType(0).getVectorNumElements() != 4)
3604 for (unsigned i = 0, e = 2; i != e; ++i)
3605 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3607 for (unsigned i = 2; i != 4; ++i)
3608 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3613 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3614 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3616 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3617 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3619 N = N->getOperand(0).getNode();
3620 if (!ISD::isNON_EXTLoad(N))
3623 *LD = cast<LoadSDNode>(N);
3627 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3628 /// match movlp{s|d}. The lower half elements should come from lower half of
3629 /// V1 (and in order), and the upper half elements should come from the upper
3630 /// half of V2 (and in order). And since V1 will become the source of the
3631 /// MOVLP, it must be either a vector load or a scalar load to vector.
3632 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3633 ShuffleVectorSDNode *Op) {
3634 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3636 // Is V2 is a vector load, don't do this transformation. We will try to use
3637 // load folding shufps op.
3638 if (ISD::isNON_EXTLoad(V2))
3641 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3643 if (NumElems != 2 && NumElems != 4)
3645 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3646 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3648 for (unsigned i = NumElems/2; i != NumElems; ++i)
3649 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3654 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3656 static bool isSplatVector(SDNode *N) {
3657 if (N->getOpcode() != ISD::BUILD_VECTOR)
3660 SDValue SplatValue = N->getOperand(0);
3661 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3662 if (N->getOperand(i) != SplatValue)
3667 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3668 /// to an zero vector.
3669 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3670 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3671 SDValue V1 = N->getOperand(0);
3672 SDValue V2 = N->getOperand(1);
3673 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3674 for (unsigned i = 0; i != NumElems; ++i) {
3675 int Idx = N->getMaskElt(i);
3676 if (Idx >= (int)NumElems) {
3677 unsigned Opc = V2.getOpcode();
3678 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3680 if (Opc != ISD::BUILD_VECTOR ||
3681 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3683 } else if (Idx >= 0) {
3684 unsigned Opc = V1.getOpcode();
3685 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3687 if (Opc != ISD::BUILD_VECTOR ||
3688 !X86::isZeroNode(V1.getOperand(Idx)))
3695 /// getZeroVector - Returns a vector of specified type with all zero elements.
3697 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3699 assert(VT.isVector() && "Expected a vector type");
3701 // Always build SSE zero vectors as <4 x i32> bitcasted
3702 // to their dest type. This ensures they get CSE'd.
3704 if (VT.getSizeInBits() == 128) { // SSE
3705 if (HasSSE2) { // SSE2
3706 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3707 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3709 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3710 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3712 } else if (VT.getSizeInBits() == 256) { // AVX
3713 // 256-bit logic and arithmetic instructions in AVX are
3714 // all floating-point, no support for integer ops. Default
3715 // to emitting fp zeroed vectors then.
3716 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3717 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3718 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3720 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3723 /// getOnesVector - Returns a vector of specified type with all bits set.
3725 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3726 assert(VT.isVector() && "Expected a vector type");
3728 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3729 // type. This ensures they get CSE'd.
3730 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3732 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3733 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3737 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3738 /// that point to V2 points to its first element.
3739 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3740 EVT VT = SVOp->getValueType(0);
3741 unsigned NumElems = VT.getVectorNumElements();
3743 bool Changed = false;
3744 SmallVector<int, 8> MaskVec;
3745 SVOp->getMask(MaskVec);
3747 for (unsigned i = 0; i != NumElems; ++i) {
3748 if (MaskVec[i] > (int)NumElems) {
3749 MaskVec[i] = NumElems;
3754 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3755 SVOp->getOperand(1), &MaskVec[0]);
3756 return SDValue(SVOp, 0);
3759 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3760 /// operation of specified width.
3761 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3763 unsigned NumElems = VT.getVectorNumElements();
3764 SmallVector<int, 8> Mask;
3765 Mask.push_back(NumElems);
3766 for (unsigned i = 1; i != NumElems; ++i)
3768 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3771 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3772 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3774 unsigned NumElems = VT.getVectorNumElements();
3775 SmallVector<int, 8> Mask;
3776 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3778 Mask.push_back(i + NumElems);
3780 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3783 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3784 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3786 unsigned NumElems = VT.getVectorNumElements();
3787 unsigned Half = NumElems/2;
3788 SmallVector<int, 8> Mask;
3789 for (unsigned i = 0; i != Half; ++i) {
3790 Mask.push_back(i + Half);
3791 Mask.push_back(i + NumElems + Half);
3793 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3796 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3797 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3798 EVT PVT = MVT::v4f32;
3799 EVT VT = SV->getValueType(0);
3800 DebugLoc dl = SV->getDebugLoc();
3801 SDValue V1 = SV->getOperand(0);
3802 int NumElems = VT.getVectorNumElements();
3803 int EltNo = SV->getSplatIndex();
3805 // unpack elements to the correct location
3806 while (NumElems > 4) {
3807 if (EltNo < NumElems/2) {
3808 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3810 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3811 EltNo -= NumElems/2;
3816 // Perform the splat.
3817 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3818 V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3819 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3820 return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3823 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3824 /// vector of zero or undef vector. This produces a shuffle where the low
3825 /// element of V2 is swizzled into the zero/undef vector, landing at element
3826 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3827 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3828 bool isZero, bool HasSSE2,
3829 SelectionDAG &DAG) {
3830 EVT VT = V2.getValueType();
3832 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3833 unsigned NumElems = VT.getVectorNumElements();
3834 SmallVector<int, 16> MaskVec;
3835 for (unsigned i = 0; i != NumElems; ++i)
3836 // If this is the insertion idx, put the low elt of V2 here.
3837 MaskVec.push_back(i == Idx ? NumElems : i);
3838 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3841 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3842 /// element of the result of the vector shuffle.
3843 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3846 return SDValue(); // Limit search depth.
3848 SDValue V = SDValue(N, 0);
3849 EVT VT = V.getValueType();
3850 unsigned Opcode = V.getOpcode();
3852 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3853 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3854 Index = SV->getMaskElt(Index);
3857 return DAG.getUNDEF(VT.getVectorElementType());
3859 int NumElems = VT.getVectorNumElements();
3860 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3861 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3864 // Recurse into target specific vector shuffles to find scalars.
3865 if (isTargetShuffle(Opcode)) {
3866 int NumElems = VT.getVectorNumElements();
3867 SmallVector<unsigned, 16> ShuffleMask;
3871 case X86ISD::SHUFPS:
3872 case X86ISD::SHUFPD:
3873 ImmN = N->getOperand(N->getNumOperands()-1);
3874 DecodeSHUFPSMask(NumElems,
3875 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3878 case X86ISD::PUNPCKHBW:
3879 case X86ISD::PUNPCKHWD:
3880 case X86ISD::PUNPCKHDQ:
3881 case X86ISD::PUNPCKHQDQ:
3882 DecodePUNPCKHMask(NumElems, ShuffleMask);
3884 case X86ISD::UNPCKHPS:
3885 case X86ISD::UNPCKHPD:
3886 DecodeUNPCKHPMask(NumElems, ShuffleMask);
3888 case X86ISD::PUNPCKLBW:
3889 case X86ISD::PUNPCKLWD:
3890 case X86ISD::PUNPCKLDQ:
3891 case X86ISD::PUNPCKLQDQ:
3892 DecodePUNPCKLMask(NumElems, ShuffleMask);
3894 case X86ISD::UNPCKLPS:
3895 case X86ISD::UNPCKLPD:
3896 DecodeUNPCKLPMask(NumElems, ShuffleMask);
3898 case X86ISD::MOVHLPS:
3899 DecodeMOVHLPSMask(NumElems, ShuffleMask);
3901 case X86ISD::MOVLHPS:
3902 DecodeMOVLHPSMask(NumElems, ShuffleMask);
3904 case X86ISD::PSHUFD:
3905 ImmN = N->getOperand(N->getNumOperands()-1);
3906 DecodePSHUFMask(NumElems,
3907 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3910 case X86ISD::PSHUFHW:
3911 ImmN = N->getOperand(N->getNumOperands()-1);
3912 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3915 case X86ISD::PSHUFLW:
3916 ImmN = N->getOperand(N->getNumOperands()-1);
3917 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3921 case X86ISD::MOVSD: {
3922 // The index 0 always comes from the first element of the second source,
3923 // this is why MOVSS and MOVSD are used in the first place. The other
3924 // elements come from the other positions of the first source vector.
3925 unsigned OpNum = (Index == 0) ? 1 : 0;
3926 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3930 assert("not implemented for target shuffle node");
3934 Index = ShuffleMask[Index];
3936 return DAG.getUNDEF(VT.getVectorElementType());
3938 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3939 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3943 // Actual nodes that may contain scalar elements
3944 if (Opcode == ISD::BITCAST) {
3945 V = V.getOperand(0);
3946 EVT SrcVT = V.getValueType();
3947 unsigned NumElems = VT.getVectorNumElements();
3949 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3953 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3954 return (Index == 0) ? V.getOperand(0)
3955 : DAG.getUNDEF(VT.getVectorElementType());
3957 if (V.getOpcode() == ISD::BUILD_VECTOR)
3958 return V.getOperand(Index);
3963 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3964 /// shuffle operation which come from a consecutively from a zero. The
3965 /// search can start in two diferent directions, from left or right.
3967 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3968 bool ZerosFromLeft, SelectionDAG &DAG) {
3971 while (i < NumElems) {
3972 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3973 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3974 if (!(Elt.getNode() &&
3975 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3983 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3984 /// MaskE correspond consecutively to elements from one of the vector operands,
3985 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3987 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3988 int OpIdx, int NumElems, unsigned &OpNum) {
3989 bool SeenV1 = false;
3990 bool SeenV2 = false;
3992 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3993 int Idx = SVOp->getMaskElt(i);
3994 // Ignore undef indicies
4003 // Only accept consecutive elements from the same vector
4004 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4008 OpNum = SeenV1 ? 0 : 1;
4012 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4013 /// logical left shift of a vector.
4014 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4015 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4016 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4017 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4018 false /* check zeros from right */, DAG);
4024 // Considering the elements in the mask that are not consecutive zeros,
4025 // check if they consecutively come from only one of the source vectors.
4027 // V1 = {X, A, B, C} 0
4029 // vector_shuffle V1, V2 <1, 2, 3, X>
4031 if (!isShuffleMaskConsecutive(SVOp,
4032 0, // Mask Start Index
4033 NumElems-NumZeros-1, // Mask End Index
4034 NumZeros, // Where to start looking in the src vector
4035 NumElems, // Number of elements in vector
4036 OpSrc)) // Which source operand ?
4041 ShVal = SVOp->getOperand(OpSrc);
4045 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4046 /// logical left shift of a vector.
4047 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4048 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4049 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4050 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4051 true /* check zeros from left */, DAG);
4057 // Considering the elements in the mask that are not consecutive zeros,
4058 // check if they consecutively come from only one of the source vectors.
4060 // 0 { A, B, X, X } = V2
4062 // vector_shuffle V1, V2 <X, X, 4, 5>
4064 if (!isShuffleMaskConsecutive(SVOp,
4065 NumZeros, // Mask Start Index
4066 NumElems-1, // Mask End Index
4067 0, // Where to start looking in the src vector
4068 NumElems, // Number of elements in vector
4069 OpSrc)) // Which source operand ?
4074 ShVal = SVOp->getOperand(OpSrc);
4078 /// isVectorShift - Returns true if the shuffle can be implemented as a
4079 /// logical left or right shift of a vector.
4080 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4081 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4082 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4083 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4089 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4091 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4092 unsigned NumNonZero, unsigned NumZero,
4094 const TargetLowering &TLI) {
4098 DebugLoc dl = Op.getDebugLoc();
4101 for (unsigned i = 0; i < 16; ++i) {
4102 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4103 if (ThisIsNonZero && First) {
4105 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4107 V = DAG.getUNDEF(MVT::v8i16);
4112 SDValue ThisElt(0, 0), LastElt(0, 0);
4113 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4114 if (LastIsNonZero) {
4115 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4116 MVT::i16, Op.getOperand(i-1));
4118 if (ThisIsNonZero) {
4119 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4120 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4121 ThisElt, DAG.getConstant(8, MVT::i8));
4123 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4127 if (ThisElt.getNode())
4128 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4129 DAG.getIntPtrConstant(i/2));
4133 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4136 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4138 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4139 unsigned NumNonZero, unsigned NumZero,
4141 const TargetLowering &TLI) {
4145 DebugLoc dl = Op.getDebugLoc();
4148 for (unsigned i = 0; i < 8; ++i) {
4149 bool isNonZero = (NonZeros & (1 << i)) != 0;
4153 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4155 V = DAG.getUNDEF(MVT::v8i16);
4158 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4159 MVT::v8i16, V, Op.getOperand(i),
4160 DAG.getIntPtrConstant(i));
4167 /// getVShift - Return a vector logical shift node.
4169 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4170 unsigned NumBits, SelectionDAG &DAG,
4171 const TargetLowering &TLI, DebugLoc dl) {
4172 EVT ShVT = MVT::v2i64;
4173 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4174 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4175 return DAG.getNode(ISD::BITCAST, dl, VT,
4176 DAG.getNode(Opc, dl, ShVT, SrcOp,
4177 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
4181 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4182 SelectionDAG &DAG) const {
4184 // Check if the scalar load can be widened into a vector load. And if
4185 // the address is "base + cst" see if the cst can be "absorbed" into
4186 // the shuffle mask.
4187 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4188 SDValue Ptr = LD->getBasePtr();
4189 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4191 EVT PVT = LD->getValueType(0);
4192 if (PVT != MVT::i32 && PVT != MVT::f32)
4197 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4198 FI = FINode->getIndex();
4200 } else if (Ptr.getOpcode() == ISD::ADD &&
4201 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4202 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4203 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4204 Offset = Ptr.getConstantOperandVal(1);
4205 Ptr = Ptr.getOperand(0);
4210 SDValue Chain = LD->getChain();
4211 // Make sure the stack object alignment is at least 16.
4212 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4213 if (DAG.InferPtrAlignment(Ptr) < 16) {
4214 if (MFI->isFixedObjectIndex(FI)) {
4215 // Can't change the alignment. FIXME: It's possible to compute
4216 // the exact stack offset and reference FI + adjust offset instead.
4217 // If someone *really* cares about this. That's the way to implement it.
4220 MFI->setObjectAlignment(FI, 16);
4224 // (Offset % 16) must be multiple of 4. Then address is then
4225 // Ptr + (Offset & ~15).
4228 if ((Offset % 16) & 3)
4230 int64_t StartOffset = Offset & ~15;
4232 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4233 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4235 int EltNo = (Offset - StartOffset) >> 2;
4236 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4237 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4238 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4239 LD->getPointerInfo().getWithOffset(StartOffset),
4241 // Canonicalize it to a v4i32 shuffle.
4242 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4243 return DAG.getNode(ISD::BITCAST, dl, VT,
4244 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4245 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4251 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4252 /// vector of type 'VT', see if the elements can be replaced by a single large
4253 /// load which has the same value as a build_vector whose operands are 'elts'.
4255 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4257 /// FIXME: we'd also like to handle the case where the last elements are zero
4258 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4259 /// There's even a handy isZeroNode for that purpose.
4260 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4261 DebugLoc &DL, SelectionDAG &DAG) {
4262 EVT EltVT = VT.getVectorElementType();
4263 unsigned NumElems = Elts.size();
4265 LoadSDNode *LDBase = NULL;
4266 unsigned LastLoadedElt = -1U;
4268 // For each element in the initializer, see if we've found a load or an undef.
4269 // If we don't find an initial load element, or later load elements are
4270 // non-consecutive, bail out.
4271 for (unsigned i = 0; i < NumElems; ++i) {
4272 SDValue Elt = Elts[i];
4274 if (!Elt.getNode() ||
4275 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4278 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4280 LDBase = cast<LoadSDNode>(Elt.getNode());
4284 if (Elt.getOpcode() == ISD::UNDEF)
4287 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4288 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4293 // If we have found an entire vector of loads and undefs, then return a large
4294 // load of the entire vector width starting at the base pointer. If we found
4295 // consecutive loads for the low half, generate a vzext_load node.
4296 if (LastLoadedElt == NumElems - 1) {
4297 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4298 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4299 LDBase->getPointerInfo(),
4300 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4301 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4302 LDBase->getPointerInfo(),
4303 LDBase->isVolatile(), LDBase->isNonTemporal(),
4304 LDBase->getAlignment());
4305 } else if (NumElems == 4 && LastLoadedElt == 1) {
4306 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4307 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4308 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4310 LDBase->getMemOperand());
4311 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4317 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4318 DebugLoc dl = Op.getDebugLoc();
4320 EVT VT = Op.getValueType();
4321 EVT ExtVT = VT.getVectorElementType();
4323 unsigned NumElems = Op.getNumOperands();
4325 // For AVX-length vectors, build the individual 128-bit pieces and
4326 // use shuffles to put them in place.
4327 if (VT.getSizeInBits() > 256 &&
4328 Subtarget->hasAVX() &&
4330 !ISD::isBuildVectorAllZeros(Op.getNode())) {
4331 SmallVector<SDValue, 8> V;
4333 for (unsigned i = 0; i < NumElems; ++i) {
4334 V[i] = Op.getOperand(i);
4337 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4339 // Build the lower subvector.
4340 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4341 // Build the upper subvector.
4342 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4345 return ConcatVectors(Lower, Upper, DAG);
4348 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4349 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4350 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4351 // is present, so AllOnes is ignored.
4352 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4353 (Op.getValueType().getSizeInBits() != 256 &&
4354 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4355 // Canonicalize this to <4 x i32> (SSE) to
4356 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4357 // eliminated on x86-32 hosts.
4358 if (Op.getValueType() == MVT::v4i32)
4361 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4362 return getOnesVector(Op.getValueType(), DAG, dl);
4363 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4366 unsigned EVTBits = ExtVT.getSizeInBits();
4368 unsigned NumZero = 0;
4369 unsigned NumNonZero = 0;
4370 unsigned NonZeros = 0;
4371 bool IsAllConstants = true;
4372 SmallSet<SDValue, 8> Values;
4373 for (unsigned i = 0; i < NumElems; ++i) {
4374 SDValue Elt = Op.getOperand(i);
4375 if (Elt.getOpcode() == ISD::UNDEF)
4378 if (Elt.getOpcode() != ISD::Constant &&
4379 Elt.getOpcode() != ISD::ConstantFP)
4380 IsAllConstants = false;
4381 if (X86::isZeroNode(Elt))
4384 NonZeros |= (1 << i);
4389 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4390 if (NumNonZero == 0)
4391 return DAG.getUNDEF(VT);
4393 // Special case for single non-zero, non-undef, element.
4394 if (NumNonZero == 1) {
4395 unsigned Idx = CountTrailingZeros_32(NonZeros);
4396 SDValue Item = Op.getOperand(Idx);
4398 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4399 // the value are obviously zero, truncate the value to i32 and do the
4400 // insertion that way. Only do this if the value is non-constant or if the
4401 // value is a constant being inserted into element 0. It is cheaper to do
4402 // a constant pool load than it is to do a movd + shuffle.
4403 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4404 (!IsAllConstants || Idx == 0)) {
4405 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4407 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4408 EVT VecVT = MVT::v4i32;
4409 unsigned VecElts = 4;
4411 // Truncate the value (which may itself be a constant) to i32, and
4412 // convert it to a vector with movd (S2V+shuffle to zero extend).
4413 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4414 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4415 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4416 Subtarget->hasSSE2(), DAG);
4418 // Now we have our 32-bit value zero extended in the low element of
4419 // a vector. If Idx != 0, swizzle it into place.
4421 SmallVector<int, 4> Mask;
4422 Mask.push_back(Idx);
4423 for (unsigned i = 1; i != VecElts; ++i)
4425 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4426 DAG.getUNDEF(Item.getValueType()),
4429 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4433 // If we have a constant or non-constant insertion into the low element of
4434 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4435 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4436 // depending on what the source datatype is.
4439 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4440 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4441 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4442 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4443 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4444 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4446 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4447 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4448 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4449 EVT MiddleVT = MVT::v4i32;
4450 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4451 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4452 Subtarget->hasSSE2(), DAG);
4453 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4457 // Is it a vector logical left shift?
4458 if (NumElems == 2 && Idx == 1 &&
4459 X86::isZeroNode(Op.getOperand(0)) &&
4460 !X86::isZeroNode(Op.getOperand(1))) {
4461 unsigned NumBits = VT.getSizeInBits();
4462 return getVShift(true, VT,
4463 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4464 VT, Op.getOperand(1)),
4465 NumBits/2, DAG, *this, dl);
4468 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4471 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4472 // is a non-constant being inserted into an element other than the low one,
4473 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4474 // movd/movss) to move this into the low element, then shuffle it into
4476 if (EVTBits == 32) {
4477 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4479 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4480 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4481 Subtarget->hasSSE2(), DAG);
4482 SmallVector<int, 8> MaskVec;
4483 for (unsigned i = 0; i < NumElems; i++)
4484 MaskVec.push_back(i == Idx ? 0 : 1);
4485 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4489 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4490 if (Values.size() == 1) {
4491 if (EVTBits == 32) {
4492 // Instead of a shuffle like this:
4493 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4494 // Check if it's possible to issue this instead.
4495 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4496 unsigned Idx = CountTrailingZeros_32(NonZeros);
4497 SDValue Item = Op.getOperand(Idx);
4498 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4499 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4504 // A vector full of immediates; various special cases are already
4505 // handled, so this is best done with a single constant-pool load.
4509 // Let legalizer expand 2-wide build_vectors.
4510 if (EVTBits == 64) {
4511 if (NumNonZero == 1) {
4512 // One half is zero or undef.
4513 unsigned Idx = CountTrailingZeros_32(NonZeros);
4514 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4515 Op.getOperand(Idx));
4516 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4517 Subtarget->hasSSE2(), DAG);
4522 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4523 if (EVTBits == 8 && NumElems == 16) {
4524 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4526 if (V.getNode()) return V;
4529 if (EVTBits == 16 && NumElems == 8) {
4530 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4532 if (V.getNode()) return V;
4535 // If element VT is == 32 bits, turn it into a number of shuffles.
4536 SmallVector<SDValue, 8> V;
4538 if (NumElems == 4 && NumZero > 0) {
4539 for (unsigned i = 0; i < 4; ++i) {
4540 bool isZero = !(NonZeros & (1 << i));
4542 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4544 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4547 for (unsigned i = 0; i < 2; ++i) {
4548 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4551 V[i] = V[i*2]; // Must be a zero vector.
4554 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4557 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4560 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4565 SmallVector<int, 8> MaskVec;
4566 bool Reverse = (NonZeros & 0x3) == 2;
4567 for (unsigned i = 0; i < 2; ++i)
4568 MaskVec.push_back(Reverse ? 1-i : i);
4569 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4570 for (unsigned i = 0; i < 2; ++i)
4571 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4572 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4575 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4576 // Check for a build vector of consecutive loads.
4577 for (unsigned i = 0; i < NumElems; ++i)
4578 V[i] = Op.getOperand(i);
4580 // Check for elements which are consecutive loads.
4581 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4585 // For SSE 4.1, use insertps to put the high elements into the low element.
4586 if (getSubtarget()->hasSSE41()) {
4588 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4589 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4591 Result = DAG.getUNDEF(VT);
4593 for (unsigned i = 1; i < NumElems; ++i) {
4594 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4595 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4596 Op.getOperand(i), DAG.getIntPtrConstant(i));
4601 // Otherwise, expand into a number of unpckl*, start by extending each of
4602 // our (non-undef) elements to the full vector width with the element in the
4603 // bottom slot of the vector (which generates no code for SSE).
4604 for (unsigned i = 0; i < NumElems; ++i) {
4605 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4606 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4608 V[i] = DAG.getUNDEF(VT);
4611 // Next, we iteratively mix elements, e.g. for v4f32:
4612 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4613 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4614 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4615 unsigned EltStride = NumElems >> 1;
4616 while (EltStride != 0) {
4617 for (unsigned i = 0; i < EltStride; ++i) {
4618 // If V[i+EltStride] is undef and this is the first round of mixing,
4619 // then it is safe to just drop this shuffle: V[i] is already in the
4620 // right place, the one element (since it's the first round) being
4621 // inserted as undef can be dropped. This isn't safe for successive
4622 // rounds because they will permute elements within both vectors.
4623 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4624 EltStride == NumElems/2)
4627 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4637 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4638 // We support concatenate two MMX registers and place them in a MMX
4639 // register. This is better than doing a stack convert.
4640 DebugLoc dl = Op.getDebugLoc();
4641 EVT ResVT = Op.getValueType();
4642 assert(Op.getNumOperands() == 2);
4643 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4644 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4646 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4647 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4648 InVec = Op.getOperand(1);
4649 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4650 unsigned NumElts = ResVT.getVectorNumElements();
4651 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4652 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4653 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4655 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4656 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4657 Mask[0] = 0; Mask[1] = 2;
4658 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4660 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4663 // v8i16 shuffles - Prefer shuffles in the following order:
4664 // 1. [all] pshuflw, pshufhw, optional move
4665 // 2. [ssse3] 1 x pshufb
4666 // 3. [ssse3] 2 x pshufb + 1 x por
4667 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4669 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4670 SelectionDAG &DAG) const {
4671 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4672 SDValue V1 = SVOp->getOperand(0);
4673 SDValue V2 = SVOp->getOperand(1);
4674 DebugLoc dl = SVOp->getDebugLoc();
4675 SmallVector<int, 8> MaskVals;
4677 // Determine if more than 1 of the words in each of the low and high quadwords
4678 // of the result come from the same quadword of one of the two inputs. Undef
4679 // mask values count as coming from any quadword, for better codegen.
4680 SmallVector<unsigned, 4> LoQuad(4);
4681 SmallVector<unsigned, 4> HiQuad(4);
4682 BitVector InputQuads(4);
4683 for (unsigned i = 0; i < 8; ++i) {
4684 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4685 int EltIdx = SVOp->getMaskElt(i);
4686 MaskVals.push_back(EltIdx);
4695 InputQuads.set(EltIdx / 4);
4698 int BestLoQuad = -1;
4699 unsigned MaxQuad = 1;
4700 for (unsigned i = 0; i < 4; ++i) {
4701 if (LoQuad[i] > MaxQuad) {
4703 MaxQuad = LoQuad[i];
4707 int BestHiQuad = -1;
4709 for (unsigned i = 0; i < 4; ++i) {
4710 if (HiQuad[i] > MaxQuad) {
4712 MaxQuad = HiQuad[i];
4716 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4717 // of the two input vectors, shuffle them into one input vector so only a
4718 // single pshufb instruction is necessary. If There are more than 2 input
4719 // quads, disable the next transformation since it does not help SSSE3.
4720 bool V1Used = InputQuads[0] || InputQuads[1];
4721 bool V2Used = InputQuads[2] || InputQuads[3];
4722 if (Subtarget->hasSSSE3()) {
4723 if (InputQuads.count() == 2 && V1Used && V2Used) {
4724 BestLoQuad = InputQuads.find_first();
4725 BestHiQuad = InputQuads.find_next(BestLoQuad);
4727 if (InputQuads.count() > 2) {
4733 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4734 // the shuffle mask. If a quad is scored as -1, that means that it contains
4735 // words from all 4 input quadwords.
4737 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4738 SmallVector<int, 8> MaskV;
4739 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4740 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4741 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4742 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4743 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4744 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4746 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4747 // source words for the shuffle, to aid later transformations.
4748 bool AllWordsInNewV = true;
4749 bool InOrder[2] = { true, true };
4750 for (unsigned i = 0; i != 8; ++i) {
4751 int idx = MaskVals[i];
4753 InOrder[i/4] = false;
4754 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4756 AllWordsInNewV = false;
4760 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4761 if (AllWordsInNewV) {
4762 for (int i = 0; i != 8; ++i) {
4763 int idx = MaskVals[i];
4766 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4767 if ((idx != i) && idx < 4)
4769 if ((idx != i) && idx > 3)
4778 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4779 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4780 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4781 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4782 unsigned TargetMask = 0;
4783 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4784 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4785 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4786 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4787 V1 = NewV.getOperand(0);
4788 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4792 // If we have SSSE3, and all words of the result are from 1 input vector,
4793 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4794 // is present, fall back to case 4.
4795 if (Subtarget->hasSSSE3()) {
4796 SmallVector<SDValue,16> pshufbMask;
4798 // If we have elements from both input vectors, set the high bit of the
4799 // shuffle mask element to zero out elements that come from V2 in the V1
4800 // mask, and elements that come from V1 in the V2 mask, so that the two
4801 // results can be OR'd together.
4802 bool TwoInputs = V1Used && V2Used;
4803 for (unsigned i = 0; i != 8; ++i) {
4804 int EltIdx = MaskVals[i] * 2;
4805 if (TwoInputs && (EltIdx >= 16)) {
4806 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4807 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4810 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4811 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4813 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4814 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4815 DAG.getNode(ISD::BUILD_VECTOR, dl,
4816 MVT::v16i8, &pshufbMask[0], 16));
4818 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4820 // Calculate the shuffle mask for the second input, shuffle it, and
4821 // OR it with the first shuffled input.
4823 for (unsigned i = 0; i != 8; ++i) {
4824 int EltIdx = MaskVals[i] * 2;
4826 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4827 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4830 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4831 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4833 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4834 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4835 DAG.getNode(ISD::BUILD_VECTOR, dl,
4836 MVT::v16i8, &pshufbMask[0], 16));
4837 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4838 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4841 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4842 // and update MaskVals with new element order.
4843 BitVector InOrder(8);
4844 if (BestLoQuad >= 0) {
4845 SmallVector<int, 8> MaskV;
4846 for (int i = 0; i != 4; ++i) {
4847 int idx = MaskVals[i];
4849 MaskV.push_back(-1);
4851 } else if ((idx / 4) == BestLoQuad) {
4852 MaskV.push_back(idx & 3);
4855 MaskV.push_back(-1);
4858 for (unsigned i = 4; i != 8; ++i)
4860 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4863 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4864 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4866 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4870 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4871 // and update MaskVals with the new element order.
4872 if (BestHiQuad >= 0) {
4873 SmallVector<int, 8> MaskV;
4874 for (unsigned i = 0; i != 4; ++i)
4876 for (unsigned i = 4; i != 8; ++i) {
4877 int idx = MaskVals[i];
4879 MaskV.push_back(-1);
4881 } else if ((idx / 4) == BestHiQuad) {
4882 MaskV.push_back((idx & 3) + 4);
4885 MaskV.push_back(-1);
4888 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4891 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4892 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4894 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4898 // In case BestHi & BestLo were both -1, which means each quadword has a word
4899 // from each of the four input quadwords, calculate the InOrder bitvector now
4900 // before falling through to the insert/extract cleanup.
4901 if (BestLoQuad == -1 && BestHiQuad == -1) {
4903 for (int i = 0; i != 8; ++i)
4904 if (MaskVals[i] < 0 || MaskVals[i] == i)
4908 // The other elements are put in the right place using pextrw and pinsrw.
4909 for (unsigned i = 0; i != 8; ++i) {
4912 int EltIdx = MaskVals[i];
4915 SDValue ExtOp = (EltIdx < 8)
4916 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4917 DAG.getIntPtrConstant(EltIdx))
4918 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4919 DAG.getIntPtrConstant(EltIdx - 8));
4920 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4921 DAG.getIntPtrConstant(i));
4926 // v16i8 shuffles - Prefer shuffles in the following order:
4927 // 1. [ssse3] 1 x pshufb
4928 // 2. [ssse3] 2 x pshufb + 1 x por
4929 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4931 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4933 const X86TargetLowering &TLI) {
4934 SDValue V1 = SVOp->getOperand(0);
4935 SDValue V2 = SVOp->getOperand(1);
4936 DebugLoc dl = SVOp->getDebugLoc();
4937 SmallVector<int, 16> MaskVals;
4938 SVOp->getMask(MaskVals);
4940 // If we have SSSE3, case 1 is generated when all result bytes come from
4941 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4942 // present, fall back to case 3.
4943 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4946 for (unsigned i = 0; i < 16; ++i) {
4947 int EltIdx = MaskVals[i];
4956 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4957 if (TLI.getSubtarget()->hasSSSE3()) {
4958 SmallVector<SDValue,16> pshufbMask;
4960 // If all result elements are from one input vector, then only translate
4961 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4963 // Otherwise, we have elements from both input vectors, and must zero out
4964 // elements that come from V2 in the first mask, and V1 in the second mask
4965 // so that we can OR them together.
4966 bool TwoInputs = !(V1Only || V2Only);
4967 for (unsigned i = 0; i != 16; ++i) {
4968 int EltIdx = MaskVals[i];
4969 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4970 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4973 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4975 // If all the elements are from V2, assign it to V1 and return after
4976 // building the first pshufb.
4979 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4980 DAG.getNode(ISD::BUILD_VECTOR, dl,
4981 MVT::v16i8, &pshufbMask[0], 16));
4985 // Calculate the shuffle mask for the second input, shuffle it, and
4986 // OR it with the first shuffled input.
4988 for (unsigned i = 0; i != 16; ++i) {
4989 int EltIdx = MaskVals[i];
4991 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4994 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4996 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4997 DAG.getNode(ISD::BUILD_VECTOR, dl,
4998 MVT::v16i8, &pshufbMask[0], 16));
4999 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5002 // No SSSE3 - Calculate in place words and then fix all out of place words
5003 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5004 // the 16 different words that comprise the two doublequadword input vectors.
5005 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5006 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5007 SDValue NewV = V2Only ? V2 : V1;
5008 for (int i = 0; i != 8; ++i) {
5009 int Elt0 = MaskVals[i*2];
5010 int Elt1 = MaskVals[i*2+1];
5012 // This word of the result is all undef, skip it.
5013 if (Elt0 < 0 && Elt1 < 0)
5016 // This word of the result is already in the correct place, skip it.
5017 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5019 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5022 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5023 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5026 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5027 // using a single extract together, load it and store it.
5028 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5029 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5030 DAG.getIntPtrConstant(Elt1 / 2));
5031 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5032 DAG.getIntPtrConstant(i));
5036 // If Elt1 is defined, extract it from the appropriate source. If the
5037 // source byte is not also odd, shift the extracted word left 8 bits
5038 // otherwise clear the bottom 8 bits if we need to do an or.
5040 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5041 DAG.getIntPtrConstant(Elt1 / 2));
5042 if ((Elt1 & 1) == 0)
5043 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5044 DAG.getConstant(8, TLI.getShiftAmountTy()));
5046 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5047 DAG.getConstant(0xFF00, MVT::i16));
5049 // If Elt0 is defined, extract it from the appropriate source. If the
5050 // source byte is not also even, shift the extracted word right 8 bits. If
5051 // Elt1 was also defined, OR the extracted values together before
5052 // inserting them in the result.
5054 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5055 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5056 if ((Elt0 & 1) != 0)
5057 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5058 DAG.getConstant(8, TLI.getShiftAmountTy()));
5060 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5061 DAG.getConstant(0x00FF, MVT::i16));
5062 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5065 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5066 DAG.getIntPtrConstant(i));
5068 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5071 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5072 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5073 /// done when every pair / quad of shuffle mask elements point to elements in
5074 /// the right sequence. e.g.
5075 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5077 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5078 SelectionDAG &DAG, DebugLoc dl) {
5079 EVT VT = SVOp->getValueType(0);
5080 SDValue V1 = SVOp->getOperand(0);
5081 SDValue V2 = SVOp->getOperand(1);
5082 unsigned NumElems = VT.getVectorNumElements();
5083 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5085 switch (VT.getSimpleVT().SimpleTy) {
5086 default: assert(false && "Unexpected!");
5087 case MVT::v4f32: NewVT = MVT::v2f64; break;
5088 case MVT::v4i32: NewVT = MVT::v2i64; break;
5089 case MVT::v8i16: NewVT = MVT::v4i32; break;
5090 case MVT::v16i8: NewVT = MVT::v4i32; break;
5093 int Scale = NumElems / NewWidth;
5094 SmallVector<int, 8> MaskVec;
5095 for (unsigned i = 0; i < NumElems; i += Scale) {
5097 for (int j = 0; j < Scale; ++j) {
5098 int EltIdx = SVOp->getMaskElt(i+j);
5102 StartIdx = EltIdx - (EltIdx % Scale);
5103 if (EltIdx != StartIdx + j)
5107 MaskVec.push_back(-1);
5109 MaskVec.push_back(StartIdx / Scale);
5112 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5113 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5114 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5117 /// getVZextMovL - Return a zero-extending vector move low node.
5119 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5120 SDValue SrcOp, SelectionDAG &DAG,
5121 const X86Subtarget *Subtarget, DebugLoc dl) {
5122 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5123 LoadSDNode *LD = NULL;
5124 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5125 LD = dyn_cast<LoadSDNode>(SrcOp);
5127 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5129 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5130 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5131 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5132 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5133 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5135 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5136 return DAG.getNode(ISD::BITCAST, dl, VT,
5137 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5138 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5146 return DAG.getNode(ISD::BITCAST, dl, VT,
5147 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5148 DAG.getNode(ISD::BITCAST, dl,
5152 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5155 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5156 SDValue V1 = SVOp->getOperand(0);
5157 SDValue V2 = SVOp->getOperand(1);
5158 DebugLoc dl = SVOp->getDebugLoc();
5159 EVT VT = SVOp->getValueType(0);
5161 SmallVector<std::pair<int, int>, 8> Locs;
5163 SmallVector<int, 8> Mask1(4U, -1);
5164 SmallVector<int, 8> PermMask;
5165 SVOp->getMask(PermMask);
5169 for (unsigned i = 0; i != 4; ++i) {
5170 int Idx = PermMask[i];
5172 Locs[i] = std::make_pair(-1, -1);
5174 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5176 Locs[i] = std::make_pair(0, NumLo);
5180 Locs[i] = std::make_pair(1, NumHi);
5182 Mask1[2+NumHi] = Idx;
5188 if (NumLo <= 2 && NumHi <= 2) {
5189 // If no more than two elements come from either vector. This can be
5190 // implemented with two shuffles. First shuffle gather the elements.
5191 // The second shuffle, which takes the first shuffle as both of its
5192 // vector operands, put the elements into the right order.
5193 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5195 SmallVector<int, 8> Mask2(4U, -1);
5197 for (unsigned i = 0; i != 4; ++i) {
5198 if (Locs[i].first == -1)
5201 unsigned Idx = (i < 2) ? 0 : 4;
5202 Idx += Locs[i].first * 2 + Locs[i].second;
5207 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5208 } else if (NumLo == 3 || NumHi == 3) {
5209 // Otherwise, we must have three elements from one vector, call it X, and
5210 // one element from the other, call it Y. First, use a shufps to build an
5211 // intermediate vector with the one element from Y and the element from X
5212 // that will be in the same half in the final destination (the indexes don't
5213 // matter). Then, use a shufps to build the final vector, taking the half
5214 // containing the element from Y from the intermediate, and the other half
5217 // Normalize it so the 3 elements come from V1.
5218 CommuteVectorShuffleMask(PermMask, VT);
5222 // Find the element from V2.
5224 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5225 int Val = PermMask[HiIndex];
5232 Mask1[0] = PermMask[HiIndex];
5234 Mask1[2] = PermMask[HiIndex^1];
5236 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5239 Mask1[0] = PermMask[0];
5240 Mask1[1] = PermMask[1];
5241 Mask1[2] = HiIndex & 1 ? 6 : 4;
5242 Mask1[3] = HiIndex & 1 ? 4 : 6;
5243 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5245 Mask1[0] = HiIndex & 1 ? 2 : 0;
5246 Mask1[1] = HiIndex & 1 ? 0 : 2;
5247 Mask1[2] = PermMask[2];
5248 Mask1[3] = PermMask[3];
5253 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5257 // Break it into (shuffle shuffle_hi, shuffle_lo).
5259 SmallVector<int,8> LoMask(4U, -1);
5260 SmallVector<int,8> HiMask(4U, -1);
5262 SmallVector<int,8> *MaskPtr = &LoMask;
5263 unsigned MaskIdx = 0;
5266 for (unsigned i = 0; i != 4; ++i) {
5273 int Idx = PermMask[i];
5275 Locs[i] = std::make_pair(-1, -1);
5276 } else if (Idx < 4) {
5277 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5278 (*MaskPtr)[LoIdx] = Idx;
5281 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5282 (*MaskPtr)[HiIdx] = Idx;
5287 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5288 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5289 SmallVector<int, 8> MaskOps;
5290 for (unsigned i = 0; i != 4; ++i) {
5291 if (Locs[i].first == -1) {
5292 MaskOps.push_back(-1);
5294 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5295 MaskOps.push_back(Idx);
5298 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5301 static bool MayFoldVectorLoad(SDValue V) {
5302 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5303 V = V.getOperand(0);
5304 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5305 V = V.getOperand(0);
5311 // FIXME: the version above should always be used. Since there's
5312 // a bug where several vector shuffles can't be folded because the
5313 // DAG is not updated during lowering and a node claims to have two
5314 // uses while it only has one, use this version, and let isel match
5315 // another instruction if the load really happens to have more than
5316 // one use. Remove this version after this bug get fixed.
5317 // rdar://8434668, PR8156
5318 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5319 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5320 V = V.getOperand(0);
5321 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5322 V = V.getOperand(0);
5323 if (ISD::isNormalLoad(V.getNode()))
5328 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5329 /// a vector extract, and if both can be later optimized into a single load.
5330 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5331 /// here because otherwise a target specific shuffle node is going to be
5332 /// emitted for this shuffle, and the optimization not done.
5333 /// FIXME: This is probably not the best approach, but fix the problem
5334 /// until the right path is decided.
5336 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5337 const TargetLowering &TLI) {
5338 EVT VT = V.getValueType();
5339 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5341 // Be sure that the vector shuffle is present in a pattern like this:
5342 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5346 SDNode *N = *V.getNode()->use_begin();
5347 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5350 SDValue EltNo = N->getOperand(1);
5351 if (!isa<ConstantSDNode>(EltNo))
5354 // If the bit convert changed the number of elements, it is unsafe
5355 // to examine the mask.
5356 bool HasShuffleIntoBitcast = false;
5357 if (V.getOpcode() == ISD::BITCAST) {
5358 EVT SrcVT = V.getOperand(0).getValueType();
5359 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5361 V = V.getOperand(0);
5362 HasShuffleIntoBitcast = true;
5365 // Select the input vector, guarding against out of range extract vector.
5366 unsigned NumElems = VT.getVectorNumElements();
5367 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5368 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5369 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5371 // Skip one more bit_convert if necessary
5372 if (V.getOpcode() == ISD::BITCAST)
5373 V = V.getOperand(0);
5375 if (ISD::isNormalLoad(V.getNode())) {
5376 // Is the original load suitable?
5377 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5379 // FIXME: avoid the multi-use bug that is preventing lots of
5380 // of foldings to be detected, this is still wrong of course, but
5381 // give the temporary desired behavior, and if it happens that
5382 // the load has real more uses, during isel it will not fold, and
5383 // will generate poor code.
5384 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5387 if (!HasShuffleIntoBitcast)
5390 // If there's a bitcast before the shuffle, check if the load type and
5391 // alignment is valid.
5392 unsigned Align = LN0->getAlignment();
5394 TLI.getTargetData()->getABITypeAlignment(
5395 VT.getTypeForEVT(*DAG.getContext()));
5397 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5405 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5406 EVT VT = Op.getValueType();
5408 // Canonizalize to v2f64.
5409 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5410 return DAG.getNode(ISD::BITCAST, dl, VT,
5411 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5416 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5418 SDValue V1 = Op.getOperand(0);
5419 SDValue V2 = Op.getOperand(1);
5420 EVT VT = Op.getValueType();
5422 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5424 if (HasSSE2 && VT == MVT::v2f64)
5425 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5428 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5432 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5433 SDValue V1 = Op.getOperand(0);
5434 SDValue V2 = Op.getOperand(1);
5435 EVT VT = Op.getValueType();
5437 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5438 "unsupported shuffle type");
5440 if (V2.getOpcode() == ISD::UNDEF)
5444 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5448 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5449 SDValue V1 = Op.getOperand(0);
5450 SDValue V2 = Op.getOperand(1);
5451 EVT VT = Op.getValueType();
5452 unsigned NumElems = VT.getVectorNumElements();
5454 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5455 // operand of these instructions is only memory, so check if there's a
5456 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5458 bool CanFoldLoad = false;
5460 // Trivial case, when V2 comes from a load.
5461 if (MayFoldVectorLoad(V2))
5464 // When V1 is a load, it can be folded later into a store in isel, example:
5465 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5467 // (MOVLPSmr addr:$src1, VR128:$src2)
5468 // So, recognize this potential and also use MOVLPS or MOVLPD
5469 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5473 if (HasSSE2 && NumElems == 2)
5474 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5477 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5480 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5481 // movl and movlp will both match v2i64, but v2i64 is never matched by
5482 // movl earlier because we make it strict to avoid messing with the movlp load
5483 // folding logic (see the code above getMOVLP call). Match it here then,
5484 // this is horrible, but will stay like this until we move all shuffle
5485 // matching to x86 specific nodes. Note that for the 1st condition all
5486 // types are matched with movsd.
5487 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5488 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5490 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5493 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5495 // Invert the operand order and use SHUFPS to match it.
5496 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5497 X86::getShuffleSHUFImmediate(SVOp), DAG);
5500 static inline unsigned getUNPCKLOpcode(EVT VT) {
5501 switch(VT.getSimpleVT().SimpleTy) {
5502 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5503 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5504 case MVT::v4f32: return X86ISD::UNPCKLPS;
5505 case MVT::v2f64: return X86ISD::UNPCKLPD;
5506 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5507 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5509 llvm_unreachable("Unknow type for unpckl");
5514 static inline unsigned getUNPCKHOpcode(EVT VT) {
5515 switch(VT.getSimpleVT().SimpleTy) {
5516 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5517 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5518 case MVT::v4f32: return X86ISD::UNPCKHPS;
5519 case MVT::v2f64: return X86ISD::UNPCKHPD;
5520 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5521 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5523 llvm_unreachable("Unknow type for unpckh");
5529 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5530 const TargetLowering &TLI,
5531 const X86Subtarget *Subtarget) {
5532 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5533 EVT VT = Op.getValueType();
5534 DebugLoc dl = Op.getDebugLoc();
5535 SDValue V1 = Op.getOperand(0);
5536 SDValue V2 = Op.getOperand(1);
5538 if (isZeroShuffle(SVOp))
5539 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5541 // Handle splat operations
5542 if (SVOp->isSplat()) {
5543 // Special case, this is the only place now where it's
5544 // allowed to return a vector_shuffle operation without
5545 // using a target specific node, because *hopefully* it
5546 // will be optimized away by the dag combiner.
5547 if (VT.getVectorNumElements() <= 4 &&
5548 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5551 // Handle splats by matching through known masks
5552 if (VT.getVectorNumElements() <= 4)
5555 // Canonicalize all of the remaining to v4f32.
5556 return PromoteSplat(SVOp, DAG);
5559 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5561 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5562 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5563 if (NewOp.getNode())
5564 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5565 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5566 // FIXME: Figure out a cleaner way to do this.
5567 // Try to make use of movq to zero out the top part.
5568 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5569 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5570 if (NewOp.getNode()) {
5571 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5572 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5573 DAG, Subtarget, dl);
5575 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5576 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5577 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5578 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5579 DAG, Subtarget, dl);
5586 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5587 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5588 SDValue V1 = Op.getOperand(0);
5589 SDValue V2 = Op.getOperand(1);
5590 EVT VT = Op.getValueType();
5591 DebugLoc dl = Op.getDebugLoc();
5592 unsigned NumElems = VT.getVectorNumElements();
5593 bool isMMX = VT.getSizeInBits() == 64;
5594 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5595 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5596 bool V1IsSplat = false;
5597 bool V2IsSplat = false;
5598 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5599 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5600 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5601 MachineFunction &MF = DAG.getMachineFunction();
5602 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5604 // Shuffle operations on MMX not supported.
5608 // Vector shuffle lowering takes 3 steps:
5610 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5611 // narrowing and commutation of operands should be handled.
5612 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5614 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5615 // so the shuffle can be broken into other shuffles and the legalizer can
5616 // try the lowering again.
5618 // The general ideia is that no vector_shuffle operation should be left to
5619 // be matched during isel, all of them must be converted to a target specific
5622 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5623 // narrowing and commutation of operands should be handled. The actual code
5624 // doesn't include all of those, work in progress...
5625 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5626 if (NewOp.getNode())
5629 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5630 // unpckh_undef). Only use pshufd if speed is more important than size.
5631 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5632 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5633 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5634 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5635 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5636 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5638 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5639 RelaxedMayFoldVectorLoad(V1))
5640 return getMOVDDup(Op, dl, V1, DAG);
5642 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5643 return getMOVHighToLow(Op, dl, DAG);
5645 // Use to match splats
5646 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5647 (VT == MVT::v2f64 || VT == MVT::v2i64))
5648 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5650 if (X86::isPSHUFDMask(SVOp)) {
5651 // The actual implementation will match the mask in the if above and then
5652 // during isel it can match several different instructions, not only pshufd
5653 // as its name says, sad but true, emulate the behavior for now...
5654 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5655 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5657 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5659 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5660 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5662 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5663 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5666 if (VT == MVT::v4f32)
5667 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5671 // Check if this can be converted into a logical shift.
5672 bool isLeft = false;
5675 bool isShift = getSubtarget()->hasSSE2() &&
5676 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5677 if (isShift && ShVal.hasOneUse()) {
5678 // If the shifted value has multiple uses, it may be cheaper to use
5679 // v_set0 + movlhps or movhlps, etc.
5680 EVT EltVT = VT.getVectorElementType();
5681 ShAmt *= EltVT.getSizeInBits();
5682 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5685 if (X86::isMOVLMask(SVOp)) {
5688 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5689 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5690 if (!X86::isMOVLPMask(SVOp)) {
5691 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5692 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5694 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5695 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5699 // FIXME: fold these into legal mask.
5700 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5701 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5703 if (X86::isMOVHLPSMask(SVOp))
5704 return getMOVHighToLow(Op, dl, DAG);
5706 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5707 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5709 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5710 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5712 if (X86::isMOVLPMask(SVOp))
5713 return getMOVLP(Op, dl, DAG, HasSSE2);
5715 if (ShouldXformToMOVHLPS(SVOp) ||
5716 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5717 return CommuteVectorShuffle(SVOp, DAG);
5720 // No better options. Use a vshl / vsrl.
5721 EVT EltVT = VT.getVectorElementType();
5722 ShAmt *= EltVT.getSizeInBits();
5723 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5726 bool Commuted = false;
5727 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5728 // 1,1,1,1 -> v8i16 though.
5729 V1IsSplat = isSplatVector(V1.getNode());
5730 V2IsSplat = isSplatVector(V2.getNode());
5732 // Canonicalize the splat or undef, if present, to be on the RHS.
5733 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5734 Op = CommuteVectorShuffle(SVOp, DAG);
5735 SVOp = cast<ShuffleVectorSDNode>(Op);
5736 V1 = SVOp->getOperand(0);
5737 V2 = SVOp->getOperand(1);
5738 std::swap(V1IsSplat, V2IsSplat);
5739 std::swap(V1IsUndef, V2IsUndef);
5743 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5744 // Shuffling low element of v1 into undef, just return v1.
5747 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5748 // the instruction selector will not match, so get a canonical MOVL with
5749 // swapped operands to undo the commute.
5750 return getMOVL(DAG, dl, VT, V2, V1);
5753 if (X86::isUNPCKLMask(SVOp))
5754 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5756 if (X86::isUNPCKHMask(SVOp))
5757 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5760 // Normalize mask so all entries that point to V2 points to its first
5761 // element then try to match unpck{h|l} again. If match, return a
5762 // new vector_shuffle with the corrected mask.
5763 SDValue NewMask = NormalizeMask(SVOp, DAG);
5764 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5765 if (NSVOp != SVOp) {
5766 if (X86::isUNPCKLMask(NSVOp, true)) {
5768 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5775 // Commute is back and try unpck* again.
5776 // FIXME: this seems wrong.
5777 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5778 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5780 if (X86::isUNPCKLMask(NewSVOp))
5781 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5783 if (X86::isUNPCKHMask(NewSVOp))
5784 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5787 // Normalize the node to match x86 shuffle ops if needed
5788 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5789 return CommuteVectorShuffle(SVOp, DAG);
5791 // The checks below are all present in isShuffleMaskLegal, but they are
5792 // inlined here right now to enable us to directly emit target specific
5793 // nodes, and remove one by one until they don't return Op anymore.
5794 SmallVector<int, 16> M;
5797 if (isPALIGNRMask(M, VT, HasSSSE3))
5798 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5799 X86::getShufflePALIGNRImmediate(SVOp),
5802 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5803 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5804 if (VT == MVT::v2f64)
5805 return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5806 if (VT == MVT::v2i64)
5807 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5810 if (isPSHUFHWMask(M, VT))
5811 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5812 X86::getShufflePSHUFHWImmediate(SVOp),
5815 if (isPSHUFLWMask(M, VT))
5816 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5817 X86::getShufflePSHUFLWImmediate(SVOp),
5820 if (isSHUFPMask(M, VT)) {
5821 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5822 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5823 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5825 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5826 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5830 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5831 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5832 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5833 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5834 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5835 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5837 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5838 if (VT == MVT::v8i16) {
5839 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5840 if (NewOp.getNode())
5844 if (VT == MVT::v16i8) {
5845 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5846 if (NewOp.getNode())
5850 // Handle all 4 wide cases with a number of shuffles.
5852 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5858 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5859 SelectionDAG &DAG) const {
5860 EVT VT = Op.getValueType();
5861 DebugLoc dl = Op.getDebugLoc();
5862 if (VT.getSizeInBits() == 8) {
5863 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5864 Op.getOperand(0), Op.getOperand(1));
5865 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5866 DAG.getValueType(VT));
5867 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5868 } else if (VT.getSizeInBits() == 16) {
5869 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5870 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5872 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5873 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5874 DAG.getNode(ISD::BITCAST, dl,
5878 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5879 Op.getOperand(0), Op.getOperand(1));
5880 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5881 DAG.getValueType(VT));
5882 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5883 } else if (VT == MVT::f32) {
5884 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5885 // the result back to FR32 register. It's only worth matching if the
5886 // result has a single use which is a store or a bitcast to i32. And in
5887 // the case of a store, it's not worth it if the index is a constant 0,
5888 // because a MOVSSmr can be used instead, which is smaller and faster.
5889 if (!Op.hasOneUse())
5891 SDNode *User = *Op.getNode()->use_begin();
5892 if ((User->getOpcode() != ISD::STORE ||
5893 (isa<ConstantSDNode>(Op.getOperand(1)) &&
5894 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5895 (User->getOpcode() != ISD::BITCAST ||
5896 User->getValueType(0) != MVT::i32))
5898 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5899 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5902 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5903 } else if (VT == MVT::i32) {
5904 // ExtractPS works with constant index.
5905 if (isa<ConstantSDNode>(Op.getOperand(1)))
5913 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5914 SelectionDAG &DAG) const {
5915 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5918 if (Subtarget->hasSSE41()) {
5919 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5924 EVT VT = Op.getValueType();
5925 DebugLoc dl = Op.getDebugLoc();
5926 // TODO: handle v16i8.
5927 if (VT.getSizeInBits() == 16) {
5928 SDValue Vec = Op.getOperand(0);
5929 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5931 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5932 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5933 DAG.getNode(ISD::BITCAST, dl,
5936 // Transform it so it match pextrw which produces a 32-bit result.
5937 EVT EltVT = MVT::i32;
5938 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5939 Op.getOperand(0), Op.getOperand(1));
5940 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5941 DAG.getValueType(VT));
5942 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5943 } else if (VT.getSizeInBits() == 32) {
5944 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5948 // SHUFPS the element to the lowest double word, then movss.
5949 int Mask[4] = { Idx, -1, -1, -1 };
5950 EVT VVT = Op.getOperand(0).getValueType();
5951 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5952 DAG.getUNDEF(VVT), Mask);
5953 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5954 DAG.getIntPtrConstant(0));
5955 } else if (VT.getSizeInBits() == 64) {
5956 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5957 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5958 // to match extract_elt for f64.
5959 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5963 // UNPCKHPD the element to the lowest double word, then movsd.
5964 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5965 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5966 int Mask[2] = { 1, -1 };
5967 EVT VVT = Op.getOperand(0).getValueType();
5968 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5969 DAG.getUNDEF(VVT), Mask);
5970 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5971 DAG.getIntPtrConstant(0));
5978 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5979 SelectionDAG &DAG) const {
5980 EVT VT = Op.getValueType();
5981 EVT EltVT = VT.getVectorElementType();
5982 DebugLoc dl = Op.getDebugLoc();
5984 SDValue N0 = Op.getOperand(0);
5985 SDValue N1 = Op.getOperand(1);
5986 SDValue N2 = Op.getOperand(2);
5988 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5989 isa<ConstantSDNode>(N2)) {
5991 if (VT == MVT::v8i16)
5992 Opc = X86ISD::PINSRW;
5993 else if (VT == MVT::v16i8)
5994 Opc = X86ISD::PINSRB;
5996 Opc = X86ISD::PINSRB;
5998 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6000 if (N1.getValueType() != MVT::i32)
6001 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6002 if (N2.getValueType() != MVT::i32)
6003 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6004 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6005 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6006 // Bits [7:6] of the constant are the source select. This will always be
6007 // zero here. The DAG Combiner may combine an extract_elt index into these
6008 // bits. For example (insert (extract, 3), 2) could be matched by putting
6009 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6010 // Bits [5:4] of the constant are the destination select. This is the
6011 // value of the incoming immediate.
6012 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6013 // combine either bitwise AND or insert of float 0.0 to set these bits.
6014 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6015 // Create this as a scalar to vector..
6016 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6017 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6018 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6019 // PINSR* works with constant index.
6026 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6027 EVT VT = Op.getValueType();
6028 EVT EltVT = VT.getVectorElementType();
6030 if (Subtarget->hasSSE41())
6031 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6033 if (EltVT == MVT::i8)
6036 DebugLoc dl = Op.getDebugLoc();
6037 SDValue N0 = Op.getOperand(0);
6038 SDValue N1 = Op.getOperand(1);
6039 SDValue N2 = Op.getOperand(2);
6041 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6042 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6043 // as its second argument.
6044 if (N1.getValueType() != MVT::i32)
6045 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6046 if (N2.getValueType() != MVT::i32)
6047 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6048 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6054 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6055 DebugLoc dl = Op.getDebugLoc();
6057 if (Op.getValueType() == MVT::v1i64 &&
6058 Op.getOperand(0).getValueType() == MVT::i64)
6059 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6061 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6062 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6063 "Expected an SSE type!");
6064 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6065 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6068 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
6069 // a simple subregister reference or explicit instructions to grab
6070 // upper bits of a vector.
6072 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6073 if (Subtarget->hasAVX()) {
6074 DebugLoc dl = Op.getNode()->getDebugLoc();
6075 SDValue Vec = Op.getNode()->getOperand(0);
6076 SDValue Idx = Op.getNode()->getOperand(1);
6078 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6079 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6080 return Extract128BitVector(Vec, Idx, DAG, dl);
6086 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
6087 // simple superregister reference or explicit instructions to insert
6088 // the upper bits of a vector.
6090 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6091 if (Subtarget->hasAVX()) {
6092 DebugLoc dl = Op.getNode()->getDebugLoc();
6093 SDValue Vec = Op.getNode()->getOperand(0);
6094 SDValue SubVec = Op.getNode()->getOperand(1);
6095 SDValue Idx = Op.getNode()->getOperand(2);
6097 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6098 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6099 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6105 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6106 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6107 // one of the above mentioned nodes. It has to be wrapped because otherwise
6108 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6109 // be used to form addressing mode. These wrapped nodes will be selected
6112 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6113 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6115 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6117 unsigned char OpFlag = 0;
6118 unsigned WrapperKind = X86ISD::Wrapper;
6119 CodeModel::Model M = getTargetMachine().getCodeModel();
6121 if (Subtarget->isPICStyleRIPRel() &&
6122 (M == CodeModel::Small || M == CodeModel::Kernel))
6123 WrapperKind = X86ISD::WrapperRIP;
6124 else if (Subtarget->isPICStyleGOT())
6125 OpFlag = X86II::MO_GOTOFF;
6126 else if (Subtarget->isPICStyleStubPIC())
6127 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6129 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6131 CP->getOffset(), OpFlag);
6132 DebugLoc DL = CP->getDebugLoc();
6133 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6134 // With PIC, the address is actually $g + Offset.
6136 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6137 DAG.getNode(X86ISD::GlobalBaseReg,
6138 DebugLoc(), getPointerTy()),
6145 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6146 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6148 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6150 unsigned char OpFlag = 0;
6151 unsigned WrapperKind = X86ISD::Wrapper;
6152 CodeModel::Model M = getTargetMachine().getCodeModel();
6154 if (Subtarget->isPICStyleRIPRel() &&
6155 (M == CodeModel::Small || M == CodeModel::Kernel))
6156 WrapperKind = X86ISD::WrapperRIP;
6157 else if (Subtarget->isPICStyleGOT())
6158 OpFlag = X86II::MO_GOTOFF;
6159 else if (Subtarget->isPICStyleStubPIC())
6160 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6162 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6164 DebugLoc DL = JT->getDebugLoc();
6165 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6167 // With PIC, the address is actually $g + Offset.
6169 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6170 DAG.getNode(X86ISD::GlobalBaseReg,
6171 DebugLoc(), getPointerTy()),
6178 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6179 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6181 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6183 unsigned char OpFlag = 0;
6184 unsigned WrapperKind = X86ISD::Wrapper;
6185 CodeModel::Model M = getTargetMachine().getCodeModel();
6187 if (Subtarget->isPICStyleRIPRel() &&
6188 (M == CodeModel::Small || M == CodeModel::Kernel))
6189 WrapperKind = X86ISD::WrapperRIP;
6190 else if (Subtarget->isPICStyleGOT())
6191 OpFlag = X86II::MO_GOTOFF;
6192 else if (Subtarget->isPICStyleStubPIC())
6193 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6195 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6197 DebugLoc DL = Op.getDebugLoc();
6198 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6201 // With PIC, the address is actually $g + Offset.
6202 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6203 !Subtarget->is64Bit()) {
6204 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6205 DAG.getNode(X86ISD::GlobalBaseReg,
6206 DebugLoc(), getPointerTy()),
6214 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6215 // Create the TargetBlockAddressAddress node.
6216 unsigned char OpFlags =
6217 Subtarget->ClassifyBlockAddressReference();
6218 CodeModel::Model M = getTargetMachine().getCodeModel();
6219 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6220 DebugLoc dl = Op.getDebugLoc();
6221 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6222 /*isTarget=*/true, OpFlags);
6224 if (Subtarget->isPICStyleRIPRel() &&
6225 (M == CodeModel::Small || M == CodeModel::Kernel))
6226 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6228 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6230 // With PIC, the address is actually $g + Offset.
6231 if (isGlobalRelativeToPICBase(OpFlags)) {
6232 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6233 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6241 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6243 SelectionDAG &DAG) const {
6244 // Create the TargetGlobalAddress node, folding in the constant
6245 // offset if it is legal.
6246 unsigned char OpFlags =
6247 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6248 CodeModel::Model M = getTargetMachine().getCodeModel();
6250 if (OpFlags == X86II::MO_NO_FLAG &&
6251 X86::isOffsetSuitableForCodeModel(Offset, M)) {
6252 // A direct static reference to a global.
6253 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6256 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6259 if (Subtarget->isPICStyleRIPRel() &&
6260 (M == CodeModel::Small || M == CodeModel::Kernel))
6261 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6263 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6265 // With PIC, the address is actually $g + Offset.
6266 if (isGlobalRelativeToPICBase(OpFlags)) {
6267 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6268 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6272 // For globals that require a load from a stub to get the address, emit the
6274 if (isGlobalStubReference(OpFlags))
6275 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6276 MachinePointerInfo::getGOT(), false, false, 0);
6278 // If there was a non-zero offset that we didn't fold, create an explicit
6281 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6282 DAG.getConstant(Offset, getPointerTy()));
6288 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6289 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6290 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6291 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6295 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6296 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6297 unsigned char OperandFlags) {
6298 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6299 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6300 DebugLoc dl = GA->getDebugLoc();
6301 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6302 GA->getValueType(0),
6306 SDValue Ops[] = { Chain, TGA, *InFlag };
6307 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6309 SDValue Ops[] = { Chain, TGA };
6310 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6313 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6314 MFI->setAdjustsStack(true);
6316 SDValue Flag = Chain.getValue(1);
6317 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6320 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6322 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6325 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6326 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6327 DAG.getNode(X86ISD::GlobalBaseReg,
6328 DebugLoc(), PtrVT), InFlag);
6329 InFlag = Chain.getValue(1);
6331 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6334 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6336 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6338 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6339 X86::RAX, X86II::MO_TLSGD);
6342 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6343 // "local exec" model.
6344 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6345 const EVT PtrVT, TLSModel::Model model,
6347 DebugLoc dl = GA->getDebugLoc();
6349 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6350 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6351 is64Bit ? 257 : 256));
6353 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6354 DAG.getIntPtrConstant(0),
6355 MachinePointerInfo(Ptr), false, false, 0);
6357 unsigned char OperandFlags = 0;
6358 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6360 unsigned WrapperKind = X86ISD::Wrapper;
6361 if (model == TLSModel::LocalExec) {
6362 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6363 } else if (is64Bit) {
6364 assert(model == TLSModel::InitialExec);
6365 OperandFlags = X86II::MO_GOTTPOFF;
6366 WrapperKind = X86ISD::WrapperRIP;
6368 assert(model == TLSModel::InitialExec);
6369 OperandFlags = X86II::MO_INDNTPOFF;
6372 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6374 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6375 GA->getValueType(0),
6376 GA->getOffset(), OperandFlags);
6377 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6379 if (model == TLSModel::InitialExec)
6380 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6381 MachinePointerInfo::getGOT(), false, false, 0);
6383 // The address of the thread local variable is the add of the thread
6384 // pointer with the offset of the variable.
6385 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6389 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6391 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6392 const GlobalValue *GV = GA->getGlobal();
6394 if (Subtarget->isTargetELF()) {
6395 // TODO: implement the "local dynamic" model
6396 // TODO: implement the "initial exec"model for pic executables
6398 // If GV is an alias then use the aliasee for determining
6399 // thread-localness.
6400 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6401 GV = GA->resolveAliasedGlobal(false);
6403 TLSModel::Model model
6404 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6407 case TLSModel::GeneralDynamic:
6408 case TLSModel::LocalDynamic: // not implemented
6409 if (Subtarget->is64Bit())
6410 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6411 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6413 case TLSModel::InitialExec:
6414 case TLSModel::LocalExec:
6415 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6416 Subtarget->is64Bit());
6418 } else if (Subtarget->isTargetDarwin()) {
6419 // Darwin only has one model of TLS. Lower to that.
6420 unsigned char OpFlag = 0;
6421 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6422 X86ISD::WrapperRIP : X86ISD::Wrapper;
6424 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6426 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6427 !Subtarget->is64Bit();
6429 OpFlag = X86II::MO_TLVP_PIC_BASE;
6431 OpFlag = X86II::MO_TLVP;
6432 DebugLoc DL = Op.getDebugLoc();
6433 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6434 GA->getValueType(0),
6435 GA->getOffset(), OpFlag);
6436 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6438 // With PIC32, the address is actually $g + Offset.
6440 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6441 DAG.getNode(X86ISD::GlobalBaseReg,
6442 DebugLoc(), getPointerTy()),
6445 // Lowering the machine isd will make sure everything is in the right
6447 SDValue Chain = DAG.getEntryNode();
6448 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6449 SDValue Args[] = { Chain, Offset };
6450 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6452 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6453 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6454 MFI->setAdjustsStack(true);
6456 // And our return value (tls address) is in the standard call return value
6458 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6459 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6463 "TLS not implemented for this target.");
6465 llvm_unreachable("Unreachable");
6470 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6471 /// take a 2 x i32 value to shift plus a shift amount.
6472 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6473 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6474 EVT VT = Op.getValueType();
6475 unsigned VTBits = VT.getSizeInBits();
6476 DebugLoc dl = Op.getDebugLoc();
6477 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6478 SDValue ShOpLo = Op.getOperand(0);
6479 SDValue ShOpHi = Op.getOperand(1);
6480 SDValue ShAmt = Op.getOperand(2);
6481 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6482 DAG.getConstant(VTBits - 1, MVT::i8))
6483 : DAG.getConstant(0, VT);
6486 if (Op.getOpcode() == ISD::SHL_PARTS) {
6487 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6488 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6490 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6491 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6494 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6495 DAG.getConstant(VTBits, MVT::i8));
6496 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6497 AndNode, DAG.getConstant(0, MVT::i8));
6500 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6501 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6502 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6504 if (Op.getOpcode() == ISD::SHL_PARTS) {
6505 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6506 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6508 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6509 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6512 SDValue Ops[2] = { Lo, Hi };
6513 return DAG.getMergeValues(Ops, 2, dl);
6516 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6517 SelectionDAG &DAG) const {
6518 EVT SrcVT = Op.getOperand(0).getValueType();
6520 if (SrcVT.isVector())
6523 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6524 "Unknown SINT_TO_FP to lower!");
6526 // These are really Legal; return the operand so the caller accepts it as
6528 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6530 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6531 Subtarget->is64Bit()) {
6535 DebugLoc dl = Op.getDebugLoc();
6536 unsigned Size = SrcVT.getSizeInBits()/8;
6537 MachineFunction &MF = DAG.getMachineFunction();
6538 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6539 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6540 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6542 MachinePointerInfo::getFixedStack(SSFI),
6544 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6547 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6549 SelectionDAG &DAG) const {
6551 DebugLoc DL = Op.getDebugLoc();
6553 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6555 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6557 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6559 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6561 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6562 MachineMemOperand *MMO =
6563 DAG.getMachineFunction()
6564 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6565 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6567 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6568 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6570 Tys, Ops, array_lengthof(Ops),
6574 Chain = Result.getValue(1);
6575 SDValue InFlag = Result.getValue(2);
6577 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6578 // shouldn't be necessary except that RFP cannot be live across
6579 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6580 MachineFunction &MF = DAG.getMachineFunction();
6581 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6582 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6583 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6584 Tys = DAG.getVTList(MVT::Other);
6586 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6588 MachineMemOperand *MMO =
6589 DAG.getMachineFunction()
6590 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6591 MachineMemOperand::MOStore, SSFISize, SSFISize);
6593 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6594 Ops, array_lengthof(Ops),
6595 Op.getValueType(), MMO);
6596 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6597 MachinePointerInfo::getFixedStack(SSFI),
6604 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6605 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6606 SelectionDAG &DAG) const {
6607 // This algorithm is not obvious. Here it is in C code, more or less:
6609 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6610 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6611 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6613 // Copy ints to xmm registers.
6614 __m128i xh = _mm_cvtsi32_si128( hi );
6615 __m128i xl = _mm_cvtsi32_si128( lo );
6617 // Combine into low half of a single xmm register.
6618 __m128i x = _mm_unpacklo_epi32( xh, xl );
6622 // Merge in appropriate exponents to give the integer bits the right
6624 x = _mm_unpacklo_epi32( x, exp );
6626 // Subtract away the biases to deal with the IEEE-754 double precision
6628 d = _mm_sub_pd( (__m128d) x, bias );
6630 // All conversions up to here are exact. The correctly rounded result is
6631 // calculated using the current rounding mode using the following
6633 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6634 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6635 // store doesn't really need to be here (except
6636 // maybe to zero the other double)
6641 DebugLoc dl = Op.getDebugLoc();
6642 LLVMContext *Context = DAG.getContext();
6644 // Build some magic constants.
6645 std::vector<Constant*> CV0;
6646 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6647 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6648 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6649 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6650 Constant *C0 = ConstantVector::get(CV0);
6651 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6653 std::vector<Constant*> CV1;
6655 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6657 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6658 Constant *C1 = ConstantVector::get(CV1);
6659 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6661 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6662 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6664 DAG.getIntPtrConstant(1)));
6665 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6666 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6668 DAG.getIntPtrConstant(0)));
6669 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6670 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6671 MachinePointerInfo::getConstantPool(),
6673 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6674 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6675 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6676 MachinePointerInfo::getConstantPool(),
6678 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6680 // Add the halves; easiest way is to swap them into another reg first.
6681 int ShufMask[2] = { 1, -1 };
6682 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6683 DAG.getUNDEF(MVT::v2f64), ShufMask);
6684 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6685 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6686 DAG.getIntPtrConstant(0));
6689 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6690 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6691 SelectionDAG &DAG) const {
6692 DebugLoc dl = Op.getDebugLoc();
6693 // FP constant to bias correct the final result.
6694 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6697 // Load the 32-bit value into an XMM register.
6698 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6699 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6701 DAG.getIntPtrConstant(0)));
6703 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6704 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6705 DAG.getIntPtrConstant(0));
6707 // Or the load with the bias.
6708 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6709 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6710 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6712 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6713 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6714 MVT::v2f64, Bias)));
6715 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6716 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6717 DAG.getIntPtrConstant(0));
6719 // Subtract the bias.
6720 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6722 // Handle final rounding.
6723 EVT DestVT = Op.getValueType();
6725 if (DestVT.bitsLT(MVT::f64)) {
6726 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6727 DAG.getIntPtrConstant(0));
6728 } else if (DestVT.bitsGT(MVT::f64)) {
6729 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6732 // Handle final rounding.
6736 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6737 SelectionDAG &DAG) const {
6738 SDValue N0 = Op.getOperand(0);
6739 DebugLoc dl = Op.getDebugLoc();
6741 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6742 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6743 // the optimization here.
6744 if (DAG.SignBitIsZero(N0))
6745 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6747 EVT SrcVT = N0.getValueType();
6748 EVT DstVT = Op.getValueType();
6749 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6750 return LowerUINT_TO_FP_i64(Op, DAG);
6751 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6752 return LowerUINT_TO_FP_i32(Op, DAG);
6754 // Make a 64-bit buffer, and use it to build an FILD.
6755 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6756 if (SrcVT == MVT::i32) {
6757 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6758 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6759 getPointerTy(), StackSlot, WordOff);
6760 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6761 StackSlot, MachinePointerInfo(),
6763 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6764 OffsetSlot, MachinePointerInfo(),
6766 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6770 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6771 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6772 StackSlot, MachinePointerInfo(),
6774 // For i64 source, we need to add the appropriate power of 2 if the input
6775 // was negative. This is the same as the optimization in
6776 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6777 // we must be careful to do the computation in x87 extended precision, not
6778 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6779 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6780 MachineMemOperand *MMO =
6781 DAG.getMachineFunction()
6782 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6783 MachineMemOperand::MOLoad, 8, 8);
6785 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6786 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6787 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6790 APInt FF(32, 0x5F800000ULL);
6792 // Check whether the sign bit is set.
6793 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6794 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6797 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6798 SDValue FudgePtr = DAG.getConstantPool(
6799 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6802 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6803 SDValue Zero = DAG.getIntPtrConstant(0);
6804 SDValue Four = DAG.getIntPtrConstant(4);
6805 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6807 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6809 // Load the value out, extending it from f32 to f80.
6810 // FIXME: Avoid the extend by constructing the right constant pool?
6811 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6812 FudgePtr, MachinePointerInfo::getConstantPool(),
6813 MVT::f32, false, false, 4);
6814 // Extend everything to 80 bits to force it to be done on x87.
6815 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6816 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6819 std::pair<SDValue,SDValue> X86TargetLowering::
6820 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6821 DebugLoc DL = Op.getDebugLoc();
6823 EVT DstTy = Op.getValueType();
6826 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6830 assert(DstTy.getSimpleVT() <= MVT::i64 &&
6831 DstTy.getSimpleVT() >= MVT::i16 &&
6832 "Unknown FP_TO_SINT to lower!");
6834 // These are really Legal.
6835 if (DstTy == MVT::i32 &&
6836 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6837 return std::make_pair(SDValue(), SDValue());
6838 if (Subtarget->is64Bit() &&
6839 DstTy == MVT::i64 &&
6840 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6841 return std::make_pair(SDValue(), SDValue());
6843 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6845 MachineFunction &MF = DAG.getMachineFunction();
6846 unsigned MemSize = DstTy.getSizeInBits()/8;
6847 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6848 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6853 switch (DstTy.getSimpleVT().SimpleTy) {
6854 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6855 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6856 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6857 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6860 SDValue Chain = DAG.getEntryNode();
6861 SDValue Value = Op.getOperand(0);
6862 EVT TheVT = Op.getOperand(0).getValueType();
6863 if (isScalarFPTypeInSSEReg(TheVT)) {
6864 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6865 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6866 MachinePointerInfo::getFixedStack(SSFI),
6868 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6870 Chain, StackSlot, DAG.getValueType(TheVT)
6873 MachineMemOperand *MMO =
6874 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6875 MachineMemOperand::MOLoad, MemSize, MemSize);
6876 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6878 Chain = Value.getValue(1);
6879 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6880 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6883 MachineMemOperand *MMO =
6884 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6885 MachineMemOperand::MOStore, MemSize, MemSize);
6887 // Build the FP_TO_INT*_IN_MEM
6888 SDValue Ops[] = { Chain, Value, StackSlot };
6889 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6890 Ops, 3, DstTy, MMO);
6892 return std::make_pair(FIST, StackSlot);
6895 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6896 SelectionDAG &DAG) const {
6897 if (Op.getValueType().isVector())
6900 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6901 SDValue FIST = Vals.first, StackSlot = Vals.second;
6902 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6903 if (FIST.getNode() == 0) return Op;
6906 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6907 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6910 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6911 SelectionDAG &DAG) const {
6912 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6913 SDValue FIST = Vals.first, StackSlot = Vals.second;
6914 assert(FIST.getNode() && "Unexpected failure");
6917 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6918 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6921 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6922 SelectionDAG &DAG) const {
6923 LLVMContext *Context = DAG.getContext();
6924 DebugLoc dl = Op.getDebugLoc();
6925 EVT VT = Op.getValueType();
6928 EltVT = VT.getVectorElementType();
6929 std::vector<Constant*> CV;
6930 if (EltVT == MVT::f64) {
6931 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6935 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6941 Constant *C = ConstantVector::get(CV);
6942 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6943 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6944 MachinePointerInfo::getConstantPool(),
6946 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6949 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6950 LLVMContext *Context = DAG.getContext();
6951 DebugLoc dl = Op.getDebugLoc();
6952 EVT VT = Op.getValueType();
6955 EltVT = VT.getVectorElementType();
6956 std::vector<Constant*> CV;
6957 if (EltVT == MVT::f64) {
6958 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6962 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6968 Constant *C = ConstantVector::get(CV);
6969 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6970 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6971 MachinePointerInfo::getConstantPool(),
6973 if (VT.isVector()) {
6974 return DAG.getNode(ISD::BITCAST, dl, VT,
6975 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6976 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6978 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
6980 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6984 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6985 LLVMContext *Context = DAG.getContext();
6986 SDValue Op0 = Op.getOperand(0);
6987 SDValue Op1 = Op.getOperand(1);
6988 DebugLoc dl = Op.getDebugLoc();
6989 EVT VT = Op.getValueType();
6990 EVT SrcVT = Op1.getValueType();
6992 // If second operand is smaller, extend it first.
6993 if (SrcVT.bitsLT(VT)) {
6994 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6997 // And if it is bigger, shrink it first.
6998 if (SrcVT.bitsGT(VT)) {
6999 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7003 // At this point the operands and the result should have the same
7004 // type, and that won't be f80 since that is not custom lowered.
7006 // First get the sign bit of second operand.
7007 std::vector<Constant*> CV;
7008 if (SrcVT == MVT::f64) {
7009 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7010 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7012 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7013 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7014 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7015 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7017 Constant *C = ConstantVector::get(CV);
7018 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7019 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7020 MachinePointerInfo::getConstantPool(),
7022 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7024 // Shift sign bit right or left if the two operands have different types.
7025 if (SrcVT.bitsGT(VT)) {
7026 // Op0 is MVT::f32, Op1 is MVT::f64.
7027 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7028 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7029 DAG.getConstant(32, MVT::i32));
7030 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7031 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7032 DAG.getIntPtrConstant(0));
7035 // Clear first operand sign bit.
7037 if (VT == MVT::f64) {
7038 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7039 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7041 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7042 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7043 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7044 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7046 C = ConstantVector::get(CV);
7047 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7048 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7049 MachinePointerInfo::getConstantPool(),
7051 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7053 // Or the value with the sign bit.
7054 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7057 /// Emit nodes that will be selected as "test Op0,Op0", or something
7059 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7060 SelectionDAG &DAG) const {
7061 DebugLoc dl = Op.getDebugLoc();
7063 // CF and OF aren't always set the way we want. Determine which
7064 // of these we need.
7065 bool NeedCF = false;
7066 bool NeedOF = false;
7069 case X86::COND_A: case X86::COND_AE:
7070 case X86::COND_B: case X86::COND_BE:
7073 case X86::COND_G: case X86::COND_GE:
7074 case X86::COND_L: case X86::COND_LE:
7075 case X86::COND_O: case X86::COND_NO:
7080 // See if we can use the EFLAGS value from the operand instead of
7081 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7082 // we prove that the arithmetic won't overflow, we can't use OF or CF.
7083 if (Op.getResNo() != 0 || NeedOF || NeedCF)
7084 // Emit a CMP with 0, which is the TEST pattern.
7085 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7086 DAG.getConstant(0, Op.getValueType()));
7088 unsigned Opcode = 0;
7089 unsigned NumOperands = 0;
7090 switch (Op.getNode()->getOpcode()) {
7092 // Due to an isel shortcoming, be conservative if this add is likely to be
7093 // selected as part of a load-modify-store instruction. When the root node
7094 // in a match is a store, isel doesn't know how to remap non-chain non-flag
7095 // uses of other nodes in the match, such as the ADD in this case. This
7096 // leads to the ADD being left around and reselected, with the result being
7097 // two adds in the output. Alas, even if none our users are stores, that
7098 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
7099 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
7100 // climbing the DAG back to the root, and it doesn't seem to be worth the
7102 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7103 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7104 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7107 if (ConstantSDNode *C =
7108 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7109 // An add of one will be selected as an INC.
7110 if (C->getAPIntValue() == 1) {
7111 Opcode = X86ISD::INC;
7116 // An add of negative one (subtract of one) will be selected as a DEC.
7117 if (C->getAPIntValue().isAllOnesValue()) {
7118 Opcode = X86ISD::DEC;
7124 // Otherwise use a regular EFLAGS-setting add.
7125 Opcode = X86ISD::ADD;
7129 // If the primary and result isn't used, don't bother using X86ISD::AND,
7130 // because a TEST instruction will be better.
7131 bool NonFlagUse = false;
7132 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7133 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7135 unsigned UOpNo = UI.getOperandNo();
7136 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7137 // Look pass truncate.
7138 UOpNo = User->use_begin().getOperandNo();
7139 User = *User->use_begin();
7142 if (User->getOpcode() != ISD::BRCOND &&
7143 User->getOpcode() != ISD::SETCC &&
7144 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7157 // Due to the ISEL shortcoming noted above, be conservative if this op is
7158 // likely to be selected as part of a load-modify-store instruction.
7159 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7160 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7161 if (UI->getOpcode() == ISD::STORE)
7164 // Otherwise use a regular EFLAGS-setting instruction.
7165 switch (Op.getNode()->getOpcode()) {
7166 default: llvm_unreachable("unexpected operator!");
7167 case ISD::SUB: Opcode = X86ISD::SUB; break;
7168 case ISD::OR: Opcode = X86ISD::OR; break;
7169 case ISD::XOR: Opcode = X86ISD::XOR; break;
7170 case ISD::AND: Opcode = X86ISD::AND; break;
7182 return SDValue(Op.getNode(), 1);
7189 // Emit a CMP with 0, which is the TEST pattern.
7190 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7191 DAG.getConstant(0, Op.getValueType()));
7193 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7194 SmallVector<SDValue, 4> Ops;
7195 for (unsigned i = 0; i != NumOperands; ++i)
7196 Ops.push_back(Op.getOperand(i));
7198 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7199 DAG.ReplaceAllUsesWith(Op, New);
7200 return SDValue(New.getNode(), 1);
7203 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7205 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7206 SelectionDAG &DAG) const {
7207 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7208 if (C->getAPIntValue() == 0)
7209 return EmitTest(Op0, X86CC, DAG);
7211 DebugLoc dl = Op0.getDebugLoc();
7212 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7215 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7216 /// if it's possible.
7217 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7218 DebugLoc dl, SelectionDAG &DAG) const {
7219 SDValue Op0 = And.getOperand(0);
7220 SDValue Op1 = And.getOperand(1);
7221 if (Op0.getOpcode() == ISD::TRUNCATE)
7222 Op0 = Op0.getOperand(0);
7223 if (Op1.getOpcode() == ISD::TRUNCATE)
7224 Op1 = Op1.getOperand(0);
7227 if (Op1.getOpcode() == ISD::SHL)
7228 std::swap(Op0, Op1);
7229 if (Op0.getOpcode() == ISD::SHL) {
7230 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7231 if (And00C->getZExtValue() == 1) {
7232 // If we looked past a truncate, check that it's only truncating away
7234 unsigned BitWidth = Op0.getValueSizeInBits();
7235 unsigned AndBitWidth = And.getValueSizeInBits();
7236 if (BitWidth > AndBitWidth) {
7237 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7238 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7239 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7243 RHS = Op0.getOperand(1);
7245 } else if (Op1.getOpcode() == ISD::Constant) {
7246 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7247 SDValue AndLHS = Op0;
7248 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7249 LHS = AndLHS.getOperand(0);
7250 RHS = AndLHS.getOperand(1);
7254 if (LHS.getNode()) {
7255 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
7256 // instruction. Since the shift amount is in-range-or-undefined, we know
7257 // that doing a bittest on the i32 value is ok. We extend to i32 because
7258 // the encoding for the i16 version is larger than the i32 version.
7259 // Also promote i16 to i32 for performance / code size reason.
7260 if (LHS.getValueType() == MVT::i8 ||
7261 LHS.getValueType() == MVT::i16)
7262 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7264 // If the operand types disagree, extend the shift amount to match. Since
7265 // BT ignores high bits (like shifts) we can use anyextend.
7266 if (LHS.getValueType() != RHS.getValueType())
7267 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7269 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7270 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7271 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7272 DAG.getConstant(Cond, MVT::i8), BT);
7278 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7279 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7280 SDValue Op0 = Op.getOperand(0);
7281 SDValue Op1 = Op.getOperand(1);
7282 DebugLoc dl = Op.getDebugLoc();
7283 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7285 // Optimize to BT if possible.
7286 // Lower (X & (1 << N)) == 0 to BT(X, N).
7287 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7288 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7289 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7290 Op1.getOpcode() == ISD::Constant &&
7291 cast<ConstantSDNode>(Op1)->isNullValue() &&
7292 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7293 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7294 if (NewSetCC.getNode())
7298 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
7300 if (Op1.getOpcode() == ISD::Constant &&
7301 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7302 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7303 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7305 // If the input is a setcc, then reuse the input setcc or use a new one with
7306 // the inverted condition.
7307 if (Op0.getOpcode() == X86ISD::SETCC) {
7308 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7309 bool Invert = (CC == ISD::SETNE) ^
7310 cast<ConstantSDNode>(Op1)->isNullValue();
7311 if (!Invert) return Op0;
7313 CCode = X86::GetOppositeBranchCondition(CCode);
7314 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7315 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7319 bool isFP = Op1.getValueType().isFloatingPoint();
7320 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7321 if (X86CC == X86::COND_INVALID)
7324 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7325 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7326 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7329 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7331 SDValue Op0 = Op.getOperand(0);
7332 SDValue Op1 = Op.getOperand(1);
7333 SDValue CC = Op.getOperand(2);
7334 EVT VT = Op.getValueType();
7335 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7336 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7337 DebugLoc dl = Op.getDebugLoc();
7341 EVT VT0 = Op0.getValueType();
7342 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7343 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7346 switch (SetCCOpcode) {
7349 case ISD::SETEQ: SSECC = 0; break;
7351 case ISD::SETGT: Swap = true; // Fallthrough
7353 case ISD::SETOLT: SSECC = 1; break;
7355 case ISD::SETGE: Swap = true; // Fallthrough
7357 case ISD::SETOLE: SSECC = 2; break;
7358 case ISD::SETUO: SSECC = 3; break;
7360 case ISD::SETNE: SSECC = 4; break;
7361 case ISD::SETULE: Swap = true;
7362 case ISD::SETUGE: SSECC = 5; break;
7363 case ISD::SETULT: Swap = true;
7364 case ISD::SETUGT: SSECC = 6; break;
7365 case ISD::SETO: SSECC = 7; break;
7368 std::swap(Op0, Op1);
7370 // In the two special cases we can't handle, emit two comparisons.
7372 if (SetCCOpcode == ISD::SETUEQ) {
7374 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7375 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7376 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7378 else if (SetCCOpcode == ISD::SETONE) {
7380 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7381 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7382 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7384 llvm_unreachable("Illegal FP comparison");
7386 // Handle all other FP comparisons here.
7387 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7390 // We are handling one of the integer comparisons here. Since SSE only has
7391 // GT and EQ comparisons for integer, swapping operands and multiple
7392 // operations may be required for some comparisons.
7393 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7394 bool Swap = false, Invert = false, FlipSigns = false;
7396 switch (VT.getSimpleVT().SimpleTy) {
7398 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7399 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7400 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7401 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7404 switch (SetCCOpcode) {
7406 case ISD::SETNE: Invert = true;
7407 case ISD::SETEQ: Opc = EQOpc; break;
7408 case ISD::SETLT: Swap = true;
7409 case ISD::SETGT: Opc = GTOpc; break;
7410 case ISD::SETGE: Swap = true;
7411 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7412 case ISD::SETULT: Swap = true;
7413 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7414 case ISD::SETUGE: Swap = true;
7415 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7418 std::swap(Op0, Op1);
7420 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7421 // bits of the inputs before performing those operations.
7423 EVT EltVT = VT.getVectorElementType();
7424 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7426 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7427 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7429 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7430 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7433 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7435 // If the logical-not of the result is required, perform that now.
7437 Result = DAG.getNOT(dl, Result, VT);
7442 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7443 static bool isX86LogicalCmp(SDValue Op) {
7444 unsigned Opc = Op.getNode()->getOpcode();
7445 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7447 if (Op.getResNo() == 1 &&
7448 (Opc == X86ISD::ADD ||
7449 Opc == X86ISD::SUB ||
7450 Opc == X86ISD::ADC ||
7451 Opc == X86ISD::SBB ||
7452 Opc == X86ISD::SMUL ||
7453 Opc == X86ISD::UMUL ||
7454 Opc == X86ISD::INC ||
7455 Opc == X86ISD::DEC ||
7456 Opc == X86ISD::OR ||
7457 Opc == X86ISD::XOR ||
7458 Opc == X86ISD::AND))
7461 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7467 static bool isZero(SDValue V) {
7468 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7469 return C && C->isNullValue();
7472 static bool isAllOnes(SDValue V) {
7473 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7474 return C && C->isAllOnesValue();
7477 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7478 bool addTest = true;
7479 SDValue Cond = Op.getOperand(0);
7480 SDValue Op1 = Op.getOperand(1);
7481 SDValue Op2 = Op.getOperand(2);
7482 DebugLoc DL = Op.getDebugLoc();
7485 if (Cond.getOpcode() == ISD::SETCC) {
7486 SDValue NewCond = LowerSETCC(Cond, DAG);
7487 if (NewCond.getNode())
7491 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7492 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7493 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7494 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7495 if (Cond.getOpcode() == X86ISD::SETCC &&
7496 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7497 isZero(Cond.getOperand(1).getOperand(1))) {
7498 SDValue Cmp = Cond.getOperand(1);
7500 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7502 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7503 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7504 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7506 SDValue CmpOp0 = Cmp.getOperand(0);
7507 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7508 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7510 SDValue Res = // Res = 0 or -1.
7511 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7512 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7514 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7515 Res = DAG.getNOT(DL, Res, Res.getValueType());
7517 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7518 if (N2C == 0 || !N2C->isNullValue())
7519 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7524 // Look past (and (setcc_carry (cmp ...)), 1).
7525 if (Cond.getOpcode() == ISD::AND &&
7526 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7527 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7528 if (C && C->getAPIntValue() == 1)
7529 Cond = Cond.getOperand(0);
7532 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7533 // setting operand in place of the X86ISD::SETCC.
7534 if (Cond.getOpcode() == X86ISD::SETCC ||
7535 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7536 CC = Cond.getOperand(0);
7538 SDValue Cmp = Cond.getOperand(1);
7539 unsigned Opc = Cmp.getOpcode();
7540 EVT VT = Op.getValueType();
7542 bool IllegalFPCMov = false;
7543 if (VT.isFloatingPoint() && !VT.isVector() &&
7544 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7545 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7547 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7548 Opc == X86ISD::BT) { // FIXME
7555 // Look pass the truncate.
7556 if (Cond.getOpcode() == ISD::TRUNCATE)
7557 Cond = Cond.getOperand(0);
7559 // We know the result of AND is compared against zero. Try to match
7561 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7562 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7563 if (NewSetCC.getNode()) {
7564 CC = NewSetCC.getOperand(0);
7565 Cond = NewSetCC.getOperand(1);
7572 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7573 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7576 // a < b ? -1 : 0 -> RES = ~setcc_carry
7577 // a < b ? 0 : -1 -> RES = setcc_carry
7578 // a >= b ? -1 : 0 -> RES = setcc_carry
7579 // a >= b ? 0 : -1 -> RES = ~setcc_carry
7580 if (Cond.getOpcode() == X86ISD::CMP) {
7581 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7583 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7584 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7585 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7586 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7587 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7588 return DAG.getNOT(DL, Res, Res.getValueType());
7593 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7594 // condition is true.
7595 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7596 SDValue Ops[] = { Op2, Op1, CC, Cond };
7597 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7600 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7601 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7602 // from the AND / OR.
7603 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7604 Opc = Op.getOpcode();
7605 if (Opc != ISD::OR && Opc != ISD::AND)
7607 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7608 Op.getOperand(0).hasOneUse() &&
7609 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7610 Op.getOperand(1).hasOneUse());
7613 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7614 // 1 and that the SETCC node has a single use.
7615 static bool isXor1OfSetCC(SDValue Op) {
7616 if (Op.getOpcode() != ISD::XOR)
7618 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7619 if (N1C && N1C->getAPIntValue() == 1) {
7620 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7621 Op.getOperand(0).hasOneUse();
7626 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7627 bool addTest = true;
7628 SDValue Chain = Op.getOperand(0);
7629 SDValue Cond = Op.getOperand(1);
7630 SDValue Dest = Op.getOperand(2);
7631 DebugLoc dl = Op.getDebugLoc();
7634 if (Cond.getOpcode() == ISD::SETCC) {
7635 SDValue NewCond = LowerSETCC(Cond, DAG);
7636 if (NewCond.getNode())
7640 // FIXME: LowerXALUO doesn't handle these!!
7641 else if (Cond.getOpcode() == X86ISD::ADD ||
7642 Cond.getOpcode() == X86ISD::SUB ||
7643 Cond.getOpcode() == X86ISD::SMUL ||
7644 Cond.getOpcode() == X86ISD::UMUL)
7645 Cond = LowerXALUO(Cond, DAG);
7648 // Look pass (and (setcc_carry (cmp ...)), 1).
7649 if (Cond.getOpcode() == ISD::AND &&
7650 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7651 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7652 if (C && C->getAPIntValue() == 1)
7653 Cond = Cond.getOperand(0);
7656 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7657 // setting operand in place of the X86ISD::SETCC.
7658 if (Cond.getOpcode() == X86ISD::SETCC ||
7659 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7660 CC = Cond.getOperand(0);
7662 SDValue Cmp = Cond.getOperand(1);
7663 unsigned Opc = Cmp.getOpcode();
7664 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7665 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7669 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7673 // These can only come from an arithmetic instruction with overflow,
7674 // e.g. SADDO, UADDO.
7675 Cond = Cond.getNode()->getOperand(1);
7682 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7683 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7684 if (CondOpc == ISD::OR) {
7685 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7686 // two branches instead of an explicit OR instruction with a
7688 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7689 isX86LogicalCmp(Cmp)) {
7690 CC = Cond.getOperand(0).getOperand(0);
7691 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7692 Chain, Dest, CC, Cmp);
7693 CC = Cond.getOperand(1).getOperand(0);
7697 } else { // ISD::AND
7698 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7699 // two branches instead of an explicit AND instruction with a
7700 // separate test. However, we only do this if this block doesn't
7701 // have a fall-through edge, because this requires an explicit
7702 // jmp when the condition is false.
7703 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7704 isX86LogicalCmp(Cmp) &&
7705 Op.getNode()->hasOneUse()) {
7706 X86::CondCode CCode =
7707 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7708 CCode = X86::GetOppositeBranchCondition(CCode);
7709 CC = DAG.getConstant(CCode, MVT::i8);
7710 SDNode *User = *Op.getNode()->use_begin();
7711 // Look for an unconditional branch following this conditional branch.
7712 // We need this because we need to reverse the successors in order
7713 // to implement FCMP_OEQ.
7714 if (User->getOpcode() == ISD::BR) {
7715 SDValue FalseBB = User->getOperand(1);
7717 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7718 assert(NewBR == User);
7722 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7723 Chain, Dest, CC, Cmp);
7724 X86::CondCode CCode =
7725 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7726 CCode = X86::GetOppositeBranchCondition(CCode);
7727 CC = DAG.getConstant(CCode, MVT::i8);
7733 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7734 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7735 // It should be transformed during dag combiner except when the condition
7736 // is set by a arithmetics with overflow node.
7737 X86::CondCode CCode =
7738 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7739 CCode = X86::GetOppositeBranchCondition(CCode);
7740 CC = DAG.getConstant(CCode, MVT::i8);
7741 Cond = Cond.getOperand(0).getOperand(1);
7747 // Look pass the truncate.
7748 if (Cond.getOpcode() == ISD::TRUNCATE)
7749 Cond = Cond.getOperand(0);
7751 // We know the result of AND is compared against zero. Try to match
7753 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7754 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7755 if (NewSetCC.getNode()) {
7756 CC = NewSetCC.getOperand(0);
7757 Cond = NewSetCC.getOperand(1);
7764 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7765 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7767 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7768 Chain, Dest, CC, Cond);
7772 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7773 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7774 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7775 // that the guard pages used by the OS virtual memory manager are allocated in
7776 // correct sequence.
7778 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7779 SelectionDAG &DAG) const {
7780 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7781 "This should be used only on Windows targets");
7782 DebugLoc dl = Op.getDebugLoc();
7785 SDValue Chain = Op.getOperand(0);
7786 SDValue Size = Op.getOperand(1);
7787 // FIXME: Ensure alignment here
7791 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7793 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7794 Flag = Chain.getValue(1);
7796 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7798 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7799 Flag = Chain.getValue(1);
7801 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7803 SDValue Ops1[2] = { Chain.getValue(0), Chain };
7804 return DAG.getMergeValues(Ops1, 2, dl);
7807 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7808 MachineFunction &MF = DAG.getMachineFunction();
7809 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7811 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7812 DebugLoc DL = Op.getDebugLoc();
7814 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7815 // vastart just stores the address of the VarArgsFrameIndex slot into the
7816 // memory location argument.
7817 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7819 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7820 MachinePointerInfo(SV), false, false, 0);
7824 // gp_offset (0 - 6 * 8)
7825 // fp_offset (48 - 48 + 8 * 16)
7826 // overflow_arg_area (point to parameters coming in memory).
7828 SmallVector<SDValue, 8> MemOps;
7829 SDValue FIN = Op.getOperand(1);
7831 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7832 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7834 FIN, MachinePointerInfo(SV), false, false, 0);
7835 MemOps.push_back(Store);
7838 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7839 FIN, DAG.getIntPtrConstant(4));
7840 Store = DAG.getStore(Op.getOperand(0), DL,
7841 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7843 FIN, MachinePointerInfo(SV, 4), false, false, 0);
7844 MemOps.push_back(Store);
7846 // Store ptr to overflow_arg_area
7847 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7848 FIN, DAG.getIntPtrConstant(4));
7849 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7851 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7852 MachinePointerInfo(SV, 8),
7854 MemOps.push_back(Store);
7856 // Store ptr to reg_save_area.
7857 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7858 FIN, DAG.getIntPtrConstant(8));
7859 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7861 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7862 MachinePointerInfo(SV, 16), false, false, 0);
7863 MemOps.push_back(Store);
7864 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7865 &MemOps[0], MemOps.size());
7868 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7869 assert(Subtarget->is64Bit() &&
7870 "LowerVAARG only handles 64-bit va_arg!");
7871 assert((Subtarget->isTargetLinux() ||
7872 Subtarget->isTargetDarwin()) &&
7873 "Unhandled target in LowerVAARG");
7874 assert(Op.getNode()->getNumOperands() == 4);
7875 SDValue Chain = Op.getOperand(0);
7876 SDValue SrcPtr = Op.getOperand(1);
7877 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7878 unsigned Align = Op.getConstantOperandVal(3);
7879 DebugLoc dl = Op.getDebugLoc();
7881 EVT ArgVT = Op.getNode()->getValueType(0);
7882 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7883 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
7886 // Decide which area this value should be read from.
7887 // TODO: Implement the AMD64 ABI in its entirety. This simple
7888 // selection mechanism works only for the basic types.
7889 if (ArgVT == MVT::f80) {
7890 llvm_unreachable("va_arg for f80 not yet implemented");
7891 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
7892 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
7893 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
7894 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
7896 llvm_unreachable("Unhandled argument type in LowerVAARG");
7900 // Sanity Check: Make sure using fp_offset makes sense.
7901 assert(!UseSoftFloat &&
7902 !(DAG.getMachineFunction()
7903 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
7904 Subtarget->hasXMM());
7907 // Insert VAARG_64 node into the DAG
7908 // VAARG_64 returns two values: Variable Argument Address, Chain
7909 SmallVector<SDValue, 11> InstOps;
7910 InstOps.push_back(Chain);
7911 InstOps.push_back(SrcPtr);
7912 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
7913 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
7914 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
7915 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
7916 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
7917 VTs, &InstOps[0], InstOps.size(),
7919 MachinePointerInfo(SV),
7924 Chain = VAARG.getValue(1);
7926 // Load the next argument and return it
7927 return DAG.getLoad(ArgVT, dl,
7930 MachinePointerInfo(),
7934 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7935 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7936 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7937 SDValue Chain = Op.getOperand(0);
7938 SDValue DstPtr = Op.getOperand(1);
7939 SDValue SrcPtr = Op.getOperand(2);
7940 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7941 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7942 DebugLoc DL = Op.getDebugLoc();
7944 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7945 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7947 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7951 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7952 DebugLoc dl = Op.getDebugLoc();
7953 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7955 default: return SDValue(); // Don't custom lower most intrinsics.
7956 // Comparison intrinsics.
7957 case Intrinsic::x86_sse_comieq_ss:
7958 case Intrinsic::x86_sse_comilt_ss:
7959 case Intrinsic::x86_sse_comile_ss:
7960 case Intrinsic::x86_sse_comigt_ss:
7961 case Intrinsic::x86_sse_comige_ss:
7962 case Intrinsic::x86_sse_comineq_ss:
7963 case Intrinsic::x86_sse_ucomieq_ss:
7964 case Intrinsic::x86_sse_ucomilt_ss:
7965 case Intrinsic::x86_sse_ucomile_ss:
7966 case Intrinsic::x86_sse_ucomigt_ss:
7967 case Intrinsic::x86_sse_ucomige_ss:
7968 case Intrinsic::x86_sse_ucomineq_ss:
7969 case Intrinsic::x86_sse2_comieq_sd:
7970 case Intrinsic::x86_sse2_comilt_sd:
7971 case Intrinsic::x86_sse2_comile_sd:
7972 case Intrinsic::x86_sse2_comigt_sd:
7973 case Intrinsic::x86_sse2_comige_sd:
7974 case Intrinsic::x86_sse2_comineq_sd:
7975 case Intrinsic::x86_sse2_ucomieq_sd:
7976 case Intrinsic::x86_sse2_ucomilt_sd:
7977 case Intrinsic::x86_sse2_ucomile_sd:
7978 case Intrinsic::x86_sse2_ucomigt_sd:
7979 case Intrinsic::x86_sse2_ucomige_sd:
7980 case Intrinsic::x86_sse2_ucomineq_sd: {
7982 ISD::CondCode CC = ISD::SETCC_INVALID;
7985 case Intrinsic::x86_sse_comieq_ss:
7986 case Intrinsic::x86_sse2_comieq_sd:
7990 case Intrinsic::x86_sse_comilt_ss:
7991 case Intrinsic::x86_sse2_comilt_sd:
7995 case Intrinsic::x86_sse_comile_ss:
7996 case Intrinsic::x86_sse2_comile_sd:
8000 case Intrinsic::x86_sse_comigt_ss:
8001 case Intrinsic::x86_sse2_comigt_sd:
8005 case Intrinsic::x86_sse_comige_ss:
8006 case Intrinsic::x86_sse2_comige_sd:
8010 case Intrinsic::x86_sse_comineq_ss:
8011 case Intrinsic::x86_sse2_comineq_sd:
8015 case Intrinsic::x86_sse_ucomieq_ss:
8016 case Intrinsic::x86_sse2_ucomieq_sd:
8017 Opc = X86ISD::UCOMI;
8020 case Intrinsic::x86_sse_ucomilt_ss:
8021 case Intrinsic::x86_sse2_ucomilt_sd:
8022 Opc = X86ISD::UCOMI;
8025 case Intrinsic::x86_sse_ucomile_ss:
8026 case Intrinsic::x86_sse2_ucomile_sd:
8027 Opc = X86ISD::UCOMI;
8030 case Intrinsic::x86_sse_ucomigt_ss:
8031 case Intrinsic::x86_sse2_ucomigt_sd:
8032 Opc = X86ISD::UCOMI;
8035 case Intrinsic::x86_sse_ucomige_ss:
8036 case Intrinsic::x86_sse2_ucomige_sd:
8037 Opc = X86ISD::UCOMI;
8040 case Intrinsic::x86_sse_ucomineq_ss:
8041 case Intrinsic::x86_sse2_ucomineq_sd:
8042 Opc = X86ISD::UCOMI;
8047 SDValue LHS = Op.getOperand(1);
8048 SDValue RHS = Op.getOperand(2);
8049 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8050 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8051 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8052 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8053 DAG.getConstant(X86CC, MVT::i8), Cond);
8054 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8056 // ptest and testp intrinsics. The intrinsic these come from are designed to
8057 // return an integer value, not just an instruction so lower it to the ptest
8058 // or testp pattern and a setcc for the result.
8059 case Intrinsic::x86_sse41_ptestz:
8060 case Intrinsic::x86_sse41_ptestc:
8061 case Intrinsic::x86_sse41_ptestnzc:
8062 case Intrinsic::x86_avx_ptestz_256:
8063 case Intrinsic::x86_avx_ptestc_256:
8064 case Intrinsic::x86_avx_ptestnzc_256:
8065 case Intrinsic::x86_avx_vtestz_ps:
8066 case Intrinsic::x86_avx_vtestc_ps:
8067 case Intrinsic::x86_avx_vtestnzc_ps:
8068 case Intrinsic::x86_avx_vtestz_pd:
8069 case Intrinsic::x86_avx_vtestc_pd:
8070 case Intrinsic::x86_avx_vtestnzc_pd:
8071 case Intrinsic::x86_avx_vtestz_ps_256:
8072 case Intrinsic::x86_avx_vtestc_ps_256:
8073 case Intrinsic::x86_avx_vtestnzc_ps_256:
8074 case Intrinsic::x86_avx_vtestz_pd_256:
8075 case Intrinsic::x86_avx_vtestc_pd_256:
8076 case Intrinsic::x86_avx_vtestnzc_pd_256: {
8077 bool IsTestPacked = false;
8080 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8081 case Intrinsic::x86_avx_vtestz_ps:
8082 case Intrinsic::x86_avx_vtestz_pd:
8083 case Intrinsic::x86_avx_vtestz_ps_256:
8084 case Intrinsic::x86_avx_vtestz_pd_256:
8085 IsTestPacked = true; // Fallthrough
8086 case Intrinsic::x86_sse41_ptestz:
8087 case Intrinsic::x86_avx_ptestz_256:
8089 X86CC = X86::COND_E;
8091 case Intrinsic::x86_avx_vtestc_ps:
8092 case Intrinsic::x86_avx_vtestc_pd:
8093 case Intrinsic::x86_avx_vtestc_ps_256:
8094 case Intrinsic::x86_avx_vtestc_pd_256:
8095 IsTestPacked = true; // Fallthrough
8096 case Intrinsic::x86_sse41_ptestc:
8097 case Intrinsic::x86_avx_ptestc_256:
8099 X86CC = X86::COND_B;
8101 case Intrinsic::x86_avx_vtestnzc_ps:
8102 case Intrinsic::x86_avx_vtestnzc_pd:
8103 case Intrinsic::x86_avx_vtestnzc_ps_256:
8104 case Intrinsic::x86_avx_vtestnzc_pd_256:
8105 IsTestPacked = true; // Fallthrough
8106 case Intrinsic::x86_sse41_ptestnzc:
8107 case Intrinsic::x86_avx_ptestnzc_256:
8109 X86CC = X86::COND_A;
8113 SDValue LHS = Op.getOperand(1);
8114 SDValue RHS = Op.getOperand(2);
8115 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8116 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8117 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8118 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8119 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8122 // Fix vector shift instructions where the last operand is a non-immediate
8124 case Intrinsic::x86_sse2_pslli_w:
8125 case Intrinsic::x86_sse2_pslli_d:
8126 case Intrinsic::x86_sse2_pslli_q:
8127 case Intrinsic::x86_sse2_psrli_w:
8128 case Intrinsic::x86_sse2_psrli_d:
8129 case Intrinsic::x86_sse2_psrli_q:
8130 case Intrinsic::x86_sse2_psrai_w:
8131 case Intrinsic::x86_sse2_psrai_d:
8132 case Intrinsic::x86_mmx_pslli_w:
8133 case Intrinsic::x86_mmx_pslli_d:
8134 case Intrinsic::x86_mmx_pslli_q:
8135 case Intrinsic::x86_mmx_psrli_w:
8136 case Intrinsic::x86_mmx_psrli_d:
8137 case Intrinsic::x86_mmx_psrli_q:
8138 case Intrinsic::x86_mmx_psrai_w:
8139 case Intrinsic::x86_mmx_psrai_d: {
8140 SDValue ShAmt = Op.getOperand(2);
8141 if (isa<ConstantSDNode>(ShAmt))
8144 unsigned NewIntNo = 0;
8145 EVT ShAmtVT = MVT::v4i32;
8147 case Intrinsic::x86_sse2_pslli_w:
8148 NewIntNo = Intrinsic::x86_sse2_psll_w;
8150 case Intrinsic::x86_sse2_pslli_d:
8151 NewIntNo = Intrinsic::x86_sse2_psll_d;
8153 case Intrinsic::x86_sse2_pslli_q:
8154 NewIntNo = Intrinsic::x86_sse2_psll_q;
8156 case Intrinsic::x86_sse2_psrli_w:
8157 NewIntNo = Intrinsic::x86_sse2_psrl_w;
8159 case Intrinsic::x86_sse2_psrli_d:
8160 NewIntNo = Intrinsic::x86_sse2_psrl_d;
8162 case Intrinsic::x86_sse2_psrli_q:
8163 NewIntNo = Intrinsic::x86_sse2_psrl_q;
8165 case Intrinsic::x86_sse2_psrai_w:
8166 NewIntNo = Intrinsic::x86_sse2_psra_w;
8168 case Intrinsic::x86_sse2_psrai_d:
8169 NewIntNo = Intrinsic::x86_sse2_psra_d;
8172 ShAmtVT = MVT::v2i32;
8174 case Intrinsic::x86_mmx_pslli_w:
8175 NewIntNo = Intrinsic::x86_mmx_psll_w;
8177 case Intrinsic::x86_mmx_pslli_d:
8178 NewIntNo = Intrinsic::x86_mmx_psll_d;
8180 case Intrinsic::x86_mmx_pslli_q:
8181 NewIntNo = Intrinsic::x86_mmx_psll_q;
8183 case Intrinsic::x86_mmx_psrli_w:
8184 NewIntNo = Intrinsic::x86_mmx_psrl_w;
8186 case Intrinsic::x86_mmx_psrli_d:
8187 NewIntNo = Intrinsic::x86_mmx_psrl_d;
8189 case Intrinsic::x86_mmx_psrli_q:
8190 NewIntNo = Intrinsic::x86_mmx_psrl_q;
8192 case Intrinsic::x86_mmx_psrai_w:
8193 NewIntNo = Intrinsic::x86_mmx_psra_w;
8195 case Intrinsic::x86_mmx_psrai_d:
8196 NewIntNo = Intrinsic::x86_mmx_psra_d;
8198 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8204 // The vector shift intrinsics with scalars uses 32b shift amounts but
8205 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8209 ShOps[1] = DAG.getConstant(0, MVT::i32);
8210 if (ShAmtVT == MVT::v4i32) {
8211 ShOps[2] = DAG.getUNDEF(MVT::i32);
8212 ShOps[3] = DAG.getUNDEF(MVT::i32);
8213 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8215 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8216 // FIXME this must be lowered to get rid of the invalid type.
8219 EVT VT = Op.getValueType();
8220 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8221 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8222 DAG.getConstant(NewIntNo, MVT::i32),
8223 Op.getOperand(1), ShAmt);
8228 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8229 SelectionDAG &DAG) const {
8230 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8231 MFI->setReturnAddressIsTaken(true);
8233 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8234 DebugLoc dl = Op.getDebugLoc();
8237 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8239 DAG.getConstant(TD->getPointerSize(),
8240 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8241 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8242 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8244 MachinePointerInfo(), false, false, 0);
8247 // Just load the return address.
8248 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8249 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8250 RetAddrFI, MachinePointerInfo(), false, false, 0);
8253 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8254 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8255 MFI->setFrameAddressIsTaken(true);
8257 EVT VT = Op.getValueType();
8258 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
8259 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8260 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8261 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8263 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8264 MachinePointerInfo(),
8269 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8270 SelectionDAG &DAG) const {
8271 return DAG.getIntPtrConstant(2*TD->getPointerSize());
8274 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8275 MachineFunction &MF = DAG.getMachineFunction();
8276 SDValue Chain = Op.getOperand(0);
8277 SDValue Offset = Op.getOperand(1);
8278 SDValue Handler = Op.getOperand(2);
8279 DebugLoc dl = Op.getDebugLoc();
8281 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8282 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8284 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8286 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8287 DAG.getIntPtrConstant(TD->getPointerSize()));
8288 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8289 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8291 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8292 MF.getRegInfo().addLiveOut(StoreAddrReg);
8294 return DAG.getNode(X86ISD::EH_RETURN, dl,
8296 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8299 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8300 SelectionDAG &DAG) const {
8301 SDValue Root = Op.getOperand(0);
8302 SDValue Trmp = Op.getOperand(1); // trampoline
8303 SDValue FPtr = Op.getOperand(2); // nested function
8304 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8305 DebugLoc dl = Op.getDebugLoc();
8307 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8309 if (Subtarget->is64Bit()) {
8310 SDValue OutChains[6];
8312 // Large code-model.
8313 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8314 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8316 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8317 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8319 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8321 // Load the pointer to the nested function into R11.
8322 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8323 SDValue Addr = Trmp;
8324 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8325 Addr, MachinePointerInfo(TrmpAddr),
8328 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8329 DAG.getConstant(2, MVT::i64));
8330 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8331 MachinePointerInfo(TrmpAddr, 2),
8334 // Load the 'nest' parameter value into R10.
8335 // R10 is specified in X86CallingConv.td
8336 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8337 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8338 DAG.getConstant(10, MVT::i64));
8339 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8340 Addr, MachinePointerInfo(TrmpAddr, 10),
8343 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8344 DAG.getConstant(12, MVT::i64));
8345 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8346 MachinePointerInfo(TrmpAddr, 12),
8349 // Jump to the nested function.
8350 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8351 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8352 DAG.getConstant(20, MVT::i64));
8353 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8354 Addr, MachinePointerInfo(TrmpAddr, 20),
8357 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8358 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8359 DAG.getConstant(22, MVT::i64));
8360 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8361 MachinePointerInfo(TrmpAddr, 22),
8365 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8366 return DAG.getMergeValues(Ops, 2, dl);
8368 const Function *Func =
8369 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8370 CallingConv::ID CC = Func->getCallingConv();
8375 llvm_unreachable("Unsupported calling convention");
8376 case CallingConv::C:
8377 case CallingConv::X86_StdCall: {
8378 // Pass 'nest' parameter in ECX.
8379 // Must be kept in sync with X86CallingConv.td
8382 // Check that ECX wasn't needed by an 'inreg' parameter.
8383 const FunctionType *FTy = Func->getFunctionType();
8384 const AttrListPtr &Attrs = Func->getAttributes();
8386 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8387 unsigned InRegCount = 0;
8390 for (FunctionType::param_iterator I = FTy->param_begin(),
8391 E = FTy->param_end(); I != E; ++I, ++Idx)
8392 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8393 // FIXME: should only count parameters that are lowered to integers.
8394 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8396 if (InRegCount > 2) {
8397 report_fatal_error("Nest register in use - reduce number of inreg"
8403 case CallingConv::X86_FastCall:
8404 case CallingConv::X86_ThisCall:
8405 case CallingConv::Fast:
8406 // Pass 'nest' parameter in EAX.
8407 // Must be kept in sync with X86CallingConv.td
8412 SDValue OutChains[4];
8415 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8416 DAG.getConstant(10, MVT::i32));
8417 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8419 // This is storing the opcode for MOV32ri.
8420 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8421 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8422 OutChains[0] = DAG.getStore(Root, dl,
8423 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8424 Trmp, MachinePointerInfo(TrmpAddr),
8427 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8428 DAG.getConstant(1, MVT::i32));
8429 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8430 MachinePointerInfo(TrmpAddr, 1),
8433 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8434 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8435 DAG.getConstant(5, MVT::i32));
8436 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8437 MachinePointerInfo(TrmpAddr, 5),
8440 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8441 DAG.getConstant(6, MVT::i32));
8442 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8443 MachinePointerInfo(TrmpAddr, 6),
8447 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8448 return DAG.getMergeValues(Ops, 2, dl);
8452 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8453 SelectionDAG &DAG) const {
8455 The rounding mode is in bits 11:10 of FPSR, and has the following
8462 FLT_ROUNDS, on the other hand, expects the following:
8469 To perform the conversion, we do:
8470 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8473 MachineFunction &MF = DAG.getMachineFunction();
8474 const TargetMachine &TM = MF.getTarget();
8475 const TargetFrameLowering &TFI = *TM.getFrameLowering();
8476 unsigned StackAlignment = TFI.getStackAlignment();
8477 EVT VT = Op.getValueType();
8478 DebugLoc DL = Op.getDebugLoc();
8480 // Save FP Control Word to stack slot
8481 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8482 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8485 MachineMemOperand *MMO =
8486 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8487 MachineMemOperand::MOStore, 2, 2);
8489 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8490 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8491 DAG.getVTList(MVT::Other),
8492 Ops, 2, MVT::i16, MMO);
8494 // Load FP Control Word from stack slot
8495 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8496 MachinePointerInfo(), false, false, 0);
8498 // Transform as necessary
8500 DAG.getNode(ISD::SRL, DL, MVT::i16,
8501 DAG.getNode(ISD::AND, DL, MVT::i16,
8502 CWD, DAG.getConstant(0x800, MVT::i16)),
8503 DAG.getConstant(11, MVT::i8));
8505 DAG.getNode(ISD::SRL, DL, MVT::i16,
8506 DAG.getNode(ISD::AND, DL, MVT::i16,
8507 CWD, DAG.getConstant(0x400, MVT::i16)),
8508 DAG.getConstant(9, MVT::i8));
8511 DAG.getNode(ISD::AND, DL, MVT::i16,
8512 DAG.getNode(ISD::ADD, DL, MVT::i16,
8513 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8514 DAG.getConstant(1, MVT::i16)),
8515 DAG.getConstant(3, MVT::i16));
8518 return DAG.getNode((VT.getSizeInBits() < 16 ?
8519 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8522 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8523 EVT VT = Op.getValueType();
8525 unsigned NumBits = VT.getSizeInBits();
8526 DebugLoc dl = Op.getDebugLoc();
8528 Op = Op.getOperand(0);
8529 if (VT == MVT::i8) {
8530 // Zero extend to i32 since there is not an i8 bsr.
8532 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8535 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8536 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8537 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8539 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8542 DAG.getConstant(NumBits+NumBits-1, OpVT),
8543 DAG.getConstant(X86::COND_E, MVT::i8),
8546 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8548 // Finally xor with NumBits-1.
8549 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8552 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8556 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8557 EVT VT = Op.getValueType();
8559 unsigned NumBits = VT.getSizeInBits();
8560 DebugLoc dl = Op.getDebugLoc();
8562 Op = Op.getOperand(0);
8563 if (VT == MVT::i8) {
8565 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8568 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8569 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8570 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8572 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8575 DAG.getConstant(NumBits, OpVT),
8576 DAG.getConstant(X86::COND_E, MVT::i8),
8579 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8582 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8586 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8587 EVT VT = Op.getValueType();
8588 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8589 DebugLoc dl = Op.getDebugLoc();
8591 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8592 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8593 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8594 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8595 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8597 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8598 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8599 // return AloBlo + AloBhi + AhiBlo;
8601 SDValue A = Op.getOperand(0);
8602 SDValue B = Op.getOperand(1);
8604 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8605 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8606 A, DAG.getConstant(32, MVT::i32));
8607 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8608 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8609 B, DAG.getConstant(32, MVT::i32));
8610 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8611 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8613 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8614 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8616 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8617 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8619 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8620 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8621 AloBhi, DAG.getConstant(32, MVT::i32));
8622 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8623 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8624 AhiBlo, DAG.getConstant(32, MVT::i32));
8625 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8626 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8630 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8631 EVT VT = Op.getValueType();
8632 DebugLoc dl = Op.getDebugLoc();
8633 SDValue R = Op.getOperand(0);
8635 LLVMContext *Context = DAG.getContext();
8637 assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8639 if (VT == MVT::v4i32) {
8640 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8641 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8642 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8644 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8646 std::vector<Constant*> CV(4, CI);
8647 Constant *C = ConstantVector::get(CV);
8648 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8649 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8650 MachinePointerInfo::getConstantPool(),
8653 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8654 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8655 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8656 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8658 if (VT == MVT::v16i8) {
8660 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8661 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8662 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8664 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8665 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8667 std::vector<Constant*> CVM1(16, CM1);
8668 std::vector<Constant*> CVM2(16, CM2);
8669 Constant *C = ConstantVector::get(CVM1);
8670 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8671 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8672 MachinePointerInfo::getConstantPool(),
8675 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8676 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8677 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8678 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8679 DAG.getConstant(4, MVT::i32));
8680 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8682 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8684 C = ConstantVector::get(CVM2);
8685 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8686 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8687 MachinePointerInfo::getConstantPool(),
8690 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8691 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8692 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8693 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8694 DAG.getConstant(2, MVT::i32));
8695 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8697 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8699 // return pblendv(r, r+r, a);
8700 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8701 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8707 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8708 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8709 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8710 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8711 // has only one use.
8712 SDNode *N = Op.getNode();
8713 SDValue LHS = N->getOperand(0);
8714 SDValue RHS = N->getOperand(1);
8715 unsigned BaseOp = 0;
8717 DebugLoc DL = Op.getDebugLoc();
8718 switch (Op.getOpcode()) {
8719 default: llvm_unreachable("Unknown ovf instruction!");
8721 // A subtract of one will be selected as a INC. Note that INC doesn't
8722 // set CF, so we can't do this for UADDO.
8723 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8724 if (C->getAPIntValue() == 1) {
8725 BaseOp = X86ISD::INC;
8729 BaseOp = X86ISD::ADD;
8733 BaseOp = X86ISD::ADD;
8737 // A subtract of one will be selected as a DEC. Note that DEC doesn't
8738 // set CF, so we can't do this for USUBO.
8739 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8740 if (C->getAPIntValue() == 1) {
8741 BaseOp = X86ISD::DEC;
8745 BaseOp = X86ISD::SUB;
8749 BaseOp = X86ISD::SUB;
8753 BaseOp = X86ISD::SMUL;
8756 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8757 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8759 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8762 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8763 DAG.getConstant(X86::COND_O, MVT::i32),
8764 SDValue(Sum.getNode(), 2));
8766 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8771 // Also sets EFLAGS.
8772 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8773 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8776 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8777 DAG.getConstant(Cond, MVT::i32),
8778 SDValue(Sum.getNode(), 1));
8780 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8784 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8785 DebugLoc dl = Op.getDebugLoc();
8787 if (!Subtarget->hasSSE2()) {
8788 SDValue Chain = Op.getOperand(0);
8789 SDValue Zero = DAG.getConstant(0,
8790 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8792 DAG.getRegister(X86::ESP, MVT::i32), // Base
8793 DAG.getTargetConstant(1, MVT::i8), // Scale
8794 DAG.getRegister(0, MVT::i32), // Index
8795 DAG.getTargetConstant(0, MVT::i32), // Disp
8796 DAG.getRegister(0, MVT::i32), // Segment.
8801 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8802 array_lengthof(Ops));
8803 return SDValue(Res, 0);
8806 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8808 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8810 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8811 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8812 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8813 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8815 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8816 if (!Op1 && !Op2 && !Op3 && Op4)
8817 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8819 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8820 if (Op1 && !Op2 && !Op3 && !Op4)
8821 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8823 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8825 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8828 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8829 EVT T = Op.getValueType();
8830 DebugLoc DL = Op.getDebugLoc();
8833 switch(T.getSimpleVT().SimpleTy) {
8835 assert(false && "Invalid value type!");
8836 case MVT::i8: Reg = X86::AL; size = 1; break;
8837 case MVT::i16: Reg = X86::AX; size = 2; break;
8838 case MVT::i32: Reg = X86::EAX; size = 4; break;
8840 assert(Subtarget->is64Bit() && "Node not type legal!");
8841 Reg = X86::RAX; size = 8;
8844 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8845 Op.getOperand(2), SDValue());
8846 SDValue Ops[] = { cpIn.getValue(0),
8849 DAG.getTargetConstant(size, MVT::i8),
8851 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8852 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8853 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8856 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8860 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8861 SelectionDAG &DAG) const {
8862 assert(Subtarget->is64Bit() && "Result not type legalized?");
8863 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8864 SDValue TheChain = Op.getOperand(0);
8865 DebugLoc dl = Op.getDebugLoc();
8866 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8867 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8868 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8870 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8871 DAG.getConstant(32, MVT::i8));
8873 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8876 return DAG.getMergeValues(Ops, 2, dl);
8879 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
8880 SelectionDAG &DAG) const {
8881 EVT SrcVT = Op.getOperand(0).getValueType();
8882 EVT DstVT = Op.getValueType();
8883 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8884 Subtarget->hasMMX() && "Unexpected custom BITCAST");
8885 assert((DstVT == MVT::i64 ||
8886 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8887 "Unexpected custom BITCAST");
8888 // i64 <=> MMX conversions are Legal.
8889 if (SrcVT==MVT::i64 && DstVT.isVector())
8891 if (DstVT==MVT::i64 && SrcVT.isVector())
8893 // MMX <=> MMX conversions are Legal.
8894 if (SrcVT.isVector() && DstVT.isVector())
8896 // All other conversions need to be expanded.
8900 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8901 SDNode *Node = Op.getNode();
8902 DebugLoc dl = Node->getDebugLoc();
8903 EVT T = Node->getValueType(0);
8904 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8905 DAG.getConstant(0, T), Node->getOperand(2));
8906 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8907 cast<AtomicSDNode>(Node)->getMemoryVT(),
8908 Node->getOperand(0),
8909 Node->getOperand(1), negOp,
8910 cast<AtomicSDNode>(Node)->getSrcValue(),
8911 cast<AtomicSDNode>(Node)->getAlignment());
8914 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
8915 EVT VT = Op.getNode()->getValueType(0);
8917 // Let legalize expand this if it isn't a legal type yet.
8918 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8921 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8924 bool ExtraOp = false;
8925 switch (Op.getOpcode()) {
8926 default: assert(0 && "Invalid code");
8927 case ISD::ADDC: Opc = X86ISD::ADD; break;
8928 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
8929 case ISD::SUBC: Opc = X86ISD::SUB; break;
8930 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
8934 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
8936 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
8937 Op.getOperand(1), Op.getOperand(2));
8940 /// LowerOperation - Provide custom lowering hooks for some operations.
8942 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8943 switch (Op.getOpcode()) {
8944 default: llvm_unreachable("Should not custom lower this!");
8945 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
8946 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
8947 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
8948 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
8949 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
8950 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8951 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8952 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8953 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
8954 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
8955 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
8956 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8957 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8958 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8959 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
8960 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8961 case ISD::SHL_PARTS:
8962 case ISD::SRA_PARTS:
8963 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
8964 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
8965 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
8966 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
8967 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
8968 case ISD::FABS: return LowerFABS(Op, DAG);
8969 case ISD::FNEG: return LowerFNEG(Op, DAG);
8970 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
8971 case ISD::SETCC: return LowerSETCC(Op, DAG);
8972 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
8973 case ISD::SELECT: return LowerSELECT(Op, DAG);
8974 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
8975 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
8976 case ISD::VASTART: return LowerVASTART(Op, DAG);
8977 case ISD::VAARG: return LowerVAARG(Op, DAG);
8978 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
8979 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8980 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8981 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8982 case ISD::FRAME_TO_ARGS_OFFSET:
8983 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8984 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8985 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
8986 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
8987 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8988 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
8989 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
8990 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
8991 case ISD::SHL: return LowerSHL(Op, DAG);
8997 case ISD::UMULO: return LowerXALUO(Op, DAG);
8998 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
8999 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
9003 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9007 void X86TargetLowering::
9008 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9009 SelectionDAG &DAG, unsigned NewOp) const {
9010 EVT T = Node->getValueType(0);
9011 DebugLoc dl = Node->getDebugLoc();
9012 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9014 SDValue Chain = Node->getOperand(0);
9015 SDValue In1 = Node->getOperand(1);
9016 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9017 Node->getOperand(2), DAG.getIntPtrConstant(0));
9018 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9019 Node->getOperand(2), DAG.getIntPtrConstant(1));
9020 SDValue Ops[] = { Chain, In1, In2L, In2H };
9021 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9023 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9024 cast<MemSDNode>(Node)->getMemOperand());
9025 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9026 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9027 Results.push_back(Result.getValue(2));
9030 /// ReplaceNodeResults - Replace a node with an illegal result type
9031 /// with a new node built out of custom code.
9032 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9033 SmallVectorImpl<SDValue>&Results,
9034 SelectionDAG &DAG) const {
9035 DebugLoc dl = N->getDebugLoc();
9036 switch (N->getOpcode()) {
9038 assert(false && "Do not know how to custom type legalize this operation!");
9044 // We don't want to expand or promote these.
9046 case ISD::FP_TO_SINT: {
9047 std::pair<SDValue,SDValue> Vals =
9048 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9049 SDValue FIST = Vals.first, StackSlot = Vals.second;
9050 if (FIST.getNode() != 0) {
9051 EVT VT = N->getValueType(0);
9052 // Return a load from the stack slot.
9053 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9054 MachinePointerInfo(), false, false, 0));
9058 case ISD::READCYCLECOUNTER: {
9059 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9060 SDValue TheChain = N->getOperand(0);
9061 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9062 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9064 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9066 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9067 SDValue Ops[] = { eax, edx };
9068 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9069 Results.push_back(edx.getValue(1));
9072 case ISD::ATOMIC_CMP_SWAP: {
9073 EVT T = N->getValueType(0);
9074 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9075 SDValue cpInL, cpInH;
9076 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9077 DAG.getConstant(0, MVT::i32));
9078 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9079 DAG.getConstant(1, MVT::i32));
9080 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9081 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9083 SDValue swapInL, swapInH;
9084 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9085 DAG.getConstant(0, MVT::i32));
9086 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9087 DAG.getConstant(1, MVT::i32));
9088 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9090 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9091 swapInL.getValue(1));
9092 SDValue Ops[] = { swapInH.getValue(0),
9094 swapInH.getValue(1) };
9095 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9096 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9097 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9099 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9100 MVT::i32, Result.getValue(1));
9101 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9102 MVT::i32, cpOutL.getValue(2));
9103 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9104 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9105 Results.push_back(cpOutH.getValue(1));
9108 case ISD::ATOMIC_LOAD_ADD:
9109 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9111 case ISD::ATOMIC_LOAD_AND:
9112 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9114 case ISD::ATOMIC_LOAD_NAND:
9115 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9117 case ISD::ATOMIC_LOAD_OR:
9118 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9120 case ISD::ATOMIC_LOAD_SUB:
9121 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9123 case ISD::ATOMIC_LOAD_XOR:
9124 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9126 case ISD::ATOMIC_SWAP:
9127 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9132 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9134 default: return NULL;
9135 case X86ISD::BSF: return "X86ISD::BSF";
9136 case X86ISD::BSR: return "X86ISD::BSR";
9137 case X86ISD::SHLD: return "X86ISD::SHLD";
9138 case X86ISD::SHRD: return "X86ISD::SHRD";
9139 case X86ISD::FAND: return "X86ISD::FAND";
9140 case X86ISD::FOR: return "X86ISD::FOR";
9141 case X86ISD::FXOR: return "X86ISD::FXOR";
9142 case X86ISD::FSRL: return "X86ISD::FSRL";
9143 case X86ISD::FILD: return "X86ISD::FILD";
9144 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
9145 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9146 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9147 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9148 case X86ISD::FLD: return "X86ISD::FLD";
9149 case X86ISD::FST: return "X86ISD::FST";
9150 case X86ISD::CALL: return "X86ISD::CALL";
9151 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
9152 case X86ISD::BT: return "X86ISD::BT";
9153 case X86ISD::CMP: return "X86ISD::CMP";
9154 case X86ISD::COMI: return "X86ISD::COMI";
9155 case X86ISD::UCOMI: return "X86ISD::UCOMI";
9156 case X86ISD::SETCC: return "X86ISD::SETCC";
9157 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
9158 case X86ISD::CMOV: return "X86ISD::CMOV";
9159 case X86ISD::BRCOND: return "X86ISD::BRCOND";
9160 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
9161 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
9162 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
9163 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
9164 case X86ISD::Wrapper: return "X86ISD::Wrapper";
9165 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
9166 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
9167 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
9168 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
9169 case X86ISD::PINSRB: return "X86ISD::PINSRB";
9170 case X86ISD::PINSRW: return "X86ISD::PINSRW";
9171 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
9172 case X86ISD::PANDN: return "X86ISD::PANDN";
9173 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
9174 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
9175 case X86ISD::PSIGND: return "X86ISD::PSIGND";
9176 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB";
9177 case X86ISD::FMAX: return "X86ISD::FMAX";
9178 case X86ISD::FMIN: return "X86ISD::FMIN";
9179 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
9180 case X86ISD::FRCP: return "X86ISD::FRCP";
9181 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
9182 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
9183 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
9184 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
9185 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
9186 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
9187 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
9188 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
9189 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
9190 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
9191 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
9192 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
9193 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
9194 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
9195 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
9196 case X86ISD::VSHL: return "X86ISD::VSHL";
9197 case X86ISD::VSRL: return "X86ISD::VSRL";
9198 case X86ISD::CMPPD: return "X86ISD::CMPPD";
9199 case X86ISD::CMPPS: return "X86ISD::CMPPS";
9200 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
9201 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
9202 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
9203 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
9204 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
9205 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
9206 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
9207 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
9208 case X86ISD::ADD: return "X86ISD::ADD";
9209 case X86ISD::SUB: return "X86ISD::SUB";
9210 case X86ISD::ADC: return "X86ISD::ADC";
9211 case X86ISD::SBB: return "X86ISD::SBB";
9212 case X86ISD::SMUL: return "X86ISD::SMUL";
9213 case X86ISD::UMUL: return "X86ISD::UMUL";
9214 case X86ISD::INC: return "X86ISD::INC";
9215 case X86ISD::DEC: return "X86ISD::DEC";
9216 case X86ISD::OR: return "X86ISD::OR";
9217 case X86ISD::XOR: return "X86ISD::XOR";
9218 case X86ISD::AND: return "X86ISD::AND";
9219 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
9220 case X86ISD::PTEST: return "X86ISD::PTEST";
9221 case X86ISD::TESTP: return "X86ISD::TESTP";
9222 case X86ISD::PALIGN: return "X86ISD::PALIGN";
9223 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
9224 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
9225 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
9226 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
9227 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
9228 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
9229 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
9230 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
9231 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
9232 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
9233 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
9234 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
9235 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
9236 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
9237 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
9238 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
9239 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
9240 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
9241 case X86ISD::MOVSD: return "X86ISD::MOVSD";
9242 case X86ISD::MOVSS: return "X86ISD::MOVSS";
9243 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
9244 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
9245 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
9246 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
9247 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
9248 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
9249 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
9250 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
9251 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
9252 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
9253 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
9254 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
9255 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9256 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
9257 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
9261 // isLegalAddressingMode - Return true if the addressing mode represented
9262 // by AM is legal for this target, for a load/store of the specified type.
9263 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9264 const Type *Ty) const {
9265 // X86 supports extremely general addressing modes.
9266 CodeModel::Model M = getTargetMachine().getCodeModel();
9267 Reloc::Model R = getTargetMachine().getRelocationModel();
9269 // X86 allows a sign-extended 32-bit immediate field as a displacement.
9270 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9275 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9277 // If a reference to this global requires an extra load, we can't fold it.
9278 if (isGlobalStubReference(GVFlags))
9281 // If BaseGV requires a register for the PIC base, we cannot also have a
9282 // BaseReg specified.
9283 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9286 // If lower 4G is not available, then we must use rip-relative addressing.
9287 if ((M != CodeModel::Small || R != Reloc::Static) &&
9288 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9298 // These scales always work.
9303 // These scales are formed with basereg+scalereg. Only accept if there is
9308 default: // Other stuff never works.
9316 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9317 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9319 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9320 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9321 if (NumBits1 <= NumBits2)
9326 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9327 if (!VT1.isInteger() || !VT2.isInteger())
9329 unsigned NumBits1 = VT1.getSizeInBits();
9330 unsigned NumBits2 = VT2.getSizeInBits();
9331 if (NumBits1 <= NumBits2)
9336 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9337 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9338 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9341 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9342 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9343 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9346 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9347 // i16 instructions are longer (0x66 prefix) and potentially slower.
9348 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9351 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9352 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9353 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9354 /// are assumed to be legal.
9356 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9358 // Very little shuffling can be done for 64-bit vectors right now.
9359 if (VT.getSizeInBits() == 64)
9360 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9362 // FIXME: pshufb, blends, shifts.
9363 return (VT.getVectorNumElements() == 2 ||
9364 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9365 isMOVLMask(M, VT) ||
9366 isSHUFPMask(M, VT) ||
9367 isPSHUFDMask(M, VT) ||
9368 isPSHUFHWMask(M, VT) ||
9369 isPSHUFLWMask(M, VT) ||
9370 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9371 isUNPCKLMask(M, VT) ||
9372 isUNPCKHMask(M, VT) ||
9373 isUNPCKL_v_undef_Mask(M, VT) ||
9374 isUNPCKH_v_undef_Mask(M, VT));
9378 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9380 unsigned NumElts = VT.getVectorNumElements();
9381 // FIXME: This collection of masks seems suspect.
9384 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9385 return (isMOVLMask(Mask, VT) ||
9386 isCommutedMOVLMask(Mask, VT, true) ||
9387 isSHUFPMask(Mask, VT) ||
9388 isCommutedSHUFPMask(Mask, VT));
9393 //===----------------------------------------------------------------------===//
9394 // X86 Scheduler Hooks
9395 //===----------------------------------------------------------------------===//
9397 // private utility function
9399 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9400 MachineBasicBlock *MBB,
9407 TargetRegisterClass *RC,
9408 bool invSrc) const {
9409 // For the atomic bitwise operator, we generate
9412 // ld t1 = [bitinstr.addr]
9413 // op t2 = t1, [bitinstr.val]
9415 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9417 // fallthrough -->nextMBB
9418 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9419 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9420 MachineFunction::iterator MBBIter = MBB;
9423 /// First build the CFG
9424 MachineFunction *F = MBB->getParent();
9425 MachineBasicBlock *thisMBB = MBB;
9426 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9427 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9428 F->insert(MBBIter, newMBB);
9429 F->insert(MBBIter, nextMBB);
9431 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9432 nextMBB->splice(nextMBB->begin(), thisMBB,
9433 llvm::next(MachineBasicBlock::iterator(bInstr)),
9435 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9437 // Update thisMBB to fall through to newMBB
9438 thisMBB->addSuccessor(newMBB);
9440 // newMBB jumps to itself and fall through to nextMBB
9441 newMBB->addSuccessor(nextMBB);
9442 newMBB->addSuccessor(newMBB);
9444 // Insert instructions into newMBB based on incoming instruction
9445 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9446 "unexpected number of operands");
9447 DebugLoc dl = bInstr->getDebugLoc();
9448 MachineOperand& destOper = bInstr->getOperand(0);
9449 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9450 int numArgs = bInstr->getNumOperands() - 1;
9451 for (int i=0; i < numArgs; ++i)
9452 argOpers[i] = &bInstr->getOperand(i+1);
9454 // x86 address has 4 operands: base, index, scale, and displacement
9455 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9456 int valArgIndx = lastAddrIndx + 1;
9458 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9459 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9460 for (int i=0; i <= lastAddrIndx; ++i)
9461 (*MIB).addOperand(*argOpers[i]);
9463 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9465 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9470 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9471 assert((argOpers[valArgIndx]->isReg() ||
9472 argOpers[valArgIndx]->isImm()) &&
9474 if (argOpers[valArgIndx]->isReg())
9475 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9477 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9479 (*MIB).addOperand(*argOpers[valArgIndx]);
9481 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9484 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9485 for (int i=0; i <= lastAddrIndx; ++i)
9486 (*MIB).addOperand(*argOpers[i]);
9488 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9489 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9490 bInstr->memoperands_end());
9492 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9496 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9498 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9502 // private utility function: 64 bit atomics on 32 bit host.
9504 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9505 MachineBasicBlock *MBB,
9510 bool invSrc) const {
9511 // For the atomic bitwise operator, we generate
9512 // thisMBB (instructions are in pairs, except cmpxchg8b)
9513 // ld t1,t2 = [bitinstr.addr]
9515 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9516 // op t5, t6 <- out1, out2, [bitinstr.val]
9517 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9518 // mov ECX, EBX <- t5, t6
9519 // mov EAX, EDX <- t1, t2
9520 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9521 // mov t3, t4 <- EAX, EDX
9523 // result in out1, out2
9524 // fallthrough -->nextMBB
9526 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9527 const unsigned LoadOpc = X86::MOV32rm;
9528 const unsigned NotOpc = X86::NOT32r;
9529 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9530 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9531 MachineFunction::iterator MBBIter = MBB;
9534 /// First build the CFG
9535 MachineFunction *F = MBB->getParent();
9536 MachineBasicBlock *thisMBB = MBB;
9537 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9538 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9539 F->insert(MBBIter, newMBB);
9540 F->insert(MBBIter, nextMBB);
9542 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9543 nextMBB->splice(nextMBB->begin(), thisMBB,
9544 llvm::next(MachineBasicBlock::iterator(bInstr)),
9546 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9548 // Update thisMBB to fall through to newMBB
9549 thisMBB->addSuccessor(newMBB);
9551 // newMBB jumps to itself and fall through to nextMBB
9552 newMBB->addSuccessor(nextMBB);
9553 newMBB->addSuccessor(newMBB);
9555 DebugLoc dl = bInstr->getDebugLoc();
9556 // Insert instructions into newMBB based on incoming instruction
9557 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9558 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9559 "unexpected number of operands");
9560 MachineOperand& dest1Oper = bInstr->getOperand(0);
9561 MachineOperand& dest2Oper = bInstr->getOperand(1);
9562 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9563 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9564 argOpers[i] = &bInstr->getOperand(i+2);
9566 // We use some of the operands multiple times, so conservatively just
9567 // clear any kill flags that might be present.
9568 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9569 argOpers[i]->setIsKill(false);
9572 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9573 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9575 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9576 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9577 for (int i=0; i <= lastAddrIndx; ++i)
9578 (*MIB).addOperand(*argOpers[i]);
9579 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9580 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9581 // add 4 to displacement.
9582 for (int i=0; i <= lastAddrIndx-2; ++i)
9583 (*MIB).addOperand(*argOpers[i]);
9584 MachineOperand newOp3 = *(argOpers[3]);
9586 newOp3.setImm(newOp3.getImm()+4);
9588 newOp3.setOffset(newOp3.getOffset()+4);
9589 (*MIB).addOperand(newOp3);
9590 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9592 // t3/4 are defined later, at the bottom of the loop
9593 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9594 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9595 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9596 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9597 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9598 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9600 // The subsequent operations should be using the destination registers of
9601 //the PHI instructions.
9603 t1 = F->getRegInfo().createVirtualRegister(RC);
9604 t2 = F->getRegInfo().createVirtualRegister(RC);
9605 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9606 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9608 t1 = dest1Oper.getReg();
9609 t2 = dest2Oper.getReg();
9612 int valArgIndx = lastAddrIndx + 1;
9613 assert((argOpers[valArgIndx]->isReg() ||
9614 argOpers[valArgIndx]->isImm()) &&
9616 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9617 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9618 if (argOpers[valArgIndx]->isReg())
9619 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9621 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9622 if (regOpcL != X86::MOV32rr)
9624 (*MIB).addOperand(*argOpers[valArgIndx]);
9625 assert(argOpers[valArgIndx + 1]->isReg() ==
9626 argOpers[valArgIndx]->isReg());
9627 assert(argOpers[valArgIndx + 1]->isImm() ==
9628 argOpers[valArgIndx]->isImm());
9629 if (argOpers[valArgIndx + 1]->isReg())
9630 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9632 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9633 if (regOpcH != X86::MOV32rr)
9635 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9637 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9639 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9642 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9644 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9647 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9648 for (int i=0; i <= lastAddrIndx; ++i)
9649 (*MIB).addOperand(*argOpers[i]);
9651 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9652 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9653 bInstr->memoperands_end());
9655 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9656 MIB.addReg(X86::EAX);
9657 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9658 MIB.addReg(X86::EDX);
9661 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9663 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9667 // private utility function
9669 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9670 MachineBasicBlock *MBB,
9671 unsigned cmovOpc) const {
9672 // For the atomic min/max operator, we generate
9675 // ld t1 = [min/max.addr]
9676 // mov t2 = [min/max.val]
9678 // cmov[cond] t2 = t1
9680 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9682 // fallthrough -->nextMBB
9684 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9685 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9686 MachineFunction::iterator MBBIter = MBB;
9689 /// First build the CFG
9690 MachineFunction *F = MBB->getParent();
9691 MachineBasicBlock *thisMBB = MBB;
9692 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9693 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9694 F->insert(MBBIter, newMBB);
9695 F->insert(MBBIter, nextMBB);
9697 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9698 nextMBB->splice(nextMBB->begin(), thisMBB,
9699 llvm::next(MachineBasicBlock::iterator(mInstr)),
9701 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9703 // Update thisMBB to fall through to newMBB
9704 thisMBB->addSuccessor(newMBB);
9706 // newMBB jumps to newMBB and fall through to nextMBB
9707 newMBB->addSuccessor(nextMBB);
9708 newMBB->addSuccessor(newMBB);
9710 DebugLoc dl = mInstr->getDebugLoc();
9711 // Insert instructions into newMBB based on incoming instruction
9712 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9713 "unexpected number of operands");
9714 MachineOperand& destOper = mInstr->getOperand(0);
9715 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9716 int numArgs = mInstr->getNumOperands() - 1;
9717 for (int i=0; i < numArgs; ++i)
9718 argOpers[i] = &mInstr->getOperand(i+1);
9720 // x86 address has 4 operands: base, index, scale, and displacement
9721 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9722 int valArgIndx = lastAddrIndx + 1;
9724 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9725 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9726 for (int i=0; i <= lastAddrIndx; ++i)
9727 (*MIB).addOperand(*argOpers[i]);
9729 // We only support register and immediate values
9730 assert((argOpers[valArgIndx]->isReg() ||
9731 argOpers[valArgIndx]->isImm()) &&
9734 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9735 if (argOpers[valArgIndx]->isReg())
9736 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9738 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9739 (*MIB).addOperand(*argOpers[valArgIndx]);
9741 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9744 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9749 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9750 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9754 // Cmp and exchange if none has modified the memory location
9755 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9756 for (int i=0; i <= lastAddrIndx; ++i)
9757 (*MIB).addOperand(*argOpers[i]);
9759 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9760 (*MIB).setMemRefs(mInstr->memoperands_begin(),
9761 mInstr->memoperands_end());
9763 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9764 MIB.addReg(X86::EAX);
9767 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9769 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
9773 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9774 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9777 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9778 unsigned numArgs, bool memArg) const {
9779 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9780 "Target must have SSE4.2 or AVX features enabled");
9782 DebugLoc dl = MI->getDebugLoc();
9783 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9785 if (!Subtarget->hasAVX()) {
9787 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9789 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9792 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9794 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9797 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9798 for (unsigned i = 0; i < numArgs; ++i) {
9799 MachineOperand &Op = MI->getOperand(i+1);
9800 if (!(Op.isReg() && Op.isImplicit()))
9803 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9806 MI->eraseFromParent();
9811 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9812 DebugLoc dl = MI->getDebugLoc();
9813 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9815 // Address into RAX/EAX, other two args into ECX, EDX.
9816 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9817 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9818 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9819 for (int i = 0; i < X86::AddrNumOperands; ++i)
9820 MIB.addOperand(MI->getOperand(i));
9822 unsigned ValOps = X86::AddrNumOperands;
9823 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9824 .addReg(MI->getOperand(ValOps).getReg());
9825 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9826 .addReg(MI->getOperand(ValOps+1).getReg());
9828 // The instruction doesn't actually take any operands though.
9829 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9831 MI->eraseFromParent(); // The pseudo is gone now.
9836 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9837 DebugLoc dl = MI->getDebugLoc();
9838 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9840 // First arg in ECX, the second in EAX.
9841 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9842 .addReg(MI->getOperand(0).getReg());
9843 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9844 .addReg(MI->getOperand(1).getReg());
9846 // The instruction doesn't actually take any operands though.
9847 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9849 MI->eraseFromParent(); // The pseudo is gone now.
9854 X86TargetLowering::EmitVAARG64WithCustomInserter(
9856 MachineBasicBlock *MBB) const {
9857 // Emit va_arg instruction on X86-64.
9859 // Operands to this pseudo-instruction:
9860 // 0 ) Output : destination address (reg)
9861 // 1-5) Input : va_list address (addr, i64mem)
9862 // 6 ) ArgSize : Size (in bytes) of vararg type
9863 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
9864 // 8 ) Align : Alignment of type
9865 // 9 ) EFLAGS (implicit-def)
9867 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
9868 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
9870 unsigned DestReg = MI->getOperand(0).getReg();
9871 MachineOperand &Base = MI->getOperand(1);
9872 MachineOperand &Scale = MI->getOperand(2);
9873 MachineOperand &Index = MI->getOperand(3);
9874 MachineOperand &Disp = MI->getOperand(4);
9875 MachineOperand &Segment = MI->getOperand(5);
9876 unsigned ArgSize = MI->getOperand(6).getImm();
9877 unsigned ArgMode = MI->getOperand(7).getImm();
9878 unsigned Align = MI->getOperand(8).getImm();
9881 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
9882 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
9883 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
9885 // Machine Information
9886 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9887 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9888 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
9889 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
9890 DebugLoc DL = MI->getDebugLoc();
9895 // i64 overflow_area (address)
9896 // i64 reg_save_area (address)
9898 // sizeof(va_list) = 24
9899 // alignment(va_list) = 8
9901 unsigned TotalNumIntRegs = 6;
9902 unsigned TotalNumXMMRegs = 8;
9903 bool UseGPOffset = (ArgMode == 1);
9904 bool UseFPOffset = (ArgMode == 2);
9905 unsigned MaxOffset = TotalNumIntRegs * 8 +
9906 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
9908 /* Align ArgSize to a multiple of 8 */
9909 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
9910 bool NeedsAlign = (Align > 8);
9912 MachineBasicBlock *thisMBB = MBB;
9913 MachineBasicBlock *overflowMBB;
9914 MachineBasicBlock *offsetMBB;
9915 MachineBasicBlock *endMBB;
9917 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
9918 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
9919 unsigned OffsetReg = 0;
9921 if (!UseGPOffset && !UseFPOffset) {
9922 // If we only pull from the overflow region, we don't create a branch.
9923 // We don't need to alter control flow.
9924 OffsetDestReg = 0; // unused
9925 OverflowDestReg = DestReg;
9928 overflowMBB = thisMBB;
9931 // First emit code to check if gp_offset (or fp_offset) is below the bound.
9932 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
9933 // If not, pull from overflow_area. (branch to overflowMBB)
9938 // offsetMBB overflowMBB
9943 // Registers for the PHI in endMBB
9944 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
9945 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
9947 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9948 MachineFunction *MF = MBB->getParent();
9949 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9950 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9951 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9953 MachineFunction::iterator MBBIter = MBB;
9956 // Insert the new basic blocks
9957 MF->insert(MBBIter, offsetMBB);
9958 MF->insert(MBBIter, overflowMBB);
9959 MF->insert(MBBIter, endMBB);
9961 // Transfer the remainder of MBB and its successor edges to endMBB.
9962 endMBB->splice(endMBB->begin(), thisMBB,
9963 llvm::next(MachineBasicBlock::iterator(MI)),
9965 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9967 // Make offsetMBB and overflowMBB successors of thisMBB
9968 thisMBB->addSuccessor(offsetMBB);
9969 thisMBB->addSuccessor(overflowMBB);
9971 // endMBB is a successor of both offsetMBB and overflowMBB
9972 offsetMBB->addSuccessor(endMBB);
9973 overflowMBB->addSuccessor(endMBB);
9975 // Load the offset value into a register
9976 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9977 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
9981 .addDisp(Disp, UseFPOffset ? 4 : 0)
9982 .addOperand(Segment)
9983 .setMemRefs(MMOBegin, MMOEnd);
9985 // Check if there is enough room left to pull this argument.
9986 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
9988 .addImm(MaxOffset + 8 - ArgSizeA8);
9990 // Branch to "overflowMBB" if offset >= max
9991 // Fall through to "offsetMBB" otherwise
9992 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
9993 .addMBB(overflowMBB);
9996 // In offsetMBB, emit code to use the reg_save_area.
9998 assert(OffsetReg != 0);
10000 // Read the reg_save_area address.
10001 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10002 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10007 .addOperand(Segment)
10008 .setMemRefs(MMOBegin, MMOEnd);
10010 // Zero-extend the offset
10011 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10012 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10015 .addImm(X86::sub_32bit);
10017 // Add the offset to the reg_save_area to get the final address.
10018 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10019 .addReg(OffsetReg64)
10020 .addReg(RegSaveReg);
10022 // Compute the offset for the next argument
10023 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10024 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10026 .addImm(UseFPOffset ? 16 : 8);
10028 // Store it back into the va_list.
10029 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10033 .addDisp(Disp, UseFPOffset ? 4 : 0)
10034 .addOperand(Segment)
10035 .addReg(NextOffsetReg)
10036 .setMemRefs(MMOBegin, MMOEnd);
10039 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10044 // Emit code to use overflow area
10047 // Load the overflow_area address into a register.
10048 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10049 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10054 .addOperand(Segment)
10055 .setMemRefs(MMOBegin, MMOEnd);
10057 // If we need to align it, do so. Otherwise, just copy the address
10058 // to OverflowDestReg.
10060 // Align the overflow address
10061 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10062 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10064 // aligned_addr = (addr + (align-1)) & ~(align-1)
10065 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10066 .addReg(OverflowAddrReg)
10069 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10071 .addImm(~(uint64_t)(Align-1));
10073 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10074 .addReg(OverflowAddrReg);
10077 // Compute the next overflow address after this argument.
10078 // (the overflow address should be kept 8-byte aligned)
10079 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10080 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10081 .addReg(OverflowDestReg)
10082 .addImm(ArgSizeA8);
10084 // Store the new overflow address.
10085 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10090 .addOperand(Segment)
10091 .addReg(NextAddrReg)
10092 .setMemRefs(MMOBegin, MMOEnd);
10094 // If we branched, emit the PHI to the front of endMBB.
10096 BuildMI(*endMBB, endMBB->begin(), DL,
10097 TII->get(X86::PHI), DestReg)
10098 .addReg(OffsetDestReg).addMBB(offsetMBB)
10099 .addReg(OverflowDestReg).addMBB(overflowMBB);
10102 // Erase the pseudo instruction
10103 MI->eraseFromParent();
10108 MachineBasicBlock *
10109 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10111 MachineBasicBlock *MBB) const {
10112 // Emit code to save XMM registers to the stack. The ABI says that the
10113 // number of registers to save is given in %al, so it's theoretically
10114 // possible to do an indirect jump trick to avoid saving all of them,
10115 // however this code takes a simpler approach and just executes all
10116 // of the stores if %al is non-zero. It's less code, and it's probably
10117 // easier on the hardware branch predictor, and stores aren't all that
10118 // expensive anyway.
10120 // Create the new basic blocks. One block contains all the XMM stores,
10121 // and one block is the final destination regardless of whether any
10122 // stores were performed.
10123 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10124 MachineFunction *F = MBB->getParent();
10125 MachineFunction::iterator MBBIter = MBB;
10127 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10128 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10129 F->insert(MBBIter, XMMSaveMBB);
10130 F->insert(MBBIter, EndMBB);
10132 // Transfer the remainder of MBB and its successor edges to EndMBB.
10133 EndMBB->splice(EndMBB->begin(), MBB,
10134 llvm::next(MachineBasicBlock::iterator(MI)),
10136 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10138 // The original block will now fall through to the XMM save block.
10139 MBB->addSuccessor(XMMSaveMBB);
10140 // The XMMSaveMBB will fall through to the end block.
10141 XMMSaveMBB->addSuccessor(EndMBB);
10143 // Now add the instructions.
10144 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10145 DebugLoc DL = MI->getDebugLoc();
10147 unsigned CountReg = MI->getOperand(0).getReg();
10148 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10149 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10151 if (!Subtarget->isTargetWin64()) {
10152 // If %al is 0, branch around the XMM save block.
10153 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10154 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10155 MBB->addSuccessor(EndMBB);
10158 // In the XMM save block, save all the XMM argument registers.
10159 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10160 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10161 MachineMemOperand *MMO =
10162 F->getMachineMemOperand(
10163 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10164 MachineMemOperand::MOStore,
10165 /*Size=*/16, /*Align=*/16);
10166 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10167 .addFrameIndex(RegSaveFrameIndex)
10168 .addImm(/*Scale=*/1)
10169 .addReg(/*IndexReg=*/0)
10170 .addImm(/*Disp=*/Offset)
10171 .addReg(/*Segment=*/0)
10172 .addReg(MI->getOperand(i).getReg())
10173 .addMemOperand(MMO);
10176 MI->eraseFromParent(); // The pseudo instruction is gone now.
10181 MachineBasicBlock *
10182 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10183 MachineBasicBlock *BB) const {
10184 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10185 DebugLoc DL = MI->getDebugLoc();
10187 // To "insert" a SELECT_CC instruction, we actually have to insert the
10188 // diamond control-flow pattern. The incoming instruction knows the
10189 // destination vreg to set, the condition code register to branch on, the
10190 // true/false values to select between, and a branch opcode to use.
10191 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10192 MachineFunction::iterator It = BB;
10198 // cmpTY ccX, r1, r2
10200 // fallthrough --> copy0MBB
10201 MachineBasicBlock *thisMBB = BB;
10202 MachineFunction *F = BB->getParent();
10203 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10204 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10205 F->insert(It, copy0MBB);
10206 F->insert(It, sinkMBB);
10208 // If the EFLAGS register isn't dead in the terminator, then claim that it's
10209 // live into the sink and copy blocks.
10210 const MachineFunction *MF = BB->getParent();
10211 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10212 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10214 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10215 const MachineOperand &MO = MI->getOperand(I);
10216 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10217 unsigned Reg = MO.getReg();
10218 if (Reg != X86::EFLAGS) continue;
10219 copy0MBB->addLiveIn(Reg);
10220 sinkMBB->addLiveIn(Reg);
10223 // Transfer the remainder of BB and its successor edges to sinkMBB.
10224 sinkMBB->splice(sinkMBB->begin(), BB,
10225 llvm::next(MachineBasicBlock::iterator(MI)),
10227 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10229 // Add the true and fallthrough blocks as its successors.
10230 BB->addSuccessor(copy0MBB);
10231 BB->addSuccessor(sinkMBB);
10233 // Create the conditional branch instruction.
10235 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10236 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10239 // %FalseValue = ...
10240 // # fallthrough to sinkMBB
10241 copy0MBB->addSuccessor(sinkMBB);
10244 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10246 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10247 TII->get(X86::PHI), MI->getOperand(0).getReg())
10248 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10249 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10251 MI->eraseFromParent(); // The pseudo instruction is gone now.
10255 MachineBasicBlock *
10256 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10257 MachineBasicBlock *BB) const {
10258 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10259 DebugLoc DL = MI->getDebugLoc();
10261 // The lowering is pretty easy: we're just emitting the call to _alloca. The
10262 // non-trivial part is impdef of ESP.
10263 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
10266 const char *StackProbeSymbol =
10267 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10269 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10270 .addExternalSymbol(StackProbeSymbol)
10271 .addReg(X86::EAX, RegState::Implicit)
10272 .addReg(X86::ESP, RegState::Implicit)
10273 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10274 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10275 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10277 MI->eraseFromParent(); // The pseudo instruction is gone now.
10281 MachineBasicBlock *
10282 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10283 MachineBasicBlock *BB) const {
10284 // This is pretty easy. We're taking the value that we received from
10285 // our load from the relocation, sticking it in either RDI (x86-64)
10286 // or EAX and doing an indirect call. The return value will then
10287 // be in the normal return register.
10288 const X86InstrInfo *TII
10289 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10290 DebugLoc DL = MI->getDebugLoc();
10291 MachineFunction *F = BB->getParent();
10293 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10294 assert(MI->getOperand(3).isGlobal() && "This should be a global");
10296 if (Subtarget->is64Bit()) {
10297 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10298 TII->get(X86::MOV64rm), X86::RDI)
10300 .addImm(0).addReg(0)
10301 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10302 MI->getOperand(3).getTargetFlags())
10304 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10305 addDirectMem(MIB, X86::RDI);
10306 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10307 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10308 TII->get(X86::MOV32rm), X86::EAX)
10310 .addImm(0).addReg(0)
10311 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10312 MI->getOperand(3).getTargetFlags())
10314 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10315 addDirectMem(MIB, X86::EAX);
10317 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10318 TII->get(X86::MOV32rm), X86::EAX)
10319 .addReg(TII->getGlobalBaseReg(F))
10320 .addImm(0).addReg(0)
10321 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10322 MI->getOperand(3).getTargetFlags())
10324 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10325 addDirectMem(MIB, X86::EAX);
10328 MI->eraseFromParent(); // The pseudo instruction is gone now.
10332 MachineBasicBlock *
10333 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10334 MachineBasicBlock *BB) const {
10335 switch (MI->getOpcode()) {
10336 default: assert(false && "Unexpected instr type to insert");
10337 case X86::TAILJMPd64:
10338 case X86::TAILJMPr64:
10339 case X86::TAILJMPm64:
10340 assert(!"TAILJMP64 would not be touched here.");
10341 case X86::TCRETURNdi64:
10342 case X86::TCRETURNri64:
10343 case X86::TCRETURNmi64:
10344 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10345 // On AMD64, additional defs should be added before register allocation.
10346 if (!Subtarget->isTargetWin64()) {
10347 MI->addRegisterDefined(X86::RSI);
10348 MI->addRegisterDefined(X86::RDI);
10349 MI->addRegisterDefined(X86::XMM6);
10350 MI->addRegisterDefined(X86::XMM7);
10351 MI->addRegisterDefined(X86::XMM8);
10352 MI->addRegisterDefined(X86::XMM9);
10353 MI->addRegisterDefined(X86::XMM10);
10354 MI->addRegisterDefined(X86::XMM11);
10355 MI->addRegisterDefined(X86::XMM12);
10356 MI->addRegisterDefined(X86::XMM13);
10357 MI->addRegisterDefined(X86::XMM14);
10358 MI->addRegisterDefined(X86::XMM15);
10361 case X86::WIN_ALLOCA:
10362 return EmitLoweredWinAlloca(MI, BB);
10363 case X86::TLSCall_32:
10364 case X86::TLSCall_64:
10365 return EmitLoweredTLSCall(MI, BB);
10366 case X86::CMOV_GR8:
10367 case X86::CMOV_FR32:
10368 case X86::CMOV_FR64:
10369 case X86::CMOV_V4F32:
10370 case X86::CMOV_V2F64:
10371 case X86::CMOV_V2I64:
10372 case X86::CMOV_GR16:
10373 case X86::CMOV_GR32:
10374 case X86::CMOV_RFP32:
10375 case X86::CMOV_RFP64:
10376 case X86::CMOV_RFP80:
10377 return EmitLoweredSelect(MI, BB);
10379 case X86::FP32_TO_INT16_IN_MEM:
10380 case X86::FP32_TO_INT32_IN_MEM:
10381 case X86::FP32_TO_INT64_IN_MEM:
10382 case X86::FP64_TO_INT16_IN_MEM:
10383 case X86::FP64_TO_INT32_IN_MEM:
10384 case X86::FP64_TO_INT64_IN_MEM:
10385 case X86::FP80_TO_INT16_IN_MEM:
10386 case X86::FP80_TO_INT32_IN_MEM:
10387 case X86::FP80_TO_INT64_IN_MEM: {
10388 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10389 DebugLoc DL = MI->getDebugLoc();
10391 // Change the floating point control register to use "round towards zero"
10392 // mode when truncating to an integer value.
10393 MachineFunction *F = BB->getParent();
10394 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10395 addFrameReference(BuildMI(*BB, MI, DL,
10396 TII->get(X86::FNSTCW16m)), CWFrameIdx);
10398 // Load the old value of the high byte of the control word...
10400 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10401 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10404 // Set the high part to be round to zero...
10405 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10408 // Reload the modified control word now...
10409 addFrameReference(BuildMI(*BB, MI, DL,
10410 TII->get(X86::FLDCW16m)), CWFrameIdx);
10412 // Restore the memory image of control word to original value
10413 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10416 // Get the X86 opcode to use.
10418 switch (MI->getOpcode()) {
10419 default: llvm_unreachable("illegal opcode!");
10420 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10421 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10422 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10423 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10424 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10425 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10426 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10427 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10428 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10432 MachineOperand &Op = MI->getOperand(0);
10434 AM.BaseType = X86AddressMode::RegBase;
10435 AM.Base.Reg = Op.getReg();
10437 AM.BaseType = X86AddressMode::FrameIndexBase;
10438 AM.Base.FrameIndex = Op.getIndex();
10440 Op = MI->getOperand(1);
10442 AM.Scale = Op.getImm();
10443 Op = MI->getOperand(2);
10445 AM.IndexReg = Op.getImm();
10446 Op = MI->getOperand(3);
10447 if (Op.isGlobal()) {
10448 AM.GV = Op.getGlobal();
10450 AM.Disp = Op.getImm();
10452 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10453 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10455 // Reload the original control word now.
10456 addFrameReference(BuildMI(*BB, MI, DL,
10457 TII->get(X86::FLDCW16m)), CWFrameIdx);
10459 MI->eraseFromParent(); // The pseudo instruction is gone now.
10462 // String/text processing lowering.
10463 case X86::PCMPISTRM128REG:
10464 case X86::VPCMPISTRM128REG:
10465 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10466 case X86::PCMPISTRM128MEM:
10467 case X86::VPCMPISTRM128MEM:
10468 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10469 case X86::PCMPESTRM128REG:
10470 case X86::VPCMPESTRM128REG:
10471 return EmitPCMP(MI, BB, 5, false /* in mem */);
10472 case X86::PCMPESTRM128MEM:
10473 case X86::VPCMPESTRM128MEM:
10474 return EmitPCMP(MI, BB, 5, true /* in mem */);
10476 // Thread synchronization.
10478 return EmitMonitor(MI, BB);
10480 return EmitMwait(MI, BB);
10482 // Atomic Lowering.
10483 case X86::ATOMAND32:
10484 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10485 X86::AND32ri, X86::MOV32rm,
10487 X86::NOT32r, X86::EAX,
10488 X86::GR32RegisterClass);
10489 case X86::ATOMOR32:
10490 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10491 X86::OR32ri, X86::MOV32rm,
10493 X86::NOT32r, X86::EAX,
10494 X86::GR32RegisterClass);
10495 case X86::ATOMXOR32:
10496 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10497 X86::XOR32ri, X86::MOV32rm,
10499 X86::NOT32r, X86::EAX,
10500 X86::GR32RegisterClass);
10501 case X86::ATOMNAND32:
10502 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10503 X86::AND32ri, X86::MOV32rm,
10505 X86::NOT32r, X86::EAX,
10506 X86::GR32RegisterClass, true);
10507 case X86::ATOMMIN32:
10508 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10509 case X86::ATOMMAX32:
10510 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10511 case X86::ATOMUMIN32:
10512 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10513 case X86::ATOMUMAX32:
10514 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10516 case X86::ATOMAND16:
10517 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10518 X86::AND16ri, X86::MOV16rm,
10520 X86::NOT16r, X86::AX,
10521 X86::GR16RegisterClass);
10522 case X86::ATOMOR16:
10523 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10524 X86::OR16ri, X86::MOV16rm,
10526 X86::NOT16r, X86::AX,
10527 X86::GR16RegisterClass);
10528 case X86::ATOMXOR16:
10529 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10530 X86::XOR16ri, X86::MOV16rm,
10532 X86::NOT16r, X86::AX,
10533 X86::GR16RegisterClass);
10534 case X86::ATOMNAND16:
10535 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10536 X86::AND16ri, X86::MOV16rm,
10538 X86::NOT16r, X86::AX,
10539 X86::GR16RegisterClass, true);
10540 case X86::ATOMMIN16:
10541 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10542 case X86::ATOMMAX16:
10543 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10544 case X86::ATOMUMIN16:
10545 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10546 case X86::ATOMUMAX16:
10547 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10549 case X86::ATOMAND8:
10550 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10551 X86::AND8ri, X86::MOV8rm,
10553 X86::NOT8r, X86::AL,
10554 X86::GR8RegisterClass);
10556 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10557 X86::OR8ri, X86::MOV8rm,
10559 X86::NOT8r, X86::AL,
10560 X86::GR8RegisterClass);
10561 case X86::ATOMXOR8:
10562 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10563 X86::XOR8ri, X86::MOV8rm,
10565 X86::NOT8r, X86::AL,
10566 X86::GR8RegisterClass);
10567 case X86::ATOMNAND8:
10568 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10569 X86::AND8ri, X86::MOV8rm,
10571 X86::NOT8r, X86::AL,
10572 X86::GR8RegisterClass, true);
10573 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10574 // This group is for 64-bit host.
10575 case X86::ATOMAND64:
10576 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10577 X86::AND64ri32, X86::MOV64rm,
10579 X86::NOT64r, X86::RAX,
10580 X86::GR64RegisterClass);
10581 case X86::ATOMOR64:
10582 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10583 X86::OR64ri32, X86::MOV64rm,
10585 X86::NOT64r, X86::RAX,
10586 X86::GR64RegisterClass);
10587 case X86::ATOMXOR64:
10588 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10589 X86::XOR64ri32, X86::MOV64rm,
10591 X86::NOT64r, X86::RAX,
10592 X86::GR64RegisterClass);
10593 case X86::ATOMNAND64:
10594 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10595 X86::AND64ri32, X86::MOV64rm,
10597 X86::NOT64r, X86::RAX,
10598 X86::GR64RegisterClass, true);
10599 case X86::ATOMMIN64:
10600 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10601 case X86::ATOMMAX64:
10602 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10603 case X86::ATOMUMIN64:
10604 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10605 case X86::ATOMUMAX64:
10606 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10608 // This group does 64-bit operations on a 32-bit host.
10609 case X86::ATOMAND6432:
10610 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10611 X86::AND32rr, X86::AND32rr,
10612 X86::AND32ri, X86::AND32ri,
10614 case X86::ATOMOR6432:
10615 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10616 X86::OR32rr, X86::OR32rr,
10617 X86::OR32ri, X86::OR32ri,
10619 case X86::ATOMXOR6432:
10620 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10621 X86::XOR32rr, X86::XOR32rr,
10622 X86::XOR32ri, X86::XOR32ri,
10624 case X86::ATOMNAND6432:
10625 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10626 X86::AND32rr, X86::AND32rr,
10627 X86::AND32ri, X86::AND32ri,
10629 case X86::ATOMADD6432:
10630 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10631 X86::ADD32rr, X86::ADC32rr,
10632 X86::ADD32ri, X86::ADC32ri,
10634 case X86::ATOMSUB6432:
10635 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10636 X86::SUB32rr, X86::SBB32rr,
10637 X86::SUB32ri, X86::SBB32ri,
10639 case X86::ATOMSWAP6432:
10640 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10641 X86::MOV32rr, X86::MOV32rr,
10642 X86::MOV32ri, X86::MOV32ri,
10644 case X86::VASTART_SAVE_XMM_REGS:
10645 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10647 case X86::VAARG_64:
10648 return EmitVAARG64WithCustomInserter(MI, BB);
10652 //===----------------------------------------------------------------------===//
10653 // X86 Optimization Hooks
10654 //===----------------------------------------------------------------------===//
10656 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10660 const SelectionDAG &DAG,
10661 unsigned Depth) const {
10662 unsigned Opc = Op.getOpcode();
10663 assert((Opc >= ISD::BUILTIN_OP_END ||
10664 Opc == ISD::INTRINSIC_WO_CHAIN ||
10665 Opc == ISD::INTRINSIC_W_CHAIN ||
10666 Opc == ISD::INTRINSIC_VOID) &&
10667 "Should use MaskedValueIsZero if you don't know whether Op"
10668 " is a target node!");
10670 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
10684 // These nodes' second result is a boolean.
10685 if (Op.getResNo() == 0)
10688 case X86ISD::SETCC:
10689 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10690 Mask.getBitWidth() - 1);
10695 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10696 unsigned Depth) const {
10697 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10698 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10699 return Op.getValueType().getScalarType().getSizeInBits();
10705 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10706 /// node is a GlobalAddress + offset.
10707 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10708 const GlobalValue* &GA,
10709 int64_t &Offset) const {
10710 if (N->getOpcode() == X86ISD::Wrapper) {
10711 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10712 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10713 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10717 return TargetLowering::isGAPlusOffset(N, GA, Offset);
10720 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10721 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10722 /// if the load addresses are consecutive, non-overlapping, and in the right
10724 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10725 TargetLowering::DAGCombinerInfo &DCI) {
10726 DebugLoc dl = N->getDebugLoc();
10727 EVT VT = N->getValueType(0);
10729 if (VT.getSizeInBits() != 128)
10732 // Don't create instructions with illegal types after legalize types has run.
10733 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10734 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
10737 SmallVector<SDValue, 16> Elts;
10738 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10739 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10741 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10744 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10745 /// generation and convert it from being a bunch of shuffles and extracts
10746 /// to a simple store and scalar loads to extract the elements.
10747 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10748 const TargetLowering &TLI) {
10749 SDValue InputVector = N->getOperand(0);
10751 // Only operate on vectors of 4 elements, where the alternative shuffling
10752 // gets to be more expensive.
10753 if (InputVector.getValueType() != MVT::v4i32)
10756 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10757 // single use which is a sign-extend or zero-extend, and all elements are
10759 SmallVector<SDNode *, 4> Uses;
10760 unsigned ExtractedElements = 0;
10761 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10762 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10763 if (UI.getUse().getResNo() != InputVector.getResNo())
10766 SDNode *Extract = *UI;
10767 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10770 if (Extract->getValueType(0) != MVT::i32)
10772 if (!Extract->hasOneUse())
10774 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10775 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10777 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10780 // Record which element was extracted.
10781 ExtractedElements |=
10782 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10784 Uses.push_back(Extract);
10787 // If not all the elements were used, this may not be worthwhile.
10788 if (ExtractedElements != 15)
10791 // Ok, we've now decided to do the transformation.
10792 DebugLoc dl = InputVector.getDebugLoc();
10794 // Store the value to a temporary stack slot.
10795 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10796 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10797 MachinePointerInfo(), false, false, 0);
10799 // Replace each use (extract) with a load of the appropriate element.
10800 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10801 UE = Uses.end(); UI != UE; ++UI) {
10802 SDNode *Extract = *UI;
10804 // Compute the element's address.
10805 SDValue Idx = Extract->getOperand(1);
10807 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10808 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10809 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10811 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10812 StackPtr, OffsetVal);
10814 // Load the scalar.
10815 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10816 ScalarAddr, MachinePointerInfo(),
10819 // Replace the exact with the load.
10820 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10823 // The replacement was made in place; don't return anything.
10827 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10828 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10829 const X86Subtarget *Subtarget) {
10830 DebugLoc DL = N->getDebugLoc();
10831 SDValue Cond = N->getOperand(0);
10832 // Get the LHS/RHS of the select.
10833 SDValue LHS = N->getOperand(1);
10834 SDValue RHS = N->getOperand(2);
10836 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10837 // instructions match the semantics of the common C idiom x<y?x:y but not
10838 // x<=y?x:y, because of how they handle negative zero (which can be
10839 // ignored in unsafe-math mode).
10840 if (Subtarget->hasSSE2() &&
10841 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10842 Cond.getOpcode() == ISD::SETCC) {
10843 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10845 unsigned Opcode = 0;
10846 // Check for x CC y ? x : y.
10847 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10848 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10852 // Converting this to a min would handle NaNs incorrectly, and swapping
10853 // the operands would cause it to handle comparisons between positive
10854 // and negative zero incorrectly.
10855 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10856 if (!UnsafeFPMath &&
10857 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10859 std::swap(LHS, RHS);
10861 Opcode = X86ISD::FMIN;
10864 // Converting this to a min would handle comparisons between positive
10865 // and negative zero incorrectly.
10866 if (!UnsafeFPMath &&
10867 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10869 Opcode = X86ISD::FMIN;
10872 // Converting this to a min would handle both negative zeros and NaNs
10873 // incorrectly, but we can swap the operands to fix both.
10874 std::swap(LHS, RHS);
10878 Opcode = X86ISD::FMIN;
10882 // Converting this to a max would handle comparisons between positive
10883 // and negative zero incorrectly.
10884 if (!UnsafeFPMath &&
10885 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10887 Opcode = X86ISD::FMAX;
10890 // Converting this to a max would handle NaNs incorrectly, and swapping
10891 // the operands would cause it to handle comparisons between positive
10892 // and negative zero incorrectly.
10893 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10894 if (!UnsafeFPMath &&
10895 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10897 std::swap(LHS, RHS);
10899 Opcode = X86ISD::FMAX;
10902 // Converting this to a max would handle both negative zeros and NaNs
10903 // incorrectly, but we can swap the operands to fix both.
10904 std::swap(LHS, RHS);
10908 Opcode = X86ISD::FMAX;
10911 // Check for x CC y ? y : x -- a min/max with reversed arms.
10912 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10913 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10917 // Converting this to a min would handle comparisons between positive
10918 // and negative zero incorrectly, and swapping the operands would
10919 // cause it to handle NaNs incorrectly.
10920 if (!UnsafeFPMath &&
10921 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10922 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10924 std::swap(LHS, RHS);
10926 Opcode = X86ISD::FMIN;
10929 // Converting this to a min would handle NaNs incorrectly.
10930 if (!UnsafeFPMath &&
10931 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10933 Opcode = X86ISD::FMIN;
10936 // Converting this to a min would handle both negative zeros and NaNs
10937 // incorrectly, but we can swap the operands to fix both.
10938 std::swap(LHS, RHS);
10942 Opcode = X86ISD::FMIN;
10946 // Converting this to a max would handle NaNs incorrectly.
10947 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10949 Opcode = X86ISD::FMAX;
10952 // Converting this to a max would handle comparisons between positive
10953 // and negative zero incorrectly, and swapping the operands would
10954 // cause it to handle NaNs incorrectly.
10955 if (!UnsafeFPMath &&
10956 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10957 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10959 std::swap(LHS, RHS);
10961 Opcode = X86ISD::FMAX;
10964 // Converting this to a max would handle both negative zeros and NaNs
10965 // incorrectly, but we can swap the operands to fix both.
10966 std::swap(LHS, RHS);
10970 Opcode = X86ISD::FMAX;
10976 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10979 // If this is a select between two integer constants, try to do some
10981 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10982 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10983 // Don't do this for crazy integer types.
10984 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10985 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10986 // so that TrueC (the true value) is larger than FalseC.
10987 bool NeedsCondInvert = false;
10989 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10990 // Efficiently invertible.
10991 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
10992 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
10993 isa<ConstantSDNode>(Cond.getOperand(1))))) {
10994 NeedsCondInvert = true;
10995 std::swap(TrueC, FalseC);
10998 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
10999 if (FalseC->getAPIntValue() == 0 &&
11000 TrueC->getAPIntValue().isPowerOf2()) {
11001 if (NeedsCondInvert) // Invert the condition if needed.
11002 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11003 DAG.getConstant(1, Cond.getValueType()));
11005 // Zero extend the condition if needed.
11006 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11008 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11009 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11010 DAG.getConstant(ShAmt, MVT::i8));
11013 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11014 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11015 if (NeedsCondInvert) // Invert the condition if needed.
11016 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11017 DAG.getConstant(1, Cond.getValueType()));
11019 // Zero extend the condition if needed.
11020 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11021 FalseC->getValueType(0), Cond);
11022 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11023 SDValue(FalseC, 0));
11026 // Optimize cases that will turn into an LEA instruction. This requires
11027 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11028 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11029 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11030 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11032 bool isFastMultiplier = false;
11034 switch ((unsigned char)Diff) {
11036 case 1: // result = add base, cond
11037 case 2: // result = lea base( , cond*2)
11038 case 3: // result = lea base(cond, cond*2)
11039 case 4: // result = lea base( , cond*4)
11040 case 5: // result = lea base(cond, cond*4)
11041 case 8: // result = lea base( , cond*8)
11042 case 9: // result = lea base(cond, cond*8)
11043 isFastMultiplier = true;
11048 if (isFastMultiplier) {
11049 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11050 if (NeedsCondInvert) // Invert the condition if needed.
11051 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11052 DAG.getConstant(1, Cond.getValueType()));
11054 // Zero extend the condition if needed.
11055 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11057 // Scale the condition by the difference.
11059 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11060 DAG.getConstant(Diff, Cond.getValueType()));
11062 // Add the base if non-zero.
11063 if (FalseC->getAPIntValue() != 0)
11064 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11065 SDValue(FalseC, 0));
11075 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11076 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11077 TargetLowering::DAGCombinerInfo &DCI) {
11078 DebugLoc DL = N->getDebugLoc();
11080 // If the flag operand isn't dead, don't touch this CMOV.
11081 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11084 // If this is a select between two integer constants, try to do some
11085 // optimizations. Note that the operands are ordered the opposite of SELECT
11087 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
11088 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11089 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11090 // larger than FalseC (the false value).
11091 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11093 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11094 CC = X86::GetOppositeBranchCondition(CC);
11095 std::swap(TrueC, FalseC);
11098 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
11099 // This is efficient for any integer data type (including i8/i16) and
11101 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11102 SDValue Cond = N->getOperand(3);
11103 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11104 DAG.getConstant(CC, MVT::i8), Cond);
11106 // Zero extend the condition if needed.
11107 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11109 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11110 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11111 DAG.getConstant(ShAmt, MVT::i8));
11112 if (N->getNumValues() == 2) // Dead flag value?
11113 return DCI.CombineTo(N, Cond, SDValue());
11117 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
11118 // for any integer data type, including i8/i16.
11119 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11120 SDValue Cond = N->getOperand(3);
11121 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11122 DAG.getConstant(CC, MVT::i8), Cond);
11124 // Zero extend the condition if needed.
11125 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11126 FalseC->getValueType(0), Cond);
11127 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11128 SDValue(FalseC, 0));
11130 if (N->getNumValues() == 2) // Dead flag value?
11131 return DCI.CombineTo(N, Cond, SDValue());
11135 // Optimize cases that will turn into an LEA instruction. This requires
11136 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11137 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11138 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11139 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11141 bool isFastMultiplier = false;
11143 switch ((unsigned char)Diff) {
11145 case 1: // result = add base, cond
11146 case 2: // result = lea base( , cond*2)
11147 case 3: // result = lea base(cond, cond*2)
11148 case 4: // result = lea base( , cond*4)
11149 case 5: // result = lea base(cond, cond*4)
11150 case 8: // result = lea base( , cond*8)
11151 case 9: // result = lea base(cond, cond*8)
11152 isFastMultiplier = true;
11157 if (isFastMultiplier) {
11158 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11159 SDValue Cond = N->getOperand(3);
11160 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11161 DAG.getConstant(CC, MVT::i8), Cond);
11162 // Zero extend the condition if needed.
11163 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11165 // Scale the condition by the difference.
11167 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11168 DAG.getConstant(Diff, Cond.getValueType()));
11170 // Add the base if non-zero.
11171 if (FalseC->getAPIntValue() != 0)
11172 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11173 SDValue(FalseC, 0));
11174 if (N->getNumValues() == 2) // Dead flag value?
11175 return DCI.CombineTo(N, Cond, SDValue());
11185 /// PerformMulCombine - Optimize a single multiply with constant into two
11186 /// in order to implement it with two cheaper instructions, e.g.
11187 /// LEA + SHL, LEA + LEA.
11188 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11189 TargetLowering::DAGCombinerInfo &DCI) {
11190 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11193 EVT VT = N->getValueType(0);
11194 if (VT != MVT::i64)
11197 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11200 uint64_t MulAmt = C->getZExtValue();
11201 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11204 uint64_t MulAmt1 = 0;
11205 uint64_t MulAmt2 = 0;
11206 if ((MulAmt % 9) == 0) {
11208 MulAmt2 = MulAmt / 9;
11209 } else if ((MulAmt % 5) == 0) {
11211 MulAmt2 = MulAmt / 5;
11212 } else if ((MulAmt % 3) == 0) {
11214 MulAmt2 = MulAmt / 3;
11217 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11218 DebugLoc DL = N->getDebugLoc();
11220 if (isPowerOf2_64(MulAmt2) &&
11221 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11222 // If second multiplifer is pow2, issue it first. We want the multiply by
11223 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11225 std::swap(MulAmt1, MulAmt2);
11228 if (isPowerOf2_64(MulAmt1))
11229 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11230 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11232 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11233 DAG.getConstant(MulAmt1, VT));
11235 if (isPowerOf2_64(MulAmt2))
11236 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11237 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11239 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11240 DAG.getConstant(MulAmt2, VT));
11242 // Do not add new nodes to DAG combiner worklist.
11243 DCI.CombineTo(N, NewMul, false);
11248 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11249 SDValue N0 = N->getOperand(0);
11250 SDValue N1 = N->getOperand(1);
11251 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11252 EVT VT = N0.getValueType();
11254 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11255 // since the result of setcc_c is all zero's or all ones.
11256 if (N1C && N0.getOpcode() == ISD::AND &&
11257 N0.getOperand(1).getOpcode() == ISD::Constant) {
11258 SDValue N00 = N0.getOperand(0);
11259 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11260 ((N00.getOpcode() == ISD::ANY_EXTEND ||
11261 N00.getOpcode() == ISD::ZERO_EXTEND) &&
11262 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11263 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11264 APInt ShAmt = N1C->getAPIntValue();
11265 Mask = Mask.shl(ShAmt);
11267 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11268 N00, DAG.getConstant(Mask, VT));
11275 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11277 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11278 const X86Subtarget *Subtarget) {
11279 EVT VT = N->getValueType(0);
11280 if (!VT.isVector() && VT.isInteger() &&
11281 N->getOpcode() == ISD::SHL)
11282 return PerformSHLCombine(N, DAG);
11284 // On X86 with SSE2 support, we can transform this to a vector shift if
11285 // all elements are shifted by the same amount. We can't do this in legalize
11286 // because the a constant vector is typically transformed to a constant pool
11287 // so we have no knowledge of the shift amount.
11288 if (!Subtarget->hasSSE2())
11291 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11294 SDValue ShAmtOp = N->getOperand(1);
11295 EVT EltVT = VT.getVectorElementType();
11296 DebugLoc DL = N->getDebugLoc();
11297 SDValue BaseShAmt = SDValue();
11298 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11299 unsigned NumElts = VT.getVectorNumElements();
11301 for (; i != NumElts; ++i) {
11302 SDValue Arg = ShAmtOp.getOperand(i);
11303 if (Arg.getOpcode() == ISD::UNDEF) continue;
11307 for (; i != NumElts; ++i) {
11308 SDValue Arg = ShAmtOp.getOperand(i);
11309 if (Arg.getOpcode() == ISD::UNDEF) continue;
11310 if (Arg != BaseShAmt) {
11314 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11315 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11316 SDValue InVec = ShAmtOp.getOperand(0);
11317 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11318 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11320 for (; i != NumElts; ++i) {
11321 SDValue Arg = InVec.getOperand(i);
11322 if (Arg.getOpcode() == ISD::UNDEF) continue;
11326 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11327 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11328 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11329 if (C->getZExtValue() == SplatIdx)
11330 BaseShAmt = InVec.getOperand(1);
11333 if (BaseShAmt.getNode() == 0)
11334 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11335 DAG.getIntPtrConstant(0));
11339 // The shift amount is an i32.
11340 if (EltVT.bitsGT(MVT::i32))
11341 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11342 else if (EltVT.bitsLT(MVT::i32))
11343 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11345 // The shift amount is identical so we can do a vector shift.
11346 SDValue ValOp = N->getOperand(0);
11347 switch (N->getOpcode()) {
11349 llvm_unreachable("Unknown shift opcode!");
11352 if (VT == MVT::v2i64)
11353 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11354 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11356 if (VT == MVT::v4i32)
11357 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11358 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11360 if (VT == MVT::v8i16)
11361 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11362 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11366 if (VT == MVT::v4i32)
11367 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11368 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11370 if (VT == MVT::v8i16)
11371 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11372 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11376 if (VT == MVT::v2i64)
11377 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11378 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11380 if (VT == MVT::v4i32)
11381 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11382 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11384 if (VT == MVT::v8i16)
11385 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11386 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11394 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11395 TargetLowering::DAGCombinerInfo &DCI,
11396 const X86Subtarget *Subtarget) {
11397 if (DCI.isBeforeLegalizeOps())
11400 // Want to form PANDN nodes, in the hopes of then easily combining them with
11401 // OR and AND nodes to form PBLEND/PSIGN.
11402 EVT VT = N->getValueType(0);
11403 if (VT != MVT::v2i64)
11406 SDValue N0 = N->getOperand(0);
11407 SDValue N1 = N->getOperand(1);
11408 DebugLoc DL = N->getDebugLoc();
11410 // Check LHS for vnot
11411 if (N0.getOpcode() == ISD::XOR &&
11412 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11413 return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11415 // Check RHS for vnot
11416 if (N1.getOpcode() == ISD::XOR &&
11417 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11418 return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11423 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11424 TargetLowering::DAGCombinerInfo &DCI,
11425 const X86Subtarget *Subtarget) {
11426 if (DCI.isBeforeLegalizeOps())
11429 EVT VT = N->getValueType(0);
11430 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11433 SDValue N0 = N->getOperand(0);
11434 SDValue N1 = N->getOperand(1);
11436 // look for psign/blend
11437 if (Subtarget->hasSSSE3()) {
11438 if (VT == MVT::v2i64) {
11439 // Canonicalize pandn to RHS
11440 if (N0.getOpcode() == X86ISD::PANDN)
11442 // or (and (m, x), (pandn m, y))
11443 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11444 SDValue Mask = N1.getOperand(0);
11445 SDValue X = N1.getOperand(1);
11447 if (N0.getOperand(0) == Mask)
11448 Y = N0.getOperand(1);
11449 if (N0.getOperand(1) == Mask)
11450 Y = N0.getOperand(0);
11452 // Check to see if the mask appeared in both the AND and PANDN and
11456 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11457 if (Mask.getOpcode() != ISD::BITCAST ||
11458 X.getOpcode() != ISD::BITCAST ||
11459 Y.getOpcode() != ISD::BITCAST)
11462 // Look through mask bitcast.
11463 Mask = Mask.getOperand(0);
11464 EVT MaskVT = Mask.getValueType();
11466 // Validate that the Mask operand is a vector sra node. The sra node
11467 // will be an intrinsic.
11468 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11471 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11472 // there is no psrai.b
11473 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11474 case Intrinsic::x86_sse2_psrai_w:
11475 case Intrinsic::x86_sse2_psrai_d:
11477 default: return SDValue();
11480 // Check that the SRA is all signbits.
11481 SDValue SraC = Mask.getOperand(2);
11482 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
11483 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11484 if ((SraAmt + 1) != EltBits)
11487 DebugLoc DL = N->getDebugLoc();
11489 // Now we know we at least have a plendvb with the mask val. See if
11490 // we can form a psignb/w/d.
11491 // psign = x.type == y.type == mask.type && y = sub(0, x);
11492 X = X.getOperand(0);
11493 Y = Y.getOperand(0);
11494 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11495 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11496 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11499 case 8: Opc = X86ISD::PSIGNB; break;
11500 case 16: Opc = X86ISD::PSIGNW; break;
11501 case 32: Opc = X86ISD::PSIGND; break;
11505 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11506 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11509 // PBLENDVB only available on SSE 4.1
11510 if (!Subtarget->hasSSE41())
11513 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11514 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11515 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11516 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11517 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11522 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11523 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11525 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11527 if (!N0.hasOneUse() || !N1.hasOneUse())
11530 SDValue ShAmt0 = N0.getOperand(1);
11531 if (ShAmt0.getValueType() != MVT::i8)
11533 SDValue ShAmt1 = N1.getOperand(1);
11534 if (ShAmt1.getValueType() != MVT::i8)
11536 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11537 ShAmt0 = ShAmt0.getOperand(0);
11538 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11539 ShAmt1 = ShAmt1.getOperand(0);
11541 DebugLoc DL = N->getDebugLoc();
11542 unsigned Opc = X86ISD::SHLD;
11543 SDValue Op0 = N0.getOperand(0);
11544 SDValue Op1 = N1.getOperand(0);
11545 if (ShAmt0.getOpcode() == ISD::SUB) {
11546 Opc = X86ISD::SHRD;
11547 std::swap(Op0, Op1);
11548 std::swap(ShAmt0, ShAmt1);
11551 unsigned Bits = VT.getSizeInBits();
11552 if (ShAmt1.getOpcode() == ISD::SUB) {
11553 SDValue Sum = ShAmt1.getOperand(0);
11554 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11555 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11556 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11557 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11558 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11559 return DAG.getNode(Opc, DL, VT,
11561 DAG.getNode(ISD::TRUNCATE, DL,
11564 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11565 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11567 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11568 return DAG.getNode(Opc, DL, VT,
11569 N0.getOperand(0), N1.getOperand(0),
11570 DAG.getNode(ISD::TRUNCATE, DL,
11577 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11578 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11579 const X86Subtarget *Subtarget) {
11580 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
11581 // the FP state in cases where an emms may be missing.
11582 // A preferable solution to the general problem is to figure out the right
11583 // places to insert EMMS. This qualifies as a quick hack.
11585 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11586 StoreSDNode *St = cast<StoreSDNode>(N);
11587 EVT VT = St->getValue().getValueType();
11588 if (VT.getSizeInBits() != 64)
11591 const Function *F = DAG.getMachineFunction().getFunction();
11592 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11593 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11594 && Subtarget->hasSSE2();
11595 if ((VT.isVector() ||
11596 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11597 isa<LoadSDNode>(St->getValue()) &&
11598 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11599 St->getChain().hasOneUse() && !St->isVolatile()) {
11600 SDNode* LdVal = St->getValue().getNode();
11601 LoadSDNode *Ld = 0;
11602 int TokenFactorIndex = -1;
11603 SmallVector<SDValue, 8> Ops;
11604 SDNode* ChainVal = St->getChain().getNode();
11605 // Must be a store of a load. We currently handle two cases: the load
11606 // is a direct child, and it's under an intervening TokenFactor. It is
11607 // possible to dig deeper under nested TokenFactors.
11608 if (ChainVal == LdVal)
11609 Ld = cast<LoadSDNode>(St->getChain());
11610 else if (St->getValue().hasOneUse() &&
11611 ChainVal->getOpcode() == ISD::TokenFactor) {
11612 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11613 if (ChainVal->getOperand(i).getNode() == LdVal) {
11614 TokenFactorIndex = i;
11615 Ld = cast<LoadSDNode>(St->getValue());
11617 Ops.push_back(ChainVal->getOperand(i));
11621 if (!Ld || !ISD::isNormalLoad(Ld))
11624 // If this is not the MMX case, i.e. we are just turning i64 load/store
11625 // into f64 load/store, avoid the transformation if there are multiple
11626 // uses of the loaded value.
11627 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11630 DebugLoc LdDL = Ld->getDebugLoc();
11631 DebugLoc StDL = N->getDebugLoc();
11632 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11633 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11635 if (Subtarget->is64Bit() || F64IsLegal) {
11636 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11637 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11638 Ld->getPointerInfo(), Ld->isVolatile(),
11639 Ld->isNonTemporal(), Ld->getAlignment());
11640 SDValue NewChain = NewLd.getValue(1);
11641 if (TokenFactorIndex != -1) {
11642 Ops.push_back(NewChain);
11643 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11646 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11647 St->getPointerInfo(),
11648 St->isVolatile(), St->isNonTemporal(),
11649 St->getAlignment());
11652 // Otherwise, lower to two pairs of 32-bit loads / stores.
11653 SDValue LoAddr = Ld->getBasePtr();
11654 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11655 DAG.getConstant(4, MVT::i32));
11657 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11658 Ld->getPointerInfo(),
11659 Ld->isVolatile(), Ld->isNonTemporal(),
11660 Ld->getAlignment());
11661 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11662 Ld->getPointerInfo().getWithOffset(4),
11663 Ld->isVolatile(), Ld->isNonTemporal(),
11664 MinAlign(Ld->getAlignment(), 4));
11666 SDValue NewChain = LoLd.getValue(1);
11667 if (TokenFactorIndex != -1) {
11668 Ops.push_back(LoLd);
11669 Ops.push_back(HiLd);
11670 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11674 LoAddr = St->getBasePtr();
11675 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11676 DAG.getConstant(4, MVT::i32));
11678 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11679 St->getPointerInfo(),
11680 St->isVolatile(), St->isNonTemporal(),
11681 St->getAlignment());
11682 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11683 St->getPointerInfo().getWithOffset(4),
11685 St->isNonTemporal(),
11686 MinAlign(St->getAlignment(), 4));
11687 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11692 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11693 /// X86ISD::FXOR nodes.
11694 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11695 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11696 // F[X]OR(0.0, x) -> x
11697 // F[X]OR(x, 0.0) -> x
11698 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11699 if (C->getValueAPF().isPosZero())
11700 return N->getOperand(1);
11701 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11702 if (C->getValueAPF().isPosZero())
11703 return N->getOperand(0);
11707 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11708 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11709 // FAND(0.0, x) -> 0.0
11710 // FAND(x, 0.0) -> 0.0
11711 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11712 if (C->getValueAPF().isPosZero())
11713 return N->getOperand(0);
11714 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11715 if (C->getValueAPF().isPosZero())
11716 return N->getOperand(1);
11720 static SDValue PerformBTCombine(SDNode *N,
11722 TargetLowering::DAGCombinerInfo &DCI) {
11723 // BT ignores high bits in the bit index operand.
11724 SDValue Op1 = N->getOperand(1);
11725 if (Op1.hasOneUse()) {
11726 unsigned BitWidth = Op1.getValueSizeInBits();
11727 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11728 APInt KnownZero, KnownOne;
11729 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11730 !DCI.isBeforeLegalizeOps());
11731 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11732 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11733 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11734 DCI.CommitTargetLoweringOpt(TLO);
11739 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11740 SDValue Op = N->getOperand(0);
11741 if (Op.getOpcode() == ISD::BITCAST)
11742 Op = Op.getOperand(0);
11743 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11744 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11745 VT.getVectorElementType().getSizeInBits() ==
11746 OpVT.getVectorElementType().getSizeInBits()) {
11747 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11752 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11753 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
11754 // (and (i32 x86isd::setcc_carry), 1)
11755 // This eliminates the zext. This transformation is necessary because
11756 // ISD::SETCC is always legalized to i8.
11757 DebugLoc dl = N->getDebugLoc();
11758 SDValue N0 = N->getOperand(0);
11759 EVT VT = N->getValueType(0);
11760 if (N0.getOpcode() == ISD::AND &&
11762 N0.getOperand(0).hasOneUse()) {
11763 SDValue N00 = N0.getOperand(0);
11764 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11766 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11767 if (!C || C->getZExtValue() != 1)
11769 return DAG.getNode(ISD::AND, dl, VT,
11770 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11771 N00.getOperand(0), N00.getOperand(1)),
11772 DAG.getConstant(1, VT));
11778 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
11779 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
11780 unsigned X86CC = N->getConstantOperandVal(0);
11781 SDValue EFLAG = N->getOperand(1);
11782 DebugLoc DL = N->getDebugLoc();
11784 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
11785 // a zext and produces an all-ones bit which is more useful than 0/1 in some
11787 if (X86CC == X86::COND_B)
11788 return DAG.getNode(ISD::AND, DL, MVT::i8,
11789 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
11790 DAG.getConstant(X86CC, MVT::i8), EFLAG),
11791 DAG.getConstant(1, MVT::i8));
11796 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
11797 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
11798 X86TargetLowering::DAGCombinerInfo &DCI) {
11799 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
11800 // the result is either zero or one (depending on the input carry bit).
11801 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
11802 if (X86::isZeroNode(N->getOperand(0)) &&
11803 X86::isZeroNode(N->getOperand(1)) &&
11804 // We don't have a good way to replace an EFLAGS use, so only do this when
11806 SDValue(N, 1).use_empty()) {
11807 DebugLoc DL = N->getDebugLoc();
11808 EVT VT = N->getValueType(0);
11809 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
11810 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
11811 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
11812 DAG.getConstant(X86::COND_B,MVT::i8),
11814 DAG.getConstant(1, VT));
11815 return DCI.CombineTo(N, Res1, CarryOut);
11821 // fold (add Y, (sete X, 0)) -> adc 0, Y
11822 // (add Y, (setne X, 0)) -> sbb -1, Y
11823 // (sub (sete X, 0), Y) -> sbb 0, Y
11824 // (sub (setne X, 0), Y) -> adc -1, Y
11825 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
11826 DebugLoc DL = N->getDebugLoc();
11828 // Look through ZExts.
11829 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
11830 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
11833 SDValue SetCC = Ext.getOperand(0);
11834 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
11837 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
11838 if (CC != X86::COND_E && CC != X86::COND_NE)
11841 SDValue Cmp = SetCC.getOperand(1);
11842 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
11843 !X86::isZeroNode(Cmp.getOperand(1)) ||
11844 !Cmp.getOperand(0).getValueType().isInteger())
11847 SDValue CmpOp0 = Cmp.getOperand(0);
11848 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
11849 DAG.getConstant(1, CmpOp0.getValueType()));
11851 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
11852 if (CC == X86::COND_NE)
11853 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
11854 DL, OtherVal.getValueType(), OtherVal,
11855 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
11856 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
11857 DL, OtherVal.getValueType(), OtherVal,
11858 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
11861 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
11862 DAGCombinerInfo &DCI) const {
11863 SelectionDAG &DAG = DCI.DAG;
11864 switch (N->getOpcode()) {
11866 case ISD::EXTRACT_VECTOR_ELT:
11867 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11868 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
11869 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
11871 case ISD::SUB: return OptimizeConditonalInDecrement(N, DAG);
11872 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
11873 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
11876 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
11877 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
11878 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
11879 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
11881 case X86ISD::FOR: return PerformFORCombine(N, DAG);
11882 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
11883 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
11884 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
11885 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
11886 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
11887 case X86ISD::SHUFPS: // Handle all target specific shuffles
11888 case X86ISD::SHUFPD:
11889 case X86ISD::PALIGN:
11890 case X86ISD::PUNPCKHBW:
11891 case X86ISD::PUNPCKHWD:
11892 case X86ISD::PUNPCKHDQ:
11893 case X86ISD::PUNPCKHQDQ:
11894 case X86ISD::UNPCKHPS:
11895 case X86ISD::UNPCKHPD:
11896 case X86ISD::PUNPCKLBW:
11897 case X86ISD::PUNPCKLWD:
11898 case X86ISD::PUNPCKLDQ:
11899 case X86ISD::PUNPCKLQDQ:
11900 case X86ISD::UNPCKLPS:
11901 case X86ISD::UNPCKLPD:
11902 case X86ISD::MOVHLPS:
11903 case X86ISD::MOVLHPS:
11904 case X86ISD::PSHUFD:
11905 case X86ISD::PSHUFHW:
11906 case X86ISD::PSHUFLW:
11907 case X86ISD::MOVSS:
11908 case X86ISD::MOVSD:
11909 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
11915 /// isTypeDesirableForOp - Return true if the target has native support for
11916 /// the specified value type and it is 'desirable' to use the type for the
11917 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
11918 /// instruction encodings are longer and some i16 instructions are slow.
11919 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
11920 if (!isTypeLegal(VT))
11922 if (VT != MVT::i16)
11929 case ISD::SIGN_EXTEND:
11930 case ISD::ZERO_EXTEND:
11931 case ISD::ANY_EXTEND:
11944 /// IsDesirableToPromoteOp - This method query the target whether it is
11945 /// beneficial for dag combiner to promote the specified node. If true, it
11946 /// should return the desired promotion type by reference.
11947 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
11948 EVT VT = Op.getValueType();
11949 if (VT != MVT::i16)
11952 bool Promote = false;
11953 bool Commute = false;
11954 switch (Op.getOpcode()) {
11957 LoadSDNode *LD = cast<LoadSDNode>(Op);
11958 // If the non-extending load has a single use and it's not live out, then it
11959 // might be folded.
11960 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11961 Op.hasOneUse()*/) {
11962 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11963 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11964 // The only case where we'd want to promote LOAD (rather then it being
11965 // promoted as an operand is when it's only use is liveout.
11966 if (UI->getOpcode() != ISD::CopyToReg)
11973 case ISD::SIGN_EXTEND:
11974 case ISD::ZERO_EXTEND:
11975 case ISD::ANY_EXTEND:
11980 SDValue N0 = Op.getOperand(0);
11981 // Look out for (store (shl (load), x)).
11982 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11995 SDValue N0 = Op.getOperand(0);
11996 SDValue N1 = Op.getOperand(1);
11997 if (!Commute && MayFoldLoad(N1))
11999 // Avoid disabling potential load folding opportunities.
12000 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12002 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12012 //===----------------------------------------------------------------------===//
12013 // X86 Inline Assembly Support
12014 //===----------------------------------------------------------------------===//
12016 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12017 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12019 std::string AsmStr = IA->getAsmString();
12021 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12022 SmallVector<StringRef, 4> AsmPieces;
12023 SplitString(AsmStr, AsmPieces, ";\n");
12025 switch (AsmPieces.size()) {
12026 default: return false;
12028 AsmStr = AsmPieces[0];
12030 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
12032 // FIXME: this should verify that we are targetting a 486 or better. If not,
12033 // we will turn this bswap into something that will be lowered to logical ops
12034 // instead of emitting the bswap asm. For now, we don't support 486 or lower
12035 // so don't worry about this.
12037 if (AsmPieces.size() == 2 &&
12038 (AsmPieces[0] == "bswap" ||
12039 AsmPieces[0] == "bswapq" ||
12040 AsmPieces[0] == "bswapl") &&
12041 (AsmPieces[1] == "$0" ||
12042 AsmPieces[1] == "${0:q}")) {
12043 // No need to check constraints, nothing other than the equivalent of
12044 // "=r,0" would be valid here.
12045 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12046 if (!Ty || Ty->getBitWidth() % 16 != 0)
12048 return IntrinsicLowering::LowerToByteSwap(CI);
12050 // rorw $$8, ${0:w} --> llvm.bswap.i16
12051 if (CI->getType()->isIntegerTy(16) &&
12052 AsmPieces.size() == 3 &&
12053 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12054 AsmPieces[1] == "$$8," &&
12055 AsmPieces[2] == "${0:w}" &&
12056 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12058 const std::string &ConstraintsStr = IA->getConstraintString();
12059 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12060 std::sort(AsmPieces.begin(), AsmPieces.end());
12061 if (AsmPieces.size() == 4 &&
12062 AsmPieces[0] == "~{cc}" &&
12063 AsmPieces[1] == "~{dirflag}" &&
12064 AsmPieces[2] == "~{flags}" &&
12065 AsmPieces[3] == "~{fpsr}") {
12066 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12067 if (!Ty || Ty->getBitWidth() % 16 != 0)
12069 return IntrinsicLowering::LowerToByteSwap(CI);
12074 if (CI->getType()->isIntegerTy(32) &&
12075 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12076 SmallVector<StringRef, 4> Words;
12077 SplitString(AsmPieces[0], Words, " \t,");
12078 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12079 Words[2] == "${0:w}") {
12081 SplitString(AsmPieces[1], Words, " \t,");
12082 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12083 Words[2] == "$0") {
12085 SplitString(AsmPieces[2], Words, " \t,");
12086 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12087 Words[2] == "${0:w}") {
12089 const std::string &ConstraintsStr = IA->getConstraintString();
12090 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12091 std::sort(AsmPieces.begin(), AsmPieces.end());
12092 if (AsmPieces.size() == 4 &&
12093 AsmPieces[0] == "~{cc}" &&
12094 AsmPieces[1] == "~{dirflag}" &&
12095 AsmPieces[2] == "~{flags}" &&
12096 AsmPieces[3] == "~{fpsr}") {
12097 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12098 if (!Ty || Ty->getBitWidth() % 16 != 0)
12100 return IntrinsicLowering::LowerToByteSwap(CI);
12107 if (CI->getType()->isIntegerTy(64)) {
12108 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12109 if (Constraints.size() >= 2 &&
12110 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12111 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12112 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
12113 SmallVector<StringRef, 4> Words;
12114 SplitString(AsmPieces[0], Words, " \t");
12115 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12117 SplitString(AsmPieces[1], Words, " \t");
12118 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12120 SplitString(AsmPieces[2], Words, " \t,");
12121 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12122 Words[2] == "%edx") {
12123 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12124 if (!Ty || Ty->getBitWidth() % 16 != 0)
12126 return IntrinsicLowering::LowerToByteSwap(CI);
12139 /// getConstraintType - Given a constraint letter, return the type of
12140 /// constraint it is for this target.
12141 X86TargetLowering::ConstraintType
12142 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12143 if (Constraint.size() == 1) {
12144 switch (Constraint[0]) {
12154 return C_RegisterClass;
12178 return TargetLowering::getConstraintType(Constraint);
12181 /// Examine constraint type and operand type and determine a weight value.
12182 /// This object must already have been set up with the operand type
12183 /// and the current alternative constraint selected.
12184 TargetLowering::ConstraintWeight
12185 X86TargetLowering::getSingleConstraintMatchWeight(
12186 AsmOperandInfo &info, const char *constraint) const {
12187 ConstraintWeight weight = CW_Invalid;
12188 Value *CallOperandVal = info.CallOperandVal;
12189 // If we don't have a value, we can't do a match,
12190 // but allow it at the lowest weight.
12191 if (CallOperandVal == NULL)
12193 const Type *type = CallOperandVal->getType();
12194 // Look at the constraint type.
12195 switch (*constraint) {
12197 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12208 if (CallOperandVal->getType()->isIntegerTy())
12209 weight = CW_SpecificReg;
12214 if (type->isFloatingPointTy())
12215 weight = CW_SpecificReg;
12218 if (type->isX86_MMXTy() && Subtarget->hasMMX())
12219 weight = CW_SpecificReg;
12223 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12224 weight = CW_Register;
12227 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12228 if (C->getZExtValue() <= 31)
12229 weight = CW_Constant;
12233 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12234 if (C->getZExtValue() <= 63)
12235 weight = CW_Constant;
12239 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12240 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12241 weight = CW_Constant;
12245 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12246 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12247 weight = CW_Constant;
12251 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12252 if (C->getZExtValue() <= 3)
12253 weight = CW_Constant;
12257 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12258 if (C->getZExtValue() <= 0xff)
12259 weight = CW_Constant;
12264 if (dyn_cast<ConstantFP>(CallOperandVal)) {
12265 weight = CW_Constant;
12269 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12270 if ((C->getSExtValue() >= -0x80000000LL) &&
12271 (C->getSExtValue() <= 0x7fffffffLL))
12272 weight = CW_Constant;
12276 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12277 if (C->getZExtValue() <= 0xffffffff)
12278 weight = CW_Constant;
12285 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12286 /// with another that has more specific requirements based on the type of the
12287 /// corresponding operand.
12288 const char *X86TargetLowering::
12289 LowerXConstraint(EVT ConstraintVT) const {
12290 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12291 // 'f' like normal targets.
12292 if (ConstraintVT.isFloatingPoint()) {
12293 if (Subtarget->hasXMMInt())
12295 if (Subtarget->hasXMM())
12299 return TargetLowering::LowerXConstraint(ConstraintVT);
12302 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12303 /// vector. If it is invalid, don't add anything to Ops.
12304 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12306 std::vector<SDValue>&Ops,
12307 SelectionDAG &DAG) const {
12308 SDValue Result(0, 0);
12310 switch (Constraint) {
12313 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12314 if (C->getZExtValue() <= 31) {
12315 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12321 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12322 if (C->getZExtValue() <= 63) {
12323 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12329 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12330 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12331 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12337 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12338 if (C->getZExtValue() <= 255) {
12339 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12345 // 32-bit signed value
12346 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12347 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12348 C->getSExtValue())) {
12349 // Widen to 64 bits here to get it sign extended.
12350 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12353 // FIXME gcc accepts some relocatable values here too, but only in certain
12354 // memory models; it's complicated.
12359 // 32-bit unsigned value
12360 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12361 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12362 C->getZExtValue())) {
12363 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12367 // FIXME gcc accepts some relocatable values here too, but only in certain
12368 // memory models; it's complicated.
12372 // Literal immediates are always ok.
12373 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12374 // Widen to 64 bits here to get it sign extended.
12375 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12379 // In any sort of PIC mode addresses need to be computed at runtime by
12380 // adding in a register or some sort of table lookup. These can't
12381 // be used as immediates.
12382 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12385 // If we are in non-pic codegen mode, we allow the address of a global (with
12386 // an optional displacement) to be used with 'i'.
12387 GlobalAddressSDNode *GA = 0;
12388 int64_t Offset = 0;
12390 // Match either (GA), (GA+C), (GA+C1+C2), etc.
12392 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12393 Offset += GA->getOffset();
12395 } else if (Op.getOpcode() == ISD::ADD) {
12396 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12397 Offset += C->getZExtValue();
12398 Op = Op.getOperand(0);
12401 } else if (Op.getOpcode() == ISD::SUB) {
12402 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12403 Offset += -C->getZExtValue();
12404 Op = Op.getOperand(0);
12409 // Otherwise, this isn't something we can handle, reject it.
12413 const GlobalValue *GV = GA->getGlobal();
12414 // If we require an extra load to get this address, as in PIC mode, we
12415 // can't accept it.
12416 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12417 getTargetMachine())))
12420 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12421 GA->getValueType(0), Offset);
12426 if (Result.getNode()) {
12427 Ops.push_back(Result);
12430 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12433 std::vector<unsigned> X86TargetLowering::
12434 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12436 if (Constraint.size() == 1) {
12437 // FIXME: not handling fp-stack yet!
12438 switch (Constraint[0]) { // GCC X86 Constraint Letters
12439 default: break; // Unknown constraint letter
12440 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12441 if (Subtarget->is64Bit()) {
12442 if (VT == MVT::i32)
12443 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12444 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12445 X86::R10D,X86::R11D,X86::R12D,
12446 X86::R13D,X86::R14D,X86::R15D,
12447 X86::EBP, X86::ESP, 0);
12448 else if (VT == MVT::i16)
12449 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
12450 X86::SI, X86::DI, X86::R8W,X86::R9W,
12451 X86::R10W,X86::R11W,X86::R12W,
12452 X86::R13W,X86::R14W,X86::R15W,
12453 X86::BP, X86::SP, 0);
12454 else if (VT == MVT::i8)
12455 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
12456 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12457 X86::R10B,X86::R11B,X86::R12B,
12458 X86::R13B,X86::R14B,X86::R15B,
12459 X86::BPL, X86::SPL, 0);
12461 else if (VT == MVT::i64)
12462 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12463 X86::RSI, X86::RDI, X86::R8, X86::R9,
12464 X86::R10, X86::R11, X86::R12,
12465 X86::R13, X86::R14, X86::R15,
12466 X86::RBP, X86::RSP, 0);
12470 // 32-bit fallthrough
12471 case 'Q': // Q_REGS
12472 if (VT == MVT::i32)
12473 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12474 else if (VT == MVT::i16)
12475 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12476 else if (VT == MVT::i8)
12477 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12478 else if (VT == MVT::i64)
12479 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12484 return std::vector<unsigned>();
12487 std::pair<unsigned, const TargetRegisterClass*>
12488 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12490 // First, see if this is a constraint that directly corresponds to an LLVM
12492 if (Constraint.size() == 1) {
12493 // GCC Constraint Letters
12494 switch (Constraint[0]) {
12496 case 'r': // GENERAL_REGS
12497 case 'l': // INDEX_REGS
12499 return std::make_pair(0U, X86::GR8RegisterClass);
12500 if (VT == MVT::i16)
12501 return std::make_pair(0U, X86::GR16RegisterClass);
12502 if (VT == MVT::i32 || !Subtarget->is64Bit())
12503 return std::make_pair(0U, X86::GR32RegisterClass);
12504 return std::make_pair(0U, X86::GR64RegisterClass);
12505 case 'R': // LEGACY_REGS
12507 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12508 if (VT == MVT::i16)
12509 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12510 if (VT == MVT::i32 || !Subtarget->is64Bit())
12511 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12512 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12513 case 'f': // FP Stack registers.
12514 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12515 // value to the correct fpstack register class.
12516 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12517 return std::make_pair(0U, X86::RFP32RegisterClass);
12518 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12519 return std::make_pair(0U, X86::RFP64RegisterClass);
12520 return std::make_pair(0U, X86::RFP80RegisterClass);
12521 case 'y': // MMX_REGS if MMX allowed.
12522 if (!Subtarget->hasMMX()) break;
12523 return std::make_pair(0U, X86::VR64RegisterClass);
12524 case 'Y': // SSE_REGS if SSE2 allowed
12525 if (!Subtarget->hasXMMInt()) break;
12527 case 'x': // SSE_REGS if SSE1 allowed
12528 if (!Subtarget->hasXMM()) break;
12530 switch (VT.getSimpleVT().SimpleTy) {
12532 // Scalar SSE types.
12535 return std::make_pair(0U, X86::FR32RegisterClass);
12538 return std::make_pair(0U, X86::FR64RegisterClass);
12546 return std::make_pair(0U, X86::VR128RegisterClass);
12552 // Use the default implementation in TargetLowering to convert the register
12553 // constraint into a member of a register class.
12554 std::pair<unsigned, const TargetRegisterClass*> Res;
12555 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12557 // Not found as a standard register?
12558 if (Res.second == 0) {
12559 // Map st(0) -> st(7) -> ST0
12560 if (Constraint.size() == 7 && Constraint[0] == '{' &&
12561 tolower(Constraint[1]) == 's' &&
12562 tolower(Constraint[2]) == 't' &&
12563 Constraint[3] == '(' &&
12564 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12565 Constraint[5] == ')' &&
12566 Constraint[6] == '}') {
12568 Res.first = X86::ST0+Constraint[4]-'0';
12569 Res.second = X86::RFP80RegisterClass;
12573 // GCC allows "st(0)" to be called just plain "st".
12574 if (StringRef("{st}").equals_lower(Constraint)) {
12575 Res.first = X86::ST0;
12576 Res.second = X86::RFP80RegisterClass;
12581 if (StringRef("{flags}").equals_lower(Constraint)) {
12582 Res.first = X86::EFLAGS;
12583 Res.second = X86::CCRRegisterClass;
12587 // 'A' means EAX + EDX.
12588 if (Constraint == "A") {
12589 Res.first = X86::EAX;
12590 Res.second = X86::GR32_ADRegisterClass;
12596 // Otherwise, check to see if this is a register class of the wrong value
12597 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12598 // turn into {ax},{dx}.
12599 if (Res.second->hasType(VT))
12600 return Res; // Correct type already, nothing to do.
12602 // All of the single-register GCC register classes map their values onto
12603 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
12604 // really want an 8-bit or 32-bit register, map to the appropriate register
12605 // class and return the appropriate register.
12606 if (Res.second == X86::GR16RegisterClass) {
12607 if (VT == MVT::i8) {
12608 unsigned DestReg = 0;
12609 switch (Res.first) {
12611 case X86::AX: DestReg = X86::AL; break;
12612 case X86::DX: DestReg = X86::DL; break;
12613 case X86::CX: DestReg = X86::CL; break;
12614 case X86::BX: DestReg = X86::BL; break;
12617 Res.first = DestReg;
12618 Res.second = X86::GR8RegisterClass;
12620 } else if (VT == MVT::i32) {
12621 unsigned DestReg = 0;
12622 switch (Res.first) {
12624 case X86::AX: DestReg = X86::EAX; break;
12625 case X86::DX: DestReg = X86::EDX; break;
12626 case X86::CX: DestReg = X86::ECX; break;
12627 case X86::BX: DestReg = X86::EBX; break;
12628 case X86::SI: DestReg = X86::ESI; break;
12629 case X86::DI: DestReg = X86::EDI; break;
12630 case X86::BP: DestReg = X86::EBP; break;
12631 case X86::SP: DestReg = X86::ESP; break;
12634 Res.first = DestReg;
12635 Res.second = X86::GR32RegisterClass;
12637 } else if (VT == MVT::i64) {
12638 unsigned DestReg = 0;
12639 switch (Res.first) {
12641 case X86::AX: DestReg = X86::RAX; break;
12642 case X86::DX: DestReg = X86::RDX; break;
12643 case X86::CX: DestReg = X86::RCX; break;
12644 case X86::BX: DestReg = X86::RBX; break;
12645 case X86::SI: DestReg = X86::RSI; break;
12646 case X86::DI: DestReg = X86::RDI; break;
12647 case X86::BP: DestReg = X86::RBP; break;
12648 case X86::SP: DestReg = X86::RSP; break;
12651 Res.first = DestReg;
12652 Res.second = X86::GR64RegisterClass;
12655 } else if (Res.second == X86::FR32RegisterClass ||
12656 Res.second == X86::FR64RegisterClass ||
12657 Res.second == X86::VR128RegisterClass) {
12658 // Handle references to XMM physical registers that got mapped into the
12659 // wrong class. This can happen with constraints like {xmm0} where the
12660 // target independent register mapper will just pick the first match it can
12661 // find, ignoring the required type.
12662 if (VT == MVT::f32)
12663 Res.second = X86::FR32RegisterClass;
12664 else if (VT == MVT::f64)
12665 Res.second = X86::FR64RegisterClass;
12666 else if (X86::VR128RegisterClass->hasType(VT))
12667 Res.second = X86::VR128RegisterClass;