1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
55 using namespace dwarf;
57 STATISTIC(NumTailCalls, "Number of tail calls");
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
63 static SDValue Insert128BitVector(SDValue Result,
69 static SDValue Extract128BitVector(SDValue Vec,
74 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
77 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
78 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
79 /// simple subregister reference. Idx is an index in the 128 bits we
80 /// want. It need not be aligned to a 128-bit bounday. That makes
81 /// lowering EXTRACT_VECTOR_ELT operations easier.
82 static SDValue Extract128BitVector(SDValue Vec,
86 EVT VT = Vec.getValueType();
87 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
88 EVT ElVT = VT.getVectorElementType();
89 int Factor = VT.getSizeInBits()/128;
90 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
91 VT.getVectorNumElements()/Factor);
93 // Extract from UNDEF is UNDEF.
94 if (Vec.getOpcode() == ISD::UNDEF)
95 return DAG.getNode(ISD::UNDEF, dl, ResultVT);
97 if (isa<ConstantSDNode>(Idx)) {
98 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
100 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
101 // we can match to VEXTRACTF128.
102 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
104 // This is the index of the first element of the 128-bit chunk
106 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
109 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
110 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
119 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
120 /// sets things up to match to an AVX VINSERTF128 instruction or a
121 /// simple superregister reference. Idx is an index in the 128 bits
122 /// we want. It need not be aligned to a 128-bit bounday. That makes
123 /// lowering INSERT_VECTOR_ELT operations easier.
124 static SDValue Insert128BitVector(SDValue Result,
129 if (isa<ConstantSDNode>(Idx)) {
130 EVT VT = Vec.getValueType();
131 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
133 EVT ElVT = VT.getVectorElementType();
134 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
135 EVT ResultVT = Result.getValueType();
137 // Insert the relevant 128 bits.
138 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
140 // This is the index of the first element of the 128-bit chunk
142 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
145 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
146 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
154 /// Given two vectors, concat them.
155 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
156 DebugLoc dl = Lower.getDebugLoc();
158 assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
160 EVT VT = EVT::getVectorVT(*DAG.getContext(),
161 Lower.getValueType().getVectorElementType(),
162 Lower.getValueType().getVectorNumElements() * 2);
164 // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
165 assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
167 // Insert the upper subvector.
168 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
170 // This is half the length of the result
171 // vector. Start inserting the upper 128
173 Lower.getValueType().getVectorNumElements(),
177 // Insert the lower subvector.
178 Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
182 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
183 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
184 bool is64Bit = Subtarget->is64Bit();
186 if (Subtarget->isTargetEnvMacho()) {
188 return new X8664_MachoTargetObjectFile();
189 return new TargetLoweringObjectFileMachO();
192 if (Subtarget->isTargetELF())
193 return new TargetLoweringObjectFileELF();
194 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
195 return new TargetLoweringObjectFileCOFF();
196 llvm_unreachable("unknown subtarget type");
199 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
200 : TargetLowering(TM, createTLOF(TM)) {
201 Subtarget = &TM.getSubtarget<X86Subtarget>();
202 X86ScalarSSEf64 = Subtarget->hasXMMInt();
203 X86ScalarSSEf32 = Subtarget->hasXMM();
204 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
206 RegInfo = TM.getRegisterInfo();
207 TD = getTargetData();
209 // Set up the TargetLowering object.
210 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
212 // X86 is weird, it always uses i8 for shift amounts and setcc results.
213 setBooleanContents(ZeroOrOneBooleanContent);
215 // For 64-bit since we have so many registers use the ILP scheduler, for
216 // 32-bit code use the register pressure specific scheduling.
217 if (Subtarget->is64Bit())
218 setSchedulingPreference(Sched::ILP);
220 setSchedulingPreference(Sched::RegPressure);
221 setStackPointerRegisterToSaveRestore(X86StackPtr);
223 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
224 // Setup Windows compiler runtime calls.
225 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
226 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
227 setLibcallName(RTLIB::SREM_I64, "_allrem");
228 setLibcallName(RTLIB::UREM_I64, "_aullrem");
229 setLibcallName(RTLIB::MUL_I64, "_allmul");
230 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
231 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
232 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
233 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
234 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
235 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
236 setLibcallCallingConv(RTLIB::MUL_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 setOperationAction(ISD::DYNAMIC_STACKALLOC,
549 (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
550 (Subtarget->isTargetCOFF()
551 && !Subtarget->isTargetEnvMacho()
554 if (!UseSoftFloat && X86ScalarSSEf64) {
555 // f32 and f64 use SSE.
556 // Set up the FP register classes.
557 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
558 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
560 // Use ANDPD to simulate FABS.
561 setOperationAction(ISD::FABS , MVT::f64, Custom);
562 setOperationAction(ISD::FABS , MVT::f32, Custom);
564 // Use XORP to simulate FNEG.
565 setOperationAction(ISD::FNEG , MVT::f64, Custom);
566 setOperationAction(ISD::FNEG , MVT::f32, Custom);
568 // Use ANDPD and ORPD to simulate FCOPYSIGN.
569 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
570 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
572 // Lower this to FGETSIGNx86 plus an AND.
573 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
574 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
576 // We don't support sin/cos/fmod
577 setOperationAction(ISD::FSIN , MVT::f64, Expand);
578 setOperationAction(ISD::FCOS , MVT::f64, Expand);
579 setOperationAction(ISD::FSIN , MVT::f32, Expand);
580 setOperationAction(ISD::FCOS , MVT::f32, Expand);
582 // Expand FP immediates into loads from the stack, except for the special
584 addLegalFPImmediate(APFloat(+0.0)); // xorpd
585 addLegalFPImmediate(APFloat(+0.0f)); // xorps
586 } else if (!UseSoftFloat && X86ScalarSSEf32) {
587 // Use SSE for f32, x87 for f64.
588 // Set up the FP register classes.
589 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
590 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
592 // Use ANDPS to simulate FABS.
593 setOperationAction(ISD::FABS , MVT::f32, Custom);
595 // Use XORP to simulate FNEG.
596 setOperationAction(ISD::FNEG , MVT::f32, Custom);
598 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
600 // Use ANDPS and ORPS to simulate FCOPYSIGN.
601 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
602 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
604 // We don't support sin/cos/fmod
605 setOperationAction(ISD::FSIN , MVT::f32, Expand);
606 setOperationAction(ISD::FCOS , MVT::f32, Expand);
608 // Special cases we handle for FP constants.
609 addLegalFPImmediate(APFloat(+0.0f)); // xorps
610 addLegalFPImmediate(APFloat(+0.0)); // FLD0
611 addLegalFPImmediate(APFloat(+1.0)); // FLD1
612 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
613 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
616 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
617 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
619 } else if (!UseSoftFloat) {
620 // f32 and f64 in x87.
621 // Set up the FP register classes.
622 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
623 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
625 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
626 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
627 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
628 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
631 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
632 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
634 addLegalFPImmediate(APFloat(+0.0)); // FLD0
635 addLegalFPImmediate(APFloat(+1.0)); // FLD1
636 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
637 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
638 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
639 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
640 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
641 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
644 // We don't support FMA.
645 setOperationAction(ISD::FMA, MVT::f64, Expand);
646 setOperationAction(ISD::FMA, MVT::f32, Expand);
648 // Long double always uses X87.
650 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
651 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
652 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
654 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
655 addLegalFPImmediate(TmpFlt); // FLD0
657 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
660 APFloat TmpFlt2(+1.0);
661 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
663 addLegalFPImmediate(TmpFlt2); // FLD1
664 TmpFlt2.changeSign();
665 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
669 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
670 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
673 setOperationAction(ISD::FMA, MVT::f80, Expand);
676 // Always use a library call for pow.
677 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
678 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
679 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
681 setOperationAction(ISD::FLOG, MVT::f80, Expand);
682 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
683 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
684 setOperationAction(ISD::FEXP, MVT::f80, Expand);
685 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
687 // First set operation action for all vector types to either promote
688 // (for widening) or expand (for scalarization). Then we will selectively
689 // turn on ones that can be effectively codegen'd.
690 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
691 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
692 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
693 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
694 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
695 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
696 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
698 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
699 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
700 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
701 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
702 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
703 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
704 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
705 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
707 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
709 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
710 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
742 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
745 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
746 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
747 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
748 setTruncStoreAction((MVT::SimpleValueType)VT,
749 (MVT::SimpleValueType)InnerVT, Expand);
750 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
751 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
752 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
755 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
756 // with -msoft-float, disable use of MMX as well.
757 if (!UseSoftFloat && Subtarget->hasMMX()) {
758 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
759 // No operations on x86mmx supported, everything uses intrinsics.
762 // MMX-sized vectors (other than x86mmx) are expected to be expanded
763 // into smaller operations.
764 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
765 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
766 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
767 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
768 setOperationAction(ISD::AND, MVT::v8i8, Expand);
769 setOperationAction(ISD::AND, MVT::v4i16, Expand);
770 setOperationAction(ISD::AND, MVT::v2i32, Expand);
771 setOperationAction(ISD::AND, MVT::v1i64, Expand);
772 setOperationAction(ISD::OR, MVT::v8i8, Expand);
773 setOperationAction(ISD::OR, MVT::v4i16, Expand);
774 setOperationAction(ISD::OR, MVT::v2i32, Expand);
775 setOperationAction(ISD::OR, MVT::v1i64, Expand);
776 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
777 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
778 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
779 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
780 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
781 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
782 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
783 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
784 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
785 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
786 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
787 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
788 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
789 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
790 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
791 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
792 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
794 if (!UseSoftFloat && Subtarget->hasXMM()) {
795 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
797 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
798 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
799 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
800 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
801 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
802 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
803 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
804 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
805 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
806 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
807 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
808 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
811 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
812 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
814 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
815 // registers cannot be used even for integer operations.
816 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
817 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
818 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
819 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
821 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
822 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
823 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
824 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
825 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
826 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
827 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
828 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
829 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
830 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
831 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
832 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
833 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
834 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
835 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
836 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
838 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
839 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
840 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
841 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
843 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
844 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
845 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
846 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
847 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
849 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
850 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
851 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
852 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
853 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
855 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
856 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
857 EVT VT = (MVT::SimpleValueType)i;
858 // Do not attempt to custom lower non-power-of-2 vectors
859 if (!isPowerOf2_32(VT.getVectorNumElements()))
861 // Do not attempt to custom lower non-128-bit vectors
862 if (!VT.is128BitVector())
864 setOperationAction(ISD::BUILD_VECTOR,
865 VT.getSimpleVT().SimpleTy, Custom);
866 setOperationAction(ISD::VECTOR_SHUFFLE,
867 VT.getSimpleVT().SimpleTy, Custom);
868 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
869 VT.getSimpleVT().SimpleTy, Custom);
872 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
873 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
874 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
875 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
876 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
877 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
879 if (Subtarget->is64Bit()) {
880 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
881 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
884 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
885 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
886 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
889 // Do not attempt to promote non-128-bit vectors
890 if (!VT.is128BitVector())
893 setOperationAction(ISD::AND, SVT, Promote);
894 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
895 setOperationAction(ISD::OR, SVT, Promote);
896 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
897 setOperationAction(ISD::XOR, SVT, Promote);
898 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
899 setOperationAction(ISD::LOAD, SVT, Promote);
900 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
901 setOperationAction(ISD::SELECT, SVT, Promote);
902 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
905 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
907 // Custom lower v2i64 and v2f64 selects.
908 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
909 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
910 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
911 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
913 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
914 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
917 if (Subtarget->hasSSE41()) {
918 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
919 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
920 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
921 setOperationAction(ISD::FRINT, MVT::f32, Legal);
922 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
923 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
924 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
925 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
926 setOperationAction(ISD::FRINT, MVT::f64, Legal);
927 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
929 // FIXME: Do we need to handle scalar-to-vector here?
930 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
932 // Can turn SHL into an integer multiply.
933 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
934 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
936 // i8 and i16 vectors are custom , because the source register and source
937 // source memory operand types are not the same width. f32 vectors are
938 // custom since the immediate controlling the insert encodes additional
940 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
941 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
942 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
943 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
945 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
946 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
947 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
948 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
950 if (Subtarget->is64Bit()) {
951 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
952 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
956 if (Subtarget->hasSSE2()) {
957 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
958 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
959 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
961 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
962 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
963 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
965 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
966 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
969 if (Subtarget->hasSSE42())
970 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
972 if (!UseSoftFloat && Subtarget->hasAVX()) {
973 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
974 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
975 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
976 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
977 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
979 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
980 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
981 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
983 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
984 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
985 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
986 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
987 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
988 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
990 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
991 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
992 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
993 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
994 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
995 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
997 // Custom lower several nodes for 256-bit types.
998 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
999 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1000 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1003 // Extract subvector is special because the value type
1004 // (result) is 128-bit but the source is 256-bit wide.
1005 if (VT.is128BitVector())
1006 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1008 // Do not attempt to custom lower other non-256-bit vectors
1009 if (!VT.is256BitVector())
1012 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1013 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1014 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1015 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1016 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1017 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1020 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1021 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1022 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1025 // Do not attempt to promote non-256-bit vectors
1026 if (!VT.is256BitVector())
1029 setOperationAction(ISD::AND, SVT, Promote);
1030 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1031 setOperationAction(ISD::OR, SVT, Promote);
1032 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1033 setOperationAction(ISD::XOR, SVT, Promote);
1034 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1035 setOperationAction(ISD::LOAD, SVT, Promote);
1036 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1037 setOperationAction(ISD::SELECT, SVT, Promote);
1038 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1042 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1043 // of this type with custom code.
1044 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1045 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1046 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1049 // We want to custom lower some of our intrinsics.
1050 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1053 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1054 // handle type legalization for these operations here.
1056 // FIXME: We really should do custom legalization for addition and
1057 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1058 // than generic legalization for 64-bit multiplication-with-overflow, though.
1059 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1060 // Add/Sub/Mul with overflow operations are custom lowered.
1062 setOperationAction(ISD::SADDO, VT, Custom);
1063 setOperationAction(ISD::UADDO, VT, Custom);
1064 setOperationAction(ISD::SSUBO, VT, Custom);
1065 setOperationAction(ISD::USUBO, VT, Custom);
1066 setOperationAction(ISD::SMULO, VT, Custom);
1067 setOperationAction(ISD::UMULO, VT, Custom);
1070 // There are no 8-bit 3-address imul/mul instructions
1071 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1072 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1074 if (!Subtarget->is64Bit()) {
1075 // These libcalls are not available in 32-bit.
1076 setLibcallName(RTLIB::SHL_I128, 0);
1077 setLibcallName(RTLIB::SRL_I128, 0);
1078 setLibcallName(RTLIB::SRA_I128, 0);
1081 // We have target-specific dag combine patterns for the following nodes:
1082 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1083 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1084 setTargetDAGCombine(ISD::BUILD_VECTOR);
1085 setTargetDAGCombine(ISD::SELECT);
1086 setTargetDAGCombine(ISD::SHL);
1087 setTargetDAGCombine(ISD::SRA);
1088 setTargetDAGCombine(ISD::SRL);
1089 setTargetDAGCombine(ISD::OR);
1090 setTargetDAGCombine(ISD::AND);
1091 setTargetDAGCombine(ISD::ADD);
1092 setTargetDAGCombine(ISD::SUB);
1093 setTargetDAGCombine(ISD::STORE);
1094 setTargetDAGCombine(ISD::ZERO_EXTEND);
1095 setTargetDAGCombine(ISD::SINT_TO_FP);
1096 if (Subtarget->is64Bit())
1097 setTargetDAGCombine(ISD::MUL);
1099 computeRegisterProperties();
1101 // On Darwin, -Os means optimize for size without hurting performance,
1102 // do not reduce the limit.
1103 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1104 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1105 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1106 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1107 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1108 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1109 setPrefLoopAlignment(16);
1110 benefitFromCodePlacementOpt = true;
1112 setPrefFunctionAlignment(4);
1116 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1121 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1122 /// the desired ByVal argument alignment.
1123 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1126 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1127 if (VTy->getBitWidth() == 128)
1129 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1130 unsigned EltAlign = 0;
1131 getMaxByValAlign(ATy->getElementType(), EltAlign);
1132 if (EltAlign > MaxAlign)
1133 MaxAlign = EltAlign;
1134 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1135 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1136 unsigned EltAlign = 0;
1137 getMaxByValAlign(STy->getElementType(i), EltAlign);
1138 if (EltAlign > MaxAlign)
1139 MaxAlign = EltAlign;
1147 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1148 /// function arguments in the caller parameter area. For X86, aggregates
1149 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1150 /// are at 4-byte boundaries.
1151 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1152 if (Subtarget->is64Bit()) {
1153 // Max of 8 and alignment of type.
1154 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1161 if (Subtarget->hasXMM())
1162 getMaxByValAlign(Ty, Align);
1166 /// getOptimalMemOpType - Returns the target specific optimal type for load
1167 /// and store operations as a result of memset, memcpy, and memmove
1168 /// lowering. If DstAlign is zero that means it's safe to destination
1169 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1170 /// means there isn't a need to check it against alignment requirement,
1171 /// probably because the source does not need to be loaded. If
1172 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1173 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1174 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1175 /// constant so it does not need to be loaded.
1176 /// It returns EVT::Other if the type should be determined using generic
1177 /// target-independent logic.
1179 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1180 unsigned DstAlign, unsigned SrcAlign,
1181 bool NonScalarIntSafe,
1183 MachineFunction &MF) const {
1184 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1185 // linux. This is because the stack realignment code can't handle certain
1186 // cases like PR2962. This should be removed when PR2962 is fixed.
1187 const Function *F = MF.getFunction();
1188 if (NonScalarIntSafe &&
1189 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1191 (Subtarget->isUnalignedMemAccessFast() ||
1192 ((DstAlign == 0 || DstAlign >= 16) &&
1193 (SrcAlign == 0 || SrcAlign >= 16))) &&
1194 Subtarget->getStackAlignment() >= 16) {
1195 if (Subtarget->hasSSE2())
1197 if (Subtarget->hasSSE1())
1199 } else if (!MemcpyStrSrc && Size >= 8 &&
1200 !Subtarget->is64Bit() &&
1201 Subtarget->getStackAlignment() >= 8 &&
1202 Subtarget->hasXMMInt()) {
1203 // Do not use f64 to lower memcpy if source is string constant. It's
1204 // better to use i32 to avoid the loads.
1208 if (Subtarget->is64Bit() && Size >= 8)
1213 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1214 /// current function. The returned value is a member of the
1215 /// MachineJumpTableInfo::JTEntryKind enum.
1216 unsigned X86TargetLowering::getJumpTableEncoding() const {
1217 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1219 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1220 Subtarget->isPICStyleGOT())
1221 return MachineJumpTableInfo::EK_Custom32;
1223 // Otherwise, use the normal jump table encoding heuristics.
1224 return TargetLowering::getJumpTableEncoding();
1228 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1229 const MachineBasicBlock *MBB,
1230 unsigned uid,MCContext &Ctx) const{
1231 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1232 Subtarget->isPICStyleGOT());
1233 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1235 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1236 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1239 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1241 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1242 SelectionDAG &DAG) const {
1243 if (!Subtarget->is64Bit())
1244 // This doesn't have DebugLoc associated with it, but is not really the
1245 // same as a Register.
1246 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1250 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1251 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1253 const MCExpr *X86TargetLowering::
1254 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1255 MCContext &Ctx) const {
1256 // X86-64 uses RIP relative addressing based on the jump table label.
1257 if (Subtarget->isPICStyleRIPRel())
1258 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1260 // Otherwise, the reference is relative to the PIC base.
1261 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1264 // FIXME: Why this routine is here? Move to RegInfo!
1265 std::pair<const TargetRegisterClass*, uint8_t>
1266 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1267 const TargetRegisterClass *RRC = 0;
1269 switch (VT.getSimpleVT().SimpleTy) {
1271 return TargetLowering::findRepresentativeClass(VT);
1272 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1273 RRC = (Subtarget->is64Bit()
1274 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1277 RRC = X86::VR64RegisterClass;
1279 case MVT::f32: case MVT::f64:
1280 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1281 case MVT::v4f32: case MVT::v2f64:
1282 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1284 RRC = X86::VR128RegisterClass;
1287 return std::make_pair(RRC, Cost);
1290 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1291 unsigned &Offset) const {
1292 if (!Subtarget->isTargetLinux())
1295 if (Subtarget->is64Bit()) {
1296 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1298 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1311 //===----------------------------------------------------------------------===//
1312 // Return Value Calling Convention Implementation
1313 //===----------------------------------------------------------------------===//
1315 #include "X86GenCallingConv.inc"
1318 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1319 MachineFunction &MF, bool isVarArg,
1320 const SmallVectorImpl<ISD::OutputArg> &Outs,
1321 LLVMContext &Context) const {
1322 SmallVector<CCValAssign, 16> RVLocs;
1323 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1325 return CCInfo.CheckReturn(Outs, RetCC_X86);
1329 X86TargetLowering::LowerReturn(SDValue Chain,
1330 CallingConv::ID CallConv, bool isVarArg,
1331 const SmallVectorImpl<ISD::OutputArg> &Outs,
1332 const SmallVectorImpl<SDValue> &OutVals,
1333 DebugLoc dl, SelectionDAG &DAG) const {
1334 MachineFunction &MF = DAG.getMachineFunction();
1335 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1337 SmallVector<CCValAssign, 16> RVLocs;
1338 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1339 RVLocs, *DAG.getContext());
1340 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1342 // Add the regs to the liveout set for the function.
1343 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1344 for (unsigned i = 0; i != RVLocs.size(); ++i)
1345 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1346 MRI.addLiveOut(RVLocs[i].getLocReg());
1350 SmallVector<SDValue, 6> RetOps;
1351 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1352 // Operand #1 = Bytes To Pop
1353 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1356 // Copy the result values into the output registers.
1357 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1358 CCValAssign &VA = RVLocs[i];
1359 assert(VA.isRegLoc() && "Can only return in registers!");
1360 SDValue ValToCopy = OutVals[i];
1361 EVT ValVT = ValToCopy.getValueType();
1363 // If this is x86-64, and we disabled SSE, we can't return FP values,
1364 // or SSE or MMX vectors.
1365 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1366 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1367 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1368 report_fatal_error("SSE register return with SSE disabled");
1370 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1371 // llvm-gcc has never done it right and no one has noticed, so this
1372 // should be OK for now.
1373 if (ValVT == MVT::f64 &&
1374 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1375 report_fatal_error("SSE2 register return with SSE2 disabled");
1377 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1378 // the RET instruction and handled by the FP Stackifier.
1379 if (VA.getLocReg() == X86::ST0 ||
1380 VA.getLocReg() == X86::ST1) {
1381 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1382 // change the value to the FP stack register class.
1383 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1384 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1385 RetOps.push_back(ValToCopy);
1386 // Don't emit a copytoreg.
1390 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1391 // which is returned in RAX / RDX.
1392 if (Subtarget->is64Bit()) {
1393 if (ValVT == MVT::x86mmx) {
1394 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1395 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1396 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1398 // If we don't have SSE2 available, convert to v4f32 so the generated
1399 // register is legal.
1400 if (!Subtarget->hasSSE2())
1401 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1406 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1407 Flag = Chain.getValue(1);
1410 // The x86-64 ABI for returning structs by value requires that we copy
1411 // the sret argument into %rax for the return. We saved the argument into
1412 // a virtual register in the entry block, so now we copy the value out
1414 if (Subtarget->is64Bit() &&
1415 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1416 MachineFunction &MF = DAG.getMachineFunction();
1417 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1418 unsigned Reg = FuncInfo->getSRetReturnReg();
1420 "SRetReturnReg should have been set in LowerFormalArguments().");
1421 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1423 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1424 Flag = Chain.getValue(1);
1426 // RAX now acts like a return value.
1427 MRI.addLiveOut(X86::RAX);
1430 RetOps[0] = Chain; // Update chain.
1432 // Add the flag if we have it.
1434 RetOps.push_back(Flag);
1436 return DAG.getNode(X86ISD::RET_FLAG, dl,
1437 MVT::Other, &RetOps[0], RetOps.size());
1440 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1441 if (N->getNumValues() != 1)
1443 if (!N->hasNUsesOfValue(1, 0))
1446 SDNode *Copy = *N->use_begin();
1447 if (Copy->getOpcode() != ISD::CopyToReg &&
1448 Copy->getOpcode() != ISD::FP_EXTEND)
1451 bool HasRet = false;
1452 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1454 if (UI->getOpcode() != X86ISD::RET_FLAG)
1463 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1464 ISD::NodeType ExtendKind) const {
1466 // TODO: Is this also valid on 32-bit?
1467 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1468 ReturnMVT = MVT::i8;
1470 ReturnMVT = MVT::i32;
1472 EVT MinVT = getRegisterType(Context, ReturnMVT);
1473 return VT.bitsLT(MinVT) ? MinVT : VT;
1476 /// LowerCallResult - Lower the result values of a call into the
1477 /// appropriate copies out of appropriate physical registers.
1480 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1481 CallingConv::ID CallConv, bool isVarArg,
1482 const SmallVectorImpl<ISD::InputArg> &Ins,
1483 DebugLoc dl, SelectionDAG &DAG,
1484 SmallVectorImpl<SDValue> &InVals) const {
1486 // Assign locations to each value returned by this call.
1487 SmallVector<CCValAssign, 16> RVLocs;
1488 bool Is64Bit = Subtarget->is64Bit();
1489 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1490 getTargetMachine(), RVLocs, *DAG.getContext());
1491 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1493 // Copy all of the result registers out of their specified physreg.
1494 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1495 CCValAssign &VA = RVLocs[i];
1496 EVT CopyVT = VA.getValVT();
1498 // If this is x86-64, and we disabled SSE, we can't return FP values
1499 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1500 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1501 report_fatal_error("SSE register return with SSE disabled");
1506 // If this is a call to a function that returns an fp value on the floating
1507 // point stack, we must guarantee the the value is popped from the stack, so
1508 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1509 // if the return value is not used. We use the FpPOP_RETVAL instruction
1511 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1512 // If we prefer to use the value in xmm registers, copy it out as f80 and
1513 // use a truncate to move it from fp stack reg to xmm reg.
1514 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1515 SDValue Ops[] = { Chain, InFlag };
1516 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1517 MVT::Other, MVT::Glue, Ops, 2), 1);
1518 Val = Chain.getValue(0);
1520 // Round the f80 to the right size, which also moves it to the appropriate
1522 if (CopyVT != VA.getValVT())
1523 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1524 // This truncation won't change the value.
1525 DAG.getIntPtrConstant(1));
1527 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1528 CopyVT, InFlag).getValue(1);
1529 Val = Chain.getValue(0);
1531 InFlag = Chain.getValue(2);
1532 InVals.push_back(Val);
1539 //===----------------------------------------------------------------------===//
1540 // C & StdCall & Fast Calling Convention implementation
1541 //===----------------------------------------------------------------------===//
1542 // StdCall calling convention seems to be standard for many Windows' API
1543 // routines and around. It differs from C calling convention just a little:
1544 // callee should clean up the stack, not caller. Symbols should be also
1545 // decorated in some fancy way :) It doesn't support any vector arguments.
1546 // For info on fast calling convention see Fast Calling Convention (tail call)
1547 // implementation LowerX86_32FastCCCallTo.
1549 /// CallIsStructReturn - Determines whether a call uses struct return
1551 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1555 return Outs[0].Flags.isSRet();
1558 /// ArgsAreStructReturn - Determines whether a function uses struct
1559 /// return semantics.
1561 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1565 return Ins[0].Flags.isSRet();
1568 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1569 /// by "Src" to address "Dst" with size and alignment information specified by
1570 /// the specific parameter attribute. The copy will be passed as a byval
1571 /// function parameter.
1573 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1574 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1576 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1578 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1579 /*isVolatile*/false, /*AlwaysInline=*/true,
1580 MachinePointerInfo(), MachinePointerInfo());
1583 /// IsTailCallConvention - Return true if the calling convention is one that
1584 /// supports tail call optimization.
1585 static bool IsTailCallConvention(CallingConv::ID CC) {
1586 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1589 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1590 if (!CI->isTailCall())
1594 CallingConv::ID CalleeCC = CS.getCallingConv();
1595 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1601 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1602 /// a tailcall target by changing its ABI.
1603 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1604 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1608 X86TargetLowering::LowerMemArgument(SDValue Chain,
1609 CallingConv::ID CallConv,
1610 const SmallVectorImpl<ISD::InputArg> &Ins,
1611 DebugLoc dl, SelectionDAG &DAG,
1612 const CCValAssign &VA,
1613 MachineFrameInfo *MFI,
1615 // Create the nodes corresponding to a load from this parameter slot.
1616 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1617 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1618 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1621 // If value is passed by pointer we have address passed instead of the value
1623 if (VA.getLocInfo() == CCValAssign::Indirect)
1624 ValVT = VA.getLocVT();
1626 ValVT = VA.getValVT();
1628 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1629 // changed with more analysis.
1630 // In case of tail call optimization mark all arguments mutable. Since they
1631 // could be overwritten by lowering of arguments in case of a tail call.
1632 if (Flags.isByVal()) {
1633 unsigned Bytes = Flags.getByValSize();
1634 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1635 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1636 return DAG.getFrameIndex(FI, getPointerTy());
1638 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1639 VA.getLocMemOffset(), isImmutable);
1640 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1641 return DAG.getLoad(ValVT, dl, Chain, FIN,
1642 MachinePointerInfo::getFixedStack(FI),
1648 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1649 CallingConv::ID CallConv,
1651 const SmallVectorImpl<ISD::InputArg> &Ins,
1654 SmallVectorImpl<SDValue> &InVals)
1656 MachineFunction &MF = DAG.getMachineFunction();
1657 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1659 const Function* Fn = MF.getFunction();
1660 if (Fn->hasExternalLinkage() &&
1661 Subtarget->isTargetCygMing() &&
1662 Fn->getName() == "main")
1663 FuncInfo->setForceFramePointer(true);
1665 MachineFrameInfo *MFI = MF.getFrameInfo();
1666 bool Is64Bit = Subtarget->is64Bit();
1667 bool IsWin64 = Subtarget->isTargetWin64();
1669 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1670 "Var args not supported with calling convention fastcc or ghc");
1672 // Assign locations to all of the incoming arguments.
1673 SmallVector<CCValAssign, 16> ArgLocs;
1674 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1675 ArgLocs, *DAG.getContext());
1677 // Allocate shadow area for Win64
1679 CCInfo.AllocateStack(32, 8);
1682 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1684 unsigned LastVal = ~0U;
1686 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1687 CCValAssign &VA = ArgLocs[i];
1688 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1690 assert(VA.getValNo() != LastVal &&
1691 "Don't support value assigned to multiple locs yet");
1692 LastVal = VA.getValNo();
1694 if (VA.isRegLoc()) {
1695 EVT RegVT = VA.getLocVT();
1696 TargetRegisterClass *RC = NULL;
1697 if (RegVT == MVT::i32)
1698 RC = X86::GR32RegisterClass;
1699 else if (Is64Bit && RegVT == MVT::i64)
1700 RC = X86::GR64RegisterClass;
1701 else if (RegVT == MVT::f32)
1702 RC = X86::FR32RegisterClass;
1703 else if (RegVT == MVT::f64)
1704 RC = X86::FR64RegisterClass;
1705 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1706 RC = X86::VR256RegisterClass;
1707 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1708 RC = X86::VR128RegisterClass;
1709 else if (RegVT == MVT::x86mmx)
1710 RC = X86::VR64RegisterClass;
1712 llvm_unreachable("Unknown argument type!");
1714 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1715 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1717 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1718 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1720 if (VA.getLocInfo() == CCValAssign::SExt)
1721 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1722 DAG.getValueType(VA.getValVT()));
1723 else if (VA.getLocInfo() == CCValAssign::ZExt)
1724 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1725 DAG.getValueType(VA.getValVT()));
1726 else if (VA.getLocInfo() == CCValAssign::BCvt)
1727 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1729 if (VA.isExtInLoc()) {
1730 // Handle MMX values passed in XMM regs.
1731 if (RegVT.isVector()) {
1732 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1735 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1738 assert(VA.isMemLoc());
1739 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1742 // If value is passed via pointer - do a load.
1743 if (VA.getLocInfo() == CCValAssign::Indirect)
1744 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1745 MachinePointerInfo(), false, false, 0);
1747 InVals.push_back(ArgValue);
1750 // The x86-64 ABI for returning structs by value requires that we copy
1751 // the sret argument into %rax for the return. Save the argument into
1752 // a virtual register so that we can access it from the return points.
1753 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1754 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1755 unsigned Reg = FuncInfo->getSRetReturnReg();
1757 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1758 FuncInfo->setSRetReturnReg(Reg);
1760 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1761 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1764 unsigned StackSize = CCInfo.getNextStackOffset();
1765 // Align stack specially for tail calls.
1766 if (FuncIsMadeTailCallSafe(CallConv))
1767 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1769 // If the function takes variable number of arguments, make a frame index for
1770 // the start of the first vararg value... for expansion of llvm.va_start.
1772 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1773 CallConv != CallingConv::X86_ThisCall)) {
1774 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1777 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1779 // FIXME: We should really autogenerate these arrays
1780 static const unsigned GPR64ArgRegsWin64[] = {
1781 X86::RCX, X86::RDX, X86::R8, X86::R9
1783 static const unsigned GPR64ArgRegs64Bit[] = {
1784 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1786 static const unsigned XMMArgRegs64Bit[] = {
1787 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1788 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1790 const unsigned *GPR64ArgRegs;
1791 unsigned NumXMMRegs = 0;
1794 // The XMM registers which might contain var arg parameters are shadowed
1795 // in their paired GPR. So we only need to save the GPR to their home
1797 TotalNumIntRegs = 4;
1798 GPR64ArgRegs = GPR64ArgRegsWin64;
1800 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1801 GPR64ArgRegs = GPR64ArgRegs64Bit;
1803 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1805 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1808 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1809 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1810 "SSE register cannot be used when SSE is disabled!");
1811 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1812 "SSE register cannot be used when SSE is disabled!");
1813 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1814 // Kernel mode asks for SSE to be disabled, so don't push them
1816 TotalNumXMMRegs = 0;
1819 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1820 // Get to the caller-allocated home save location. Add 8 to account
1821 // for the return address.
1822 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1823 FuncInfo->setRegSaveFrameIndex(
1824 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1825 // Fixup to set vararg frame on shadow area (4 x i64).
1827 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1829 // For X86-64, if there are vararg parameters that are passed via
1830 // registers, then we must store them to their spots on the stack so they
1831 // may be loaded by deferencing the result of va_next.
1832 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1833 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1834 FuncInfo->setRegSaveFrameIndex(
1835 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1839 // Store the integer parameter registers.
1840 SmallVector<SDValue, 8> MemOps;
1841 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1843 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1844 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1845 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1846 DAG.getIntPtrConstant(Offset));
1847 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1848 X86::GR64RegisterClass);
1849 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1851 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1852 MachinePointerInfo::getFixedStack(
1853 FuncInfo->getRegSaveFrameIndex(), Offset),
1855 MemOps.push_back(Store);
1859 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1860 // Now store the XMM (fp + vector) parameter registers.
1861 SmallVector<SDValue, 11> SaveXMMOps;
1862 SaveXMMOps.push_back(Chain);
1864 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1865 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1866 SaveXMMOps.push_back(ALVal);
1868 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1869 FuncInfo->getRegSaveFrameIndex()));
1870 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1871 FuncInfo->getVarArgsFPOffset()));
1873 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1874 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1875 X86::VR128RegisterClass);
1876 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1877 SaveXMMOps.push_back(Val);
1879 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1881 &SaveXMMOps[0], SaveXMMOps.size()));
1884 if (!MemOps.empty())
1885 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1886 &MemOps[0], MemOps.size());
1890 // Some CCs need callee pop.
1891 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1892 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1894 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1895 // If this is an sret function, the return should pop the hidden pointer.
1896 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1897 FuncInfo->setBytesToPopOnReturn(4);
1901 // RegSaveFrameIndex is X86-64 only.
1902 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1903 if (CallConv == CallingConv::X86_FastCall ||
1904 CallConv == CallingConv::X86_ThisCall)
1905 // fastcc functions can't have varargs.
1906 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1913 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1914 SDValue StackPtr, SDValue Arg,
1915 DebugLoc dl, SelectionDAG &DAG,
1916 const CCValAssign &VA,
1917 ISD::ArgFlagsTy Flags) const {
1918 unsigned LocMemOffset = VA.getLocMemOffset();
1919 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1920 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1921 if (Flags.isByVal())
1922 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1924 return DAG.getStore(Chain, dl, Arg, PtrOff,
1925 MachinePointerInfo::getStack(LocMemOffset),
1929 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1930 /// optimization is performed and it is required.
1932 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1933 SDValue &OutRetAddr, SDValue Chain,
1934 bool IsTailCall, bool Is64Bit,
1935 int FPDiff, DebugLoc dl) const {
1936 // Adjust the Return address stack slot.
1937 EVT VT = getPointerTy();
1938 OutRetAddr = getReturnAddressFrameIndex(DAG);
1940 // Load the "old" Return address.
1941 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1943 return SDValue(OutRetAddr.getNode(), 1);
1946 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1947 /// optimization is performed and it is required (FPDiff!=0).
1949 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1950 SDValue Chain, SDValue RetAddrFrIdx,
1951 bool Is64Bit, int FPDiff, DebugLoc dl) {
1952 // Store the return address to the appropriate stack slot.
1953 if (!FPDiff) return Chain;
1954 // Calculate the new stack slot for the return address.
1955 int SlotSize = Is64Bit ? 8 : 4;
1956 int NewReturnAddrFI =
1957 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1958 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1959 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1960 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1961 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1967 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1968 CallingConv::ID CallConv, bool isVarArg,
1970 const SmallVectorImpl<ISD::OutputArg> &Outs,
1971 const SmallVectorImpl<SDValue> &OutVals,
1972 const SmallVectorImpl<ISD::InputArg> &Ins,
1973 DebugLoc dl, SelectionDAG &DAG,
1974 SmallVectorImpl<SDValue> &InVals) const {
1975 MachineFunction &MF = DAG.getMachineFunction();
1976 bool Is64Bit = Subtarget->is64Bit();
1977 bool IsWin64 = Subtarget->isTargetWin64();
1978 bool IsStructRet = CallIsStructReturn(Outs);
1979 bool IsSibcall = false;
1982 // Check if it's really possible to do a tail call.
1983 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1984 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1985 Outs, OutVals, Ins, DAG);
1987 // Sibcalls are automatically detected tailcalls which do not require
1989 if (!GuaranteedTailCallOpt && isTailCall)
1996 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1997 "Var args not supported with calling convention fastcc or ghc");
1999 // Analyze operands of the call, assigning locations to each operand.
2000 SmallVector<CCValAssign, 16> ArgLocs;
2001 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2002 ArgLocs, *DAG.getContext());
2004 // Allocate shadow area for Win64
2006 CCInfo.AllocateStack(32, 8);
2009 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2011 // Get a count of how many bytes are to be pushed on the stack.
2012 unsigned NumBytes = CCInfo.getNextStackOffset();
2014 // This is a sibcall. The memory operands are available in caller's
2015 // own caller's stack.
2017 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2018 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2021 if (isTailCall && !IsSibcall) {
2022 // Lower arguments at fp - stackoffset + fpdiff.
2023 unsigned NumBytesCallerPushed =
2024 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2025 FPDiff = NumBytesCallerPushed - NumBytes;
2027 // Set the delta of movement of the returnaddr stackslot.
2028 // But only set if delta is greater than previous delta.
2029 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2030 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2034 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2036 SDValue RetAddrFrIdx;
2037 // Load return address for tail calls.
2038 if (isTailCall && FPDiff)
2039 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2040 Is64Bit, FPDiff, dl);
2042 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2043 SmallVector<SDValue, 8> MemOpChains;
2046 // Walk the register/memloc assignments, inserting copies/loads. In the case
2047 // of tail call optimization arguments are handle later.
2048 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2049 CCValAssign &VA = ArgLocs[i];
2050 EVT RegVT = VA.getLocVT();
2051 SDValue Arg = OutVals[i];
2052 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2053 bool isByVal = Flags.isByVal();
2055 // Promote the value if needed.
2056 switch (VA.getLocInfo()) {
2057 default: llvm_unreachable("Unknown loc info!");
2058 case CCValAssign::Full: break;
2059 case CCValAssign::SExt:
2060 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2062 case CCValAssign::ZExt:
2063 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2065 case CCValAssign::AExt:
2066 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2067 // Special case: passing MMX values in XMM registers.
2068 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2069 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2070 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2072 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2074 case CCValAssign::BCvt:
2075 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2077 case CCValAssign::Indirect: {
2078 // Store the argument.
2079 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2080 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2081 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2082 MachinePointerInfo::getFixedStack(FI),
2089 if (VA.isRegLoc()) {
2090 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2091 if (isVarArg && IsWin64) {
2092 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2093 // shadow reg if callee is a varargs function.
2094 unsigned ShadowReg = 0;
2095 switch (VA.getLocReg()) {
2096 case X86::XMM0: ShadowReg = X86::RCX; break;
2097 case X86::XMM1: ShadowReg = X86::RDX; break;
2098 case X86::XMM2: ShadowReg = X86::R8; break;
2099 case X86::XMM3: ShadowReg = X86::R9; break;
2102 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2104 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2105 assert(VA.isMemLoc());
2106 if (StackPtr.getNode() == 0)
2107 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2108 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2109 dl, DAG, VA, Flags));
2113 if (!MemOpChains.empty())
2114 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2115 &MemOpChains[0], MemOpChains.size());
2117 // Build a sequence of copy-to-reg nodes chained together with token chain
2118 // and flag operands which copy the outgoing args into registers.
2120 // Tail call byval lowering might overwrite argument registers so in case of
2121 // tail call optimization the copies to registers are lowered later.
2123 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2124 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2125 RegsToPass[i].second, InFlag);
2126 InFlag = Chain.getValue(1);
2129 if (Subtarget->isPICStyleGOT()) {
2130 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2133 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2134 DAG.getNode(X86ISD::GlobalBaseReg,
2135 DebugLoc(), getPointerTy()),
2137 InFlag = Chain.getValue(1);
2139 // If we are tail calling and generating PIC/GOT style code load the
2140 // address of the callee into ECX. The value in ecx is used as target of
2141 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2142 // for tail calls on PIC/GOT architectures. Normally we would just put the
2143 // address of GOT into ebx and then call target@PLT. But for tail calls
2144 // ebx would be restored (since ebx is callee saved) before jumping to the
2147 // Note: The actual moving to ECX is done further down.
2148 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2149 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2150 !G->getGlobal()->hasProtectedVisibility())
2151 Callee = LowerGlobalAddress(Callee, DAG);
2152 else if (isa<ExternalSymbolSDNode>(Callee))
2153 Callee = LowerExternalSymbol(Callee, DAG);
2157 if (Is64Bit && isVarArg && !IsWin64) {
2158 // From AMD64 ABI document:
2159 // For calls that may call functions that use varargs or stdargs
2160 // (prototype-less calls or calls to functions containing ellipsis (...) in
2161 // the declaration) %al is used as hidden argument to specify the number
2162 // of SSE registers used. The contents of %al do not need to match exactly
2163 // the number of registers, but must be an ubound on the number of SSE
2164 // registers used and is in the range 0 - 8 inclusive.
2166 // Count the number of XMM registers allocated.
2167 static const unsigned XMMArgRegs[] = {
2168 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2169 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2171 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2172 assert((Subtarget->hasXMM() || !NumXMMRegs)
2173 && "SSE registers cannot be used when SSE is disabled");
2175 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2176 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2177 InFlag = Chain.getValue(1);
2181 // For tail calls lower the arguments to the 'real' stack slot.
2183 // Force all the incoming stack arguments to be loaded from the stack
2184 // before any new outgoing arguments are stored to the stack, because the
2185 // outgoing stack slots may alias the incoming argument stack slots, and
2186 // the alias isn't otherwise explicit. This is slightly more conservative
2187 // than necessary, because it means that each store effectively depends
2188 // on every argument instead of just those arguments it would clobber.
2189 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2191 SmallVector<SDValue, 8> MemOpChains2;
2194 // Do not flag preceding copytoreg stuff together with the following stuff.
2196 if (GuaranteedTailCallOpt) {
2197 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2198 CCValAssign &VA = ArgLocs[i];
2201 assert(VA.isMemLoc());
2202 SDValue Arg = OutVals[i];
2203 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2204 // Create frame index.
2205 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2206 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2207 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2208 FIN = DAG.getFrameIndex(FI, getPointerTy());
2210 if (Flags.isByVal()) {
2211 // Copy relative to framepointer.
2212 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2213 if (StackPtr.getNode() == 0)
2214 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2216 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2218 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2222 // Store relative to framepointer.
2223 MemOpChains2.push_back(
2224 DAG.getStore(ArgChain, dl, Arg, FIN,
2225 MachinePointerInfo::getFixedStack(FI),
2231 if (!MemOpChains2.empty())
2232 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2233 &MemOpChains2[0], MemOpChains2.size());
2235 // Copy arguments to their registers.
2236 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2237 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2238 RegsToPass[i].second, InFlag);
2239 InFlag = Chain.getValue(1);
2243 // Store the return address to the appropriate stack slot.
2244 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2248 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2249 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2250 // In the 64-bit large code model, we have to make all calls
2251 // through a register, since the call instruction's 32-bit
2252 // pc-relative offset may not be large enough to hold the whole
2254 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2255 // If the callee is a GlobalAddress node (quite common, every direct call
2256 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2259 // We should use extra load for direct calls to dllimported functions in
2261 const GlobalValue *GV = G->getGlobal();
2262 if (!GV->hasDLLImportLinkage()) {
2263 unsigned char OpFlags = 0;
2264 bool ExtraLoad = false;
2265 unsigned WrapperKind = ISD::DELETED_NODE;
2267 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2268 // external symbols most go through the PLT in PIC mode. If the symbol
2269 // has hidden or protected visibility, or if it is static or local, then
2270 // we don't need to use the PLT - we can directly call it.
2271 if (Subtarget->isTargetELF() &&
2272 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2273 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2274 OpFlags = X86II::MO_PLT;
2275 } else if (Subtarget->isPICStyleStubAny() &&
2276 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2277 (!Subtarget->getTargetTriple().isMacOSX() ||
2278 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2279 // PC-relative references to external symbols should go through $stub,
2280 // unless we're building with the leopard linker or later, which
2281 // automatically synthesizes these stubs.
2282 OpFlags = X86II::MO_DARWIN_STUB;
2283 } else if (Subtarget->isPICStyleRIPRel() &&
2284 isa<Function>(GV) &&
2285 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2286 // If the function is marked as non-lazy, generate an indirect call
2287 // which loads from the GOT directly. This avoids runtime overhead
2288 // at the cost of eager binding (and one extra byte of encoding).
2289 OpFlags = X86II::MO_GOTPCREL;
2290 WrapperKind = X86ISD::WrapperRIP;
2294 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2295 G->getOffset(), OpFlags);
2297 // Add a wrapper if needed.
2298 if (WrapperKind != ISD::DELETED_NODE)
2299 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2300 // Add extra indirection if needed.
2302 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2303 MachinePointerInfo::getGOT(),
2306 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2307 unsigned char OpFlags = 0;
2309 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2310 // external symbols should go through the PLT.
2311 if (Subtarget->isTargetELF() &&
2312 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2313 OpFlags = X86II::MO_PLT;
2314 } else if (Subtarget->isPICStyleStubAny() &&
2315 (!Subtarget->getTargetTriple().isMacOSX() ||
2316 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2317 // PC-relative references to external symbols should go through $stub,
2318 // unless we're building with the leopard linker or later, which
2319 // automatically synthesizes these stubs.
2320 OpFlags = X86II::MO_DARWIN_STUB;
2323 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2327 // Returns a chain & a flag for retval copy to use.
2328 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2329 SmallVector<SDValue, 8> Ops;
2331 if (!IsSibcall && isTailCall) {
2332 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2333 DAG.getIntPtrConstant(0, true), InFlag);
2334 InFlag = Chain.getValue(1);
2337 Ops.push_back(Chain);
2338 Ops.push_back(Callee);
2341 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2343 // Add argument registers to the end of the list so that they are known live
2345 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2346 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2347 RegsToPass[i].second.getValueType()));
2349 // Add an implicit use GOT pointer in EBX.
2350 if (!isTailCall && Subtarget->isPICStyleGOT())
2351 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2353 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2354 if (Is64Bit && isVarArg && !IsWin64)
2355 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2357 if (InFlag.getNode())
2358 Ops.push_back(InFlag);
2362 //// If this is the first return lowered for this function, add the regs
2363 //// to the liveout set for the function.
2364 // This isn't right, although it's probably harmless on x86; liveouts
2365 // should be computed from returns not tail calls. Consider a void
2366 // function making a tail call to a function returning int.
2367 return DAG.getNode(X86ISD::TC_RETURN, dl,
2368 NodeTys, &Ops[0], Ops.size());
2371 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2372 InFlag = Chain.getValue(1);
2374 // Create the CALLSEQ_END node.
2375 unsigned NumBytesForCalleeToPush;
2376 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2377 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2378 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2379 // If this is a call to a struct-return function, the callee
2380 // pops the hidden struct pointer, so we have to push it back.
2381 // This is common for Darwin/X86, Linux & Mingw32 targets.
2382 NumBytesForCalleeToPush = 4;
2384 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2386 // Returns a flag for retval copy to use.
2388 Chain = DAG.getCALLSEQ_END(Chain,
2389 DAG.getIntPtrConstant(NumBytes, true),
2390 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2393 InFlag = Chain.getValue(1);
2396 // Handle result values, copying them out of physregs into vregs that we
2398 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2399 Ins, dl, DAG, InVals);
2403 //===----------------------------------------------------------------------===//
2404 // Fast Calling Convention (tail call) implementation
2405 //===----------------------------------------------------------------------===//
2407 // Like std call, callee cleans arguments, convention except that ECX is
2408 // reserved for storing the tail called function address. Only 2 registers are
2409 // free for argument passing (inreg). Tail call optimization is performed
2411 // * tailcallopt is enabled
2412 // * caller/callee are fastcc
2413 // On X86_64 architecture with GOT-style position independent code only local
2414 // (within module) calls are supported at the moment.
2415 // To keep the stack aligned according to platform abi the function
2416 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2417 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2418 // If a tail called function callee has more arguments than the caller the
2419 // caller needs to make sure that there is room to move the RETADDR to. This is
2420 // achieved by reserving an area the size of the argument delta right after the
2421 // original REtADDR, but before the saved framepointer or the spilled registers
2422 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2434 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2435 /// for a 16 byte align requirement.
2437 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2438 SelectionDAG& DAG) const {
2439 MachineFunction &MF = DAG.getMachineFunction();
2440 const TargetMachine &TM = MF.getTarget();
2441 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2442 unsigned StackAlignment = TFI.getStackAlignment();
2443 uint64_t AlignMask = StackAlignment - 1;
2444 int64_t Offset = StackSize;
2445 uint64_t SlotSize = TD->getPointerSize();
2446 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2447 // Number smaller than 12 so just add the difference.
2448 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2450 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2451 Offset = ((~AlignMask) & Offset) + StackAlignment +
2452 (StackAlignment-SlotSize);
2457 /// MatchingStackOffset - Return true if the given stack call argument is
2458 /// already available in the same position (relatively) of the caller's
2459 /// incoming argument stack.
2461 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2462 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2463 const X86InstrInfo *TII) {
2464 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2466 if (Arg.getOpcode() == ISD::CopyFromReg) {
2467 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2468 if (!TargetRegisterInfo::isVirtualRegister(VR))
2470 MachineInstr *Def = MRI->getVRegDef(VR);
2473 if (!Flags.isByVal()) {
2474 if (!TII->isLoadFromStackSlot(Def, FI))
2477 unsigned Opcode = Def->getOpcode();
2478 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2479 Def->getOperand(1).isFI()) {
2480 FI = Def->getOperand(1).getIndex();
2481 Bytes = Flags.getByValSize();
2485 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2486 if (Flags.isByVal())
2487 // ByVal argument is passed in as a pointer but it's now being
2488 // dereferenced. e.g.
2489 // define @foo(%struct.X* %A) {
2490 // tail call @bar(%struct.X* byval %A)
2493 SDValue Ptr = Ld->getBasePtr();
2494 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2497 FI = FINode->getIndex();
2498 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2499 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2500 FI = FINode->getIndex();
2501 Bytes = Flags.getByValSize();
2505 assert(FI != INT_MAX);
2506 if (!MFI->isFixedObjectIndex(FI))
2508 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2511 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2512 /// for tail call optimization. Targets which want to do tail call
2513 /// optimization should implement this function.
2515 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2516 CallingConv::ID CalleeCC,
2518 bool isCalleeStructRet,
2519 bool isCallerStructRet,
2520 const SmallVectorImpl<ISD::OutputArg> &Outs,
2521 const SmallVectorImpl<SDValue> &OutVals,
2522 const SmallVectorImpl<ISD::InputArg> &Ins,
2523 SelectionDAG& DAG) const {
2524 if (!IsTailCallConvention(CalleeCC) &&
2525 CalleeCC != CallingConv::C)
2528 // If -tailcallopt is specified, make fastcc functions tail-callable.
2529 const MachineFunction &MF = DAG.getMachineFunction();
2530 const Function *CallerF = DAG.getMachineFunction().getFunction();
2531 CallingConv::ID CallerCC = CallerF->getCallingConv();
2532 bool CCMatch = CallerCC == CalleeCC;
2534 if (GuaranteedTailCallOpt) {
2535 if (IsTailCallConvention(CalleeCC) && CCMatch)
2540 // Look for obvious safe cases to perform tail call optimization that do not
2541 // require ABI changes. This is what gcc calls sibcall.
2543 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2544 // emit a special epilogue.
2545 if (RegInfo->needsStackRealignment(MF))
2548 // Also avoid sibcall optimization if either caller or callee uses struct
2549 // return semantics.
2550 if (isCalleeStructRet || isCallerStructRet)
2553 // An stdcall caller is expected to clean up its arguments; the callee
2554 // isn't going to do that.
2555 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2558 // Do not sibcall optimize vararg calls unless all arguments are passed via
2560 if (isVarArg && !Outs.empty()) {
2562 // Optimizing for varargs on Win64 is unlikely to be safe without
2563 // additional testing.
2564 if (Subtarget->isTargetWin64())
2567 SmallVector<CCValAssign, 16> ArgLocs;
2568 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2569 getTargetMachine(), ArgLocs, *DAG.getContext());
2571 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2572 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2573 if (!ArgLocs[i].isRegLoc())
2577 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2578 // Therefore if it's not used by the call it is not safe to optimize this into
2580 bool Unused = false;
2581 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2588 SmallVector<CCValAssign, 16> RVLocs;
2589 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2590 getTargetMachine(), RVLocs, *DAG.getContext());
2591 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2592 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2593 CCValAssign &VA = RVLocs[i];
2594 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2599 // If the calling conventions do not match, then we'd better make sure the
2600 // results are returned in the same way as what the caller expects.
2602 SmallVector<CCValAssign, 16> RVLocs1;
2603 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2604 getTargetMachine(), RVLocs1, *DAG.getContext());
2605 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2607 SmallVector<CCValAssign, 16> RVLocs2;
2608 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2609 getTargetMachine(), RVLocs2, *DAG.getContext());
2610 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2612 if (RVLocs1.size() != RVLocs2.size())
2614 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2615 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2617 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2619 if (RVLocs1[i].isRegLoc()) {
2620 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2623 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2629 // If the callee takes no arguments then go on to check the results of the
2631 if (!Outs.empty()) {
2632 // Check if stack adjustment is needed. For now, do not do this if any
2633 // argument is passed on the stack.
2634 SmallVector<CCValAssign, 16> ArgLocs;
2635 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2636 getTargetMachine(), ArgLocs, *DAG.getContext());
2638 // Allocate shadow area for Win64
2639 if (Subtarget->isTargetWin64()) {
2640 CCInfo.AllocateStack(32, 8);
2643 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2644 if (CCInfo.getNextStackOffset()) {
2645 MachineFunction &MF = DAG.getMachineFunction();
2646 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2649 // Check if the arguments are already laid out in the right way as
2650 // the caller's fixed stack objects.
2651 MachineFrameInfo *MFI = MF.getFrameInfo();
2652 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2653 const X86InstrInfo *TII =
2654 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2655 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2656 CCValAssign &VA = ArgLocs[i];
2657 SDValue Arg = OutVals[i];
2658 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2659 if (VA.getLocInfo() == CCValAssign::Indirect)
2661 if (!VA.isRegLoc()) {
2662 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2669 // If the tailcall address may be in a register, then make sure it's
2670 // possible to register allocate for it. In 32-bit, the call address can
2671 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2672 // callee-saved registers are restored. These happen to be the same
2673 // registers used to pass 'inreg' arguments so watch out for those.
2674 if (!Subtarget->is64Bit() &&
2675 !isa<GlobalAddressSDNode>(Callee) &&
2676 !isa<ExternalSymbolSDNode>(Callee)) {
2677 unsigned NumInRegs = 0;
2678 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2679 CCValAssign &VA = ArgLocs[i];
2682 unsigned Reg = VA.getLocReg();
2685 case X86::EAX: case X86::EDX: case X86::ECX:
2686 if (++NumInRegs == 3)
2698 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2699 return X86::createFastISel(funcInfo);
2703 //===----------------------------------------------------------------------===//
2704 // Other Lowering Hooks
2705 //===----------------------------------------------------------------------===//
2707 static bool MayFoldLoad(SDValue Op) {
2708 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2711 static bool MayFoldIntoStore(SDValue Op) {
2712 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2715 static bool isTargetShuffle(unsigned Opcode) {
2717 default: return false;
2718 case X86ISD::PSHUFD:
2719 case X86ISD::PSHUFHW:
2720 case X86ISD::PSHUFLW:
2721 case X86ISD::SHUFPD:
2722 case X86ISD::PALIGN:
2723 case X86ISD::SHUFPS:
2724 case X86ISD::MOVLHPS:
2725 case X86ISD::MOVLHPD:
2726 case X86ISD::MOVHLPS:
2727 case X86ISD::MOVLPS:
2728 case X86ISD::MOVLPD:
2729 case X86ISD::MOVSHDUP:
2730 case X86ISD::MOVSLDUP:
2731 case X86ISD::MOVDDUP:
2734 case X86ISD::UNPCKLPS:
2735 case X86ISD::UNPCKLPD:
2736 case X86ISD::VUNPCKLPS:
2737 case X86ISD::VUNPCKLPD:
2738 case X86ISD::VUNPCKLPSY:
2739 case X86ISD::VUNPCKLPDY:
2740 case X86ISD::PUNPCKLWD:
2741 case X86ISD::PUNPCKLBW:
2742 case X86ISD::PUNPCKLDQ:
2743 case X86ISD::PUNPCKLQDQ:
2744 case X86ISD::UNPCKHPS:
2745 case X86ISD::UNPCKHPD:
2746 case X86ISD::PUNPCKHWD:
2747 case X86ISD::PUNPCKHBW:
2748 case X86ISD::PUNPCKHDQ:
2749 case X86ISD::PUNPCKHQDQ:
2755 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2756 SDValue V1, SelectionDAG &DAG) {
2758 default: llvm_unreachable("Unknown x86 shuffle node");
2759 case X86ISD::MOVSHDUP:
2760 case X86ISD::MOVSLDUP:
2761 case X86ISD::MOVDDUP:
2762 return DAG.getNode(Opc, dl, VT, V1);
2768 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2769 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2771 default: llvm_unreachable("Unknown x86 shuffle node");
2772 case X86ISD::PSHUFD:
2773 case X86ISD::PSHUFHW:
2774 case X86ISD::PSHUFLW:
2775 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2781 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2782 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2784 default: llvm_unreachable("Unknown x86 shuffle node");
2785 case X86ISD::PALIGN:
2786 case X86ISD::SHUFPD:
2787 case X86ISD::SHUFPS:
2788 return DAG.getNode(Opc, dl, VT, V1, V2,
2789 DAG.getConstant(TargetMask, MVT::i8));
2794 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2795 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2797 default: llvm_unreachable("Unknown x86 shuffle node");
2798 case X86ISD::MOVLHPS:
2799 case X86ISD::MOVLHPD:
2800 case X86ISD::MOVHLPS:
2801 case X86ISD::MOVLPS:
2802 case X86ISD::MOVLPD:
2805 case X86ISD::UNPCKLPS:
2806 case X86ISD::UNPCKLPD:
2807 case X86ISD::VUNPCKLPS:
2808 case X86ISD::VUNPCKLPD:
2809 case X86ISD::VUNPCKLPSY:
2810 case X86ISD::VUNPCKLPDY:
2811 case X86ISD::PUNPCKLWD:
2812 case X86ISD::PUNPCKLBW:
2813 case X86ISD::PUNPCKLDQ:
2814 case X86ISD::PUNPCKLQDQ:
2815 case X86ISD::UNPCKHPS:
2816 case X86ISD::UNPCKHPD:
2817 case X86ISD::PUNPCKHWD:
2818 case X86ISD::PUNPCKHBW:
2819 case X86ISD::PUNPCKHDQ:
2820 case X86ISD::PUNPCKHQDQ:
2821 return DAG.getNode(Opc, dl, VT, V1, V2);
2826 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2827 MachineFunction &MF = DAG.getMachineFunction();
2828 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2829 int ReturnAddrIndex = FuncInfo->getRAIndex();
2831 if (ReturnAddrIndex == 0) {
2832 // Set up a frame object for the return address.
2833 uint64_t SlotSize = TD->getPointerSize();
2834 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2836 FuncInfo->setRAIndex(ReturnAddrIndex);
2839 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2843 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2844 bool hasSymbolicDisplacement) {
2845 // Offset should fit into 32 bit immediate field.
2846 if (!isInt<32>(Offset))
2849 // If we don't have a symbolic displacement - we don't have any extra
2851 if (!hasSymbolicDisplacement)
2854 // FIXME: Some tweaks might be needed for medium code model.
2855 if (M != CodeModel::Small && M != CodeModel::Kernel)
2858 // For small code model we assume that latest object is 16MB before end of 31
2859 // bits boundary. We may also accept pretty large negative constants knowing
2860 // that all objects are in the positive half of address space.
2861 if (M == CodeModel::Small && Offset < 16*1024*1024)
2864 // For kernel code model we know that all object resist in the negative half
2865 // of 32bits address space. We may not accept negative offsets, since they may
2866 // be just off and we may accept pretty large positive ones.
2867 if (M == CodeModel::Kernel && Offset > 0)
2873 /// isCalleePop - Determines whether the callee is required to pop its
2874 /// own arguments. Callee pop is necessary to support tail calls.
2875 bool X86::isCalleePop(CallingConv::ID CallingConv,
2876 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2880 switch (CallingConv) {
2883 case CallingConv::X86_StdCall:
2885 case CallingConv::X86_FastCall:
2887 case CallingConv::X86_ThisCall:
2889 case CallingConv::Fast:
2891 case CallingConv::GHC:
2896 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2897 /// specific condition code, returning the condition code and the LHS/RHS of the
2898 /// comparison to make.
2899 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2900 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2902 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2903 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2904 // X > -1 -> X == 0, jump !sign.
2905 RHS = DAG.getConstant(0, RHS.getValueType());
2906 return X86::COND_NS;
2907 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2908 // X < 0 -> X == 0, jump on sign.
2910 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2912 RHS = DAG.getConstant(0, RHS.getValueType());
2913 return X86::COND_LE;
2917 switch (SetCCOpcode) {
2918 default: llvm_unreachable("Invalid integer condition!");
2919 case ISD::SETEQ: return X86::COND_E;
2920 case ISD::SETGT: return X86::COND_G;
2921 case ISD::SETGE: return X86::COND_GE;
2922 case ISD::SETLT: return X86::COND_L;
2923 case ISD::SETLE: return X86::COND_LE;
2924 case ISD::SETNE: return X86::COND_NE;
2925 case ISD::SETULT: return X86::COND_B;
2926 case ISD::SETUGT: return X86::COND_A;
2927 case ISD::SETULE: return X86::COND_BE;
2928 case ISD::SETUGE: return X86::COND_AE;
2932 // First determine if it is required or is profitable to flip the operands.
2934 // If LHS is a foldable load, but RHS is not, flip the condition.
2935 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2936 !ISD::isNON_EXTLoad(RHS.getNode())) {
2937 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2938 std::swap(LHS, RHS);
2941 switch (SetCCOpcode) {
2947 std::swap(LHS, RHS);
2951 // On a floating point condition, the flags are set as follows:
2953 // 0 | 0 | 0 | X > Y
2954 // 0 | 0 | 1 | X < Y
2955 // 1 | 0 | 0 | X == Y
2956 // 1 | 1 | 1 | unordered
2957 switch (SetCCOpcode) {
2958 default: llvm_unreachable("Condcode should be pre-legalized away");
2960 case ISD::SETEQ: return X86::COND_E;
2961 case ISD::SETOLT: // flipped
2963 case ISD::SETGT: return X86::COND_A;
2964 case ISD::SETOLE: // flipped
2966 case ISD::SETGE: return X86::COND_AE;
2967 case ISD::SETUGT: // flipped
2969 case ISD::SETLT: return X86::COND_B;
2970 case ISD::SETUGE: // flipped
2972 case ISD::SETLE: return X86::COND_BE;
2974 case ISD::SETNE: return X86::COND_NE;
2975 case ISD::SETUO: return X86::COND_P;
2976 case ISD::SETO: return X86::COND_NP;
2978 case ISD::SETUNE: return X86::COND_INVALID;
2982 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2983 /// code. Current x86 isa includes the following FP cmov instructions:
2984 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2985 static bool hasFPCMov(unsigned X86CC) {
3001 /// isFPImmLegal - Returns true if the target can instruction select the
3002 /// specified FP immediate natively. If false, the legalizer will
3003 /// materialize the FP immediate as a load from a constant pool.
3004 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3005 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3006 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3012 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3013 /// the specified range (L, H].
3014 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3015 return (Val < 0) || (Val >= Low && Val < Hi);
3018 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3019 /// specified value.
3020 static bool isUndefOrEqual(int Val, int CmpVal) {
3021 if (Val < 0 || Val == CmpVal)
3026 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3027 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3028 /// the second operand.
3029 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3030 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3031 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3032 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3033 return (Mask[0] < 2 && Mask[1] < 2);
3037 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3038 SmallVector<int, 8> M;
3040 return ::isPSHUFDMask(M, N->getValueType(0));
3043 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3044 /// is suitable for input to PSHUFHW.
3045 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3046 if (VT != MVT::v8i16)
3049 // Lower quadword copied in order or undef.
3050 for (int i = 0; i != 4; ++i)
3051 if (Mask[i] >= 0 && Mask[i] != i)
3054 // Upper quadword shuffled.
3055 for (int i = 4; i != 8; ++i)
3056 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3062 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3063 SmallVector<int, 8> M;
3065 return ::isPSHUFHWMask(M, N->getValueType(0));
3068 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3069 /// is suitable for input to PSHUFLW.
3070 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3071 if (VT != MVT::v8i16)
3074 // Upper quadword copied in order.
3075 for (int i = 4; i != 8; ++i)
3076 if (Mask[i] >= 0 && Mask[i] != i)
3079 // Lower quadword shuffled.
3080 for (int i = 0; i != 4; ++i)
3087 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3088 SmallVector<int, 8> M;
3090 return ::isPSHUFLWMask(M, N->getValueType(0));
3093 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3094 /// is suitable for input to PALIGNR.
3095 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3097 int i, e = VT.getVectorNumElements();
3099 // Do not handle v2i64 / v2f64 shuffles with palignr.
3100 if (e < 4 || !hasSSSE3)
3103 for (i = 0; i != e; ++i)
3107 // All undef, not a palignr.
3111 // Determine if it's ok to perform a palignr with only the LHS, since we
3112 // don't have access to the actual shuffle elements to see if RHS is undef.
3113 bool Unary = Mask[i] < (int)e;
3114 bool NeedsUnary = false;
3116 int s = Mask[i] - i;
3118 // Check the rest of the elements to see if they are consecutive.
3119 for (++i; i != e; ++i) {
3124 Unary = Unary && (m < (int)e);
3125 NeedsUnary = NeedsUnary || (m < s);
3127 if (NeedsUnary && !Unary)
3129 if (Unary && m != ((s+i) & (e-1)))
3131 if (!Unary && m != (s+i))
3137 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3138 SmallVector<int, 8> M;
3140 return ::isPALIGNRMask(M, N->getValueType(0), true);
3143 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3144 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3145 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3146 int NumElems = VT.getVectorNumElements();
3147 if (NumElems != 2 && NumElems != 4)
3150 int Half = NumElems / 2;
3151 for (int i = 0; i < Half; ++i)
3152 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3154 for (int i = Half; i < NumElems; ++i)
3155 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3161 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3162 SmallVector<int, 8> M;
3164 return ::isSHUFPMask(M, N->getValueType(0));
3167 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3168 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3169 /// half elements to come from vector 1 (which would equal the dest.) and
3170 /// the upper half to come from vector 2.
3171 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3172 int NumElems = VT.getVectorNumElements();
3174 if (NumElems != 2 && NumElems != 4)
3177 int Half = NumElems / 2;
3178 for (int i = 0; i < Half; ++i)
3179 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3181 for (int i = Half; i < NumElems; ++i)
3182 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3187 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3188 SmallVector<int, 8> M;
3190 return isCommutedSHUFPMask(M, N->getValueType(0));
3193 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3194 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3195 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3196 if (N->getValueType(0).getVectorNumElements() != 4)
3199 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3200 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3201 isUndefOrEqual(N->getMaskElt(1), 7) &&
3202 isUndefOrEqual(N->getMaskElt(2), 2) &&
3203 isUndefOrEqual(N->getMaskElt(3), 3);
3206 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3207 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3209 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3210 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3215 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3216 isUndefOrEqual(N->getMaskElt(1), 3) &&
3217 isUndefOrEqual(N->getMaskElt(2), 2) &&
3218 isUndefOrEqual(N->getMaskElt(3), 3);
3221 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3222 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3223 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3224 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3226 if (NumElems != 2 && NumElems != 4)
3229 for (unsigned i = 0; i < NumElems/2; ++i)
3230 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3233 for (unsigned i = NumElems/2; i < NumElems; ++i)
3234 if (!isUndefOrEqual(N->getMaskElt(i), i))
3240 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3241 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3242 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3243 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3245 if ((NumElems != 2 && NumElems != 4)
3246 || N->getValueType(0).getSizeInBits() > 128)
3249 for (unsigned i = 0; i < NumElems/2; ++i)
3250 if (!isUndefOrEqual(N->getMaskElt(i), i))
3253 for (unsigned i = 0; i < NumElems/2; ++i)
3254 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3260 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3261 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3262 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3263 bool V2IsSplat = false) {
3264 int NumElts = VT.getVectorNumElements();
3265 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3268 // Handle vector lengths > 128 bits. Define a "section" as a set of
3269 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3271 unsigned NumSections = VT.getSizeInBits() / 128;
3272 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3273 unsigned NumSectionElts = NumElts / NumSections;
3276 unsigned End = NumSectionElts;
3277 for (unsigned s = 0; s < NumSections; ++s) {
3278 for (unsigned i = Start, j = s * NumSectionElts;
3282 int BitI1 = Mask[i+1];
3283 if (!isUndefOrEqual(BitI, j))
3286 if (!isUndefOrEqual(BitI1, NumElts))
3289 if (!isUndefOrEqual(BitI1, j + NumElts))
3293 // Process the next 128 bits.
3294 Start += NumSectionElts;
3295 End += NumSectionElts;
3301 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3302 SmallVector<int, 8> M;
3304 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3307 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3308 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3309 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3310 bool V2IsSplat = false) {
3311 int NumElts = VT.getVectorNumElements();
3312 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3315 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3317 int BitI1 = Mask[i+1];
3318 if (!isUndefOrEqual(BitI, j + NumElts/2))
3321 if (isUndefOrEqual(BitI1, NumElts))
3324 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3331 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3332 SmallVector<int, 8> M;
3334 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3337 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3338 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3340 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3341 int NumElems = VT.getVectorNumElements();
3342 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3345 // Handle vector lengths > 128 bits. Define a "section" as a set of
3346 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3348 unsigned NumSections = VT.getSizeInBits() / 128;
3349 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3350 unsigned NumSectionElts = NumElems / NumSections;
3352 for (unsigned s = 0; s < NumSections; ++s) {
3353 for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3354 i != NumSectionElts * (s + 1);
3357 int BitI1 = Mask[i+1];
3359 if (!isUndefOrEqual(BitI, j))
3361 if (!isUndefOrEqual(BitI1, j))
3369 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3370 SmallVector<int, 8> M;
3372 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3375 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3376 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3378 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3379 int NumElems = VT.getVectorNumElements();
3380 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3383 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3385 int BitI1 = Mask[i+1];
3386 if (!isUndefOrEqual(BitI, j))
3388 if (!isUndefOrEqual(BitI1, j))
3394 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3395 SmallVector<int, 8> M;
3397 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3400 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3401 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3402 /// MOVSD, and MOVD, i.e. setting the lowest element.
3403 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3404 if (VT.getVectorElementType().getSizeInBits() < 32)
3407 int NumElts = VT.getVectorNumElements();
3409 if (!isUndefOrEqual(Mask[0], NumElts))
3412 for (int i = 1; i < NumElts; ++i)
3413 if (!isUndefOrEqual(Mask[i], i))
3419 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3420 SmallVector<int, 8> M;
3422 return ::isMOVLMask(M, N->getValueType(0));
3425 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3426 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3427 /// element of vector 2 and the other elements to come from vector 1 in order.
3428 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3429 bool V2IsSplat = false, bool V2IsUndef = false) {
3430 int NumOps = VT.getVectorNumElements();
3431 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3434 if (!isUndefOrEqual(Mask[0], 0))
3437 for (int i = 1; i < NumOps; ++i)
3438 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3439 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3440 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3446 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3447 bool V2IsUndef = false) {
3448 SmallVector<int, 8> M;
3450 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3453 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3454 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3455 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3456 if (N->getValueType(0).getVectorNumElements() != 4)
3459 // Expect 1, 1, 3, 3
3460 for (unsigned i = 0; i < 2; ++i) {
3461 int Elt = N->getMaskElt(i);
3462 if (Elt >= 0 && Elt != 1)
3467 for (unsigned i = 2; i < 4; ++i) {
3468 int Elt = N->getMaskElt(i);
3469 if (Elt >= 0 && Elt != 3)
3474 // Don't use movshdup if it can be done with a shufps.
3475 // FIXME: verify that matching u, u, 3, 3 is what we want.
3479 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3480 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3481 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3482 if (N->getValueType(0).getVectorNumElements() != 4)
3485 // Expect 0, 0, 2, 2
3486 for (unsigned i = 0; i < 2; ++i)
3487 if (N->getMaskElt(i) > 0)
3491 for (unsigned i = 2; i < 4; ++i) {
3492 int Elt = N->getMaskElt(i);
3493 if (Elt >= 0 && Elt != 2)
3498 // Don't use movsldup if it can be done with a shufps.
3502 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3503 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3504 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3505 int e = N->getValueType(0).getVectorNumElements() / 2;
3507 for (int i = 0; i < e; ++i)
3508 if (!isUndefOrEqual(N->getMaskElt(i), i))
3510 for (int i = 0; i < e; ++i)
3511 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3516 /// isVEXTRACTF128Index - Return true if the specified
3517 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3518 /// suitable for input to VEXTRACTF128.
3519 bool X86::isVEXTRACTF128Index(SDNode *N) {
3520 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3523 // The index should be aligned on a 128-bit boundary.
3525 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3527 unsigned VL = N->getValueType(0).getVectorNumElements();
3528 unsigned VBits = N->getValueType(0).getSizeInBits();
3529 unsigned ElSize = VBits / VL;
3530 bool Result = (Index * ElSize) % 128 == 0;
3535 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3536 /// operand specifies a subvector insert that is suitable for input to
3538 bool X86::isVINSERTF128Index(SDNode *N) {
3539 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3542 // The index should be aligned on a 128-bit boundary.
3544 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3546 unsigned VL = N->getValueType(0).getVectorNumElements();
3547 unsigned VBits = N->getValueType(0).getSizeInBits();
3548 unsigned ElSize = VBits / VL;
3549 bool Result = (Index * ElSize) % 128 == 0;
3554 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3555 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3556 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3557 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3558 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3560 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3562 for (int i = 0; i < NumOperands; ++i) {
3563 int Val = SVOp->getMaskElt(NumOperands-i-1);
3564 if (Val < 0) Val = 0;
3565 if (Val >= NumOperands) Val -= NumOperands;
3567 if (i != NumOperands - 1)
3573 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3574 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3575 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3576 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3578 // 8 nodes, but we only care about the last 4.
3579 for (unsigned i = 7; i >= 4; --i) {
3580 int Val = SVOp->getMaskElt(i);
3589 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3590 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3591 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3592 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3594 // 8 nodes, but we only care about the first 4.
3595 for (int i = 3; i >= 0; --i) {
3596 int Val = SVOp->getMaskElt(i);
3605 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3606 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3607 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3608 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3609 EVT VVT = N->getValueType(0);
3610 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3614 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3615 Val = SVOp->getMaskElt(i);
3619 return (Val - i) * EltSize;
3622 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3623 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3625 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3626 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3627 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3630 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3632 EVT VecVT = N->getOperand(0).getValueType();
3633 EVT ElVT = VecVT.getVectorElementType();
3635 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3636 return Index / NumElemsPerChunk;
3639 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3640 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3642 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3643 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3644 llvm_unreachable("Illegal insert subvector for VINSERTF128");
3647 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3649 EVT VecVT = N->getValueType(0);
3650 EVT ElVT = VecVT.getVectorElementType();
3652 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3653 return Index / NumElemsPerChunk;
3656 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3658 bool X86::isZeroNode(SDValue Elt) {
3659 return ((isa<ConstantSDNode>(Elt) &&
3660 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3661 (isa<ConstantFPSDNode>(Elt) &&
3662 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3665 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3666 /// their permute mask.
3667 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3668 SelectionDAG &DAG) {
3669 EVT VT = SVOp->getValueType(0);
3670 unsigned NumElems = VT.getVectorNumElements();
3671 SmallVector<int, 8> MaskVec;
3673 for (unsigned i = 0; i != NumElems; ++i) {
3674 int idx = SVOp->getMaskElt(i);
3676 MaskVec.push_back(idx);
3677 else if (idx < (int)NumElems)
3678 MaskVec.push_back(idx + NumElems);
3680 MaskVec.push_back(idx - NumElems);
3682 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3683 SVOp->getOperand(0), &MaskVec[0]);
3686 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3687 /// the two vector operands have swapped position.
3688 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3689 unsigned NumElems = VT.getVectorNumElements();
3690 for (unsigned i = 0; i != NumElems; ++i) {
3694 else if (idx < (int)NumElems)
3695 Mask[i] = idx + NumElems;
3697 Mask[i] = idx - NumElems;
3701 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3702 /// match movhlps. The lower half elements should come from upper half of
3703 /// V1 (and in order), and the upper half elements should come from the upper
3704 /// half of V2 (and in order).
3705 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3706 if (Op->getValueType(0).getVectorNumElements() != 4)
3708 for (unsigned i = 0, e = 2; i != e; ++i)
3709 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3711 for (unsigned i = 2; i != 4; ++i)
3712 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3717 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3718 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3720 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3721 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3723 N = N->getOperand(0).getNode();
3724 if (!ISD::isNON_EXTLoad(N))
3727 *LD = cast<LoadSDNode>(N);
3731 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3732 /// match movlp{s|d}. The lower half elements should come from lower half of
3733 /// V1 (and in order), and the upper half elements should come from the upper
3734 /// half of V2 (and in order). And since V1 will become the source of the
3735 /// MOVLP, it must be either a vector load or a scalar load to vector.
3736 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3737 ShuffleVectorSDNode *Op) {
3738 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3740 // Is V2 is a vector load, don't do this transformation. We will try to use
3741 // load folding shufps op.
3742 if (ISD::isNON_EXTLoad(V2))
3745 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3747 if (NumElems != 2 && NumElems != 4)
3749 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3750 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3752 for (unsigned i = NumElems/2; i != NumElems; ++i)
3753 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3758 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3760 static bool isSplatVector(SDNode *N) {
3761 if (N->getOpcode() != ISD::BUILD_VECTOR)
3764 SDValue SplatValue = N->getOperand(0);
3765 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3766 if (N->getOperand(i) != SplatValue)
3771 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3772 /// to an zero vector.
3773 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3774 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3775 SDValue V1 = N->getOperand(0);
3776 SDValue V2 = N->getOperand(1);
3777 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3778 for (unsigned i = 0; i != NumElems; ++i) {
3779 int Idx = N->getMaskElt(i);
3780 if (Idx >= (int)NumElems) {
3781 unsigned Opc = V2.getOpcode();
3782 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3784 if (Opc != ISD::BUILD_VECTOR ||
3785 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3787 } else if (Idx >= 0) {
3788 unsigned Opc = V1.getOpcode();
3789 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3791 if (Opc != ISD::BUILD_VECTOR ||
3792 !X86::isZeroNode(V1.getOperand(Idx)))
3799 /// getZeroVector - Returns a vector of specified type with all zero elements.
3801 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3803 assert(VT.isVector() && "Expected a vector type");
3805 // Always build SSE zero vectors as <4 x i32> bitcasted
3806 // to their dest type. This ensures they get CSE'd.
3808 if (VT.getSizeInBits() == 128) { // SSE
3809 if (HasSSE2) { // SSE2
3810 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3811 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3813 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3814 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3816 } else if (VT.getSizeInBits() == 256) { // AVX
3817 // 256-bit logic and arithmetic instructions in AVX are
3818 // all floating-point, no support for integer ops. Default
3819 // to emitting fp zeroed vectors then.
3820 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3821 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3822 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3824 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3827 /// getOnesVector - Returns a vector of specified type with all bits set.
3828 /// Always build ones vectors as <4 x i32> or <8 x i32> bitcasted to
3829 /// their original type, ensuring they get CSE'd.
3830 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3831 assert(VT.isVector() && "Expected a vector type");
3832 assert((VT.is128BitVector() || VT.is256BitVector())
3833 && "Expected a 128-bit or 256-bit vector type");
3835 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3838 if (VT.is256BitVector()) {
3839 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3840 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
3842 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3843 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3846 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3847 /// that point to V2 points to its first element.
3848 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3849 EVT VT = SVOp->getValueType(0);
3850 unsigned NumElems = VT.getVectorNumElements();
3852 bool Changed = false;
3853 SmallVector<int, 8> MaskVec;
3854 SVOp->getMask(MaskVec);
3856 for (unsigned i = 0; i != NumElems; ++i) {
3857 if (MaskVec[i] > (int)NumElems) {
3858 MaskVec[i] = NumElems;
3863 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3864 SVOp->getOperand(1), &MaskVec[0]);
3865 return SDValue(SVOp, 0);
3868 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3869 /// operation of specified width.
3870 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3872 unsigned NumElems = VT.getVectorNumElements();
3873 SmallVector<int, 8> Mask;
3874 Mask.push_back(NumElems);
3875 for (unsigned i = 1; i != NumElems; ++i)
3877 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3880 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3881 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3883 unsigned NumElems = VT.getVectorNumElements();
3884 SmallVector<int, 8> Mask;
3885 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3887 Mask.push_back(i + NumElems);
3889 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3892 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3893 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3895 unsigned NumElems = VT.getVectorNumElements();
3896 unsigned Half = NumElems/2;
3897 SmallVector<int, 8> Mask;
3898 for (unsigned i = 0; i != Half; ++i) {
3899 Mask.push_back(i + Half);
3900 Mask.push_back(i + NumElems + Half);
3902 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3905 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3906 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3907 EVT PVT = MVT::v4f32;
3908 EVT VT = SV->getValueType(0);
3909 DebugLoc dl = SV->getDebugLoc();
3910 SDValue V1 = SV->getOperand(0);
3911 int NumElems = VT.getVectorNumElements();
3912 int EltNo = SV->getSplatIndex();
3914 // unpack elements to the correct location
3915 while (NumElems > 4) {
3916 if (EltNo < NumElems/2) {
3917 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3919 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3920 EltNo -= NumElems/2;
3925 // Perform the splat.
3926 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3927 V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3928 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3929 return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3932 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3933 /// vector of zero or undef vector. This produces a shuffle where the low
3934 /// element of V2 is swizzled into the zero/undef vector, landing at element
3935 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3936 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3937 bool isZero, bool HasSSE2,
3938 SelectionDAG &DAG) {
3939 EVT VT = V2.getValueType();
3941 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3942 unsigned NumElems = VT.getVectorNumElements();
3943 SmallVector<int, 16> MaskVec;
3944 for (unsigned i = 0; i != NumElems; ++i)
3945 // If this is the insertion idx, put the low elt of V2 here.
3946 MaskVec.push_back(i == Idx ? NumElems : i);
3947 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3950 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3951 /// element of the result of the vector shuffle.
3952 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3955 return SDValue(); // Limit search depth.
3957 SDValue V = SDValue(N, 0);
3958 EVT VT = V.getValueType();
3959 unsigned Opcode = V.getOpcode();
3961 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3962 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3963 Index = SV->getMaskElt(Index);
3966 return DAG.getUNDEF(VT.getVectorElementType());
3968 int NumElems = VT.getVectorNumElements();
3969 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3970 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3973 // Recurse into target specific vector shuffles to find scalars.
3974 if (isTargetShuffle(Opcode)) {
3975 int NumElems = VT.getVectorNumElements();
3976 SmallVector<unsigned, 16> ShuffleMask;
3980 case X86ISD::SHUFPS:
3981 case X86ISD::SHUFPD:
3982 ImmN = N->getOperand(N->getNumOperands()-1);
3983 DecodeSHUFPSMask(NumElems,
3984 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3987 case X86ISD::PUNPCKHBW:
3988 case X86ISD::PUNPCKHWD:
3989 case X86ISD::PUNPCKHDQ:
3990 case X86ISD::PUNPCKHQDQ:
3991 DecodePUNPCKHMask(NumElems, ShuffleMask);
3993 case X86ISD::UNPCKHPS:
3994 case X86ISD::UNPCKHPD:
3995 DecodeUNPCKHPMask(NumElems, ShuffleMask);
3997 case X86ISD::PUNPCKLBW:
3998 case X86ISD::PUNPCKLWD:
3999 case X86ISD::PUNPCKLDQ:
4000 case X86ISD::PUNPCKLQDQ:
4001 DecodePUNPCKLMask(VT, ShuffleMask);
4003 case X86ISD::UNPCKLPS:
4004 case X86ISD::UNPCKLPD:
4005 case X86ISD::VUNPCKLPS:
4006 case X86ISD::VUNPCKLPD:
4007 case X86ISD::VUNPCKLPSY:
4008 case X86ISD::VUNPCKLPDY:
4009 DecodeUNPCKLPMask(VT, ShuffleMask);
4011 case X86ISD::MOVHLPS:
4012 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4014 case X86ISD::MOVLHPS:
4015 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4017 case X86ISD::PSHUFD:
4018 ImmN = N->getOperand(N->getNumOperands()-1);
4019 DecodePSHUFMask(NumElems,
4020 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4023 case X86ISD::PSHUFHW:
4024 ImmN = N->getOperand(N->getNumOperands()-1);
4025 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4028 case X86ISD::PSHUFLW:
4029 ImmN = N->getOperand(N->getNumOperands()-1);
4030 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4034 case X86ISD::MOVSD: {
4035 // The index 0 always comes from the first element of the second source,
4036 // this is why MOVSS and MOVSD are used in the first place. The other
4037 // elements come from the other positions of the first source vector.
4038 unsigned OpNum = (Index == 0) ? 1 : 0;
4039 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4043 assert("not implemented for target shuffle node");
4047 Index = ShuffleMask[Index];
4049 return DAG.getUNDEF(VT.getVectorElementType());
4051 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4052 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4056 // Actual nodes that may contain scalar elements
4057 if (Opcode == ISD::BITCAST) {
4058 V = V.getOperand(0);
4059 EVT SrcVT = V.getValueType();
4060 unsigned NumElems = VT.getVectorNumElements();
4062 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4066 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4067 return (Index == 0) ? V.getOperand(0)
4068 : DAG.getUNDEF(VT.getVectorElementType());
4070 if (V.getOpcode() == ISD::BUILD_VECTOR)
4071 return V.getOperand(Index);
4076 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4077 /// shuffle operation which come from a consecutively from a zero. The
4078 /// search can start in two different directions, from left or right.
4080 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4081 bool ZerosFromLeft, SelectionDAG &DAG) {
4084 while (i < NumElems) {
4085 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4086 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4087 if (!(Elt.getNode() &&
4088 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4096 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4097 /// MaskE correspond consecutively to elements from one of the vector operands,
4098 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4100 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4101 int OpIdx, int NumElems, unsigned &OpNum) {
4102 bool SeenV1 = false;
4103 bool SeenV2 = false;
4105 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4106 int Idx = SVOp->getMaskElt(i);
4107 // Ignore undef indicies
4116 // Only accept consecutive elements from the same vector
4117 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4121 OpNum = SeenV1 ? 0 : 1;
4125 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4126 /// logical left shift of a vector.
4127 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4128 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4129 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4130 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4131 false /* check zeros from right */, DAG);
4137 // Considering the elements in the mask that are not consecutive zeros,
4138 // check if they consecutively come from only one of the source vectors.
4140 // V1 = {X, A, B, C} 0
4142 // vector_shuffle V1, V2 <1, 2, 3, X>
4144 if (!isShuffleMaskConsecutive(SVOp,
4145 0, // Mask Start Index
4146 NumElems-NumZeros-1, // Mask End Index
4147 NumZeros, // Where to start looking in the src vector
4148 NumElems, // Number of elements in vector
4149 OpSrc)) // Which source operand ?
4154 ShVal = SVOp->getOperand(OpSrc);
4158 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4159 /// logical left shift of a vector.
4160 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4161 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4162 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4163 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4164 true /* check zeros from left */, DAG);
4170 // Considering the elements in the mask that are not consecutive zeros,
4171 // check if they consecutively come from only one of the source vectors.
4173 // 0 { A, B, X, X } = V2
4175 // vector_shuffle V1, V2 <X, X, 4, 5>
4177 if (!isShuffleMaskConsecutive(SVOp,
4178 NumZeros, // Mask Start Index
4179 NumElems-1, // Mask End Index
4180 0, // Where to start looking in the src vector
4181 NumElems, // Number of elements in vector
4182 OpSrc)) // Which source operand ?
4187 ShVal = SVOp->getOperand(OpSrc);
4191 /// isVectorShift - Returns true if the shuffle can be implemented as a
4192 /// logical left or right shift of a vector.
4193 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4194 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4195 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4196 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4202 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4204 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4205 unsigned NumNonZero, unsigned NumZero,
4207 const TargetLowering &TLI) {
4211 DebugLoc dl = Op.getDebugLoc();
4214 for (unsigned i = 0; i < 16; ++i) {
4215 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4216 if (ThisIsNonZero && First) {
4218 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4220 V = DAG.getUNDEF(MVT::v8i16);
4225 SDValue ThisElt(0, 0), LastElt(0, 0);
4226 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4227 if (LastIsNonZero) {
4228 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4229 MVT::i16, Op.getOperand(i-1));
4231 if (ThisIsNonZero) {
4232 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4233 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4234 ThisElt, DAG.getConstant(8, MVT::i8));
4236 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4240 if (ThisElt.getNode())
4241 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4242 DAG.getIntPtrConstant(i/2));
4246 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4249 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4251 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4252 unsigned NumNonZero, unsigned NumZero,
4254 const TargetLowering &TLI) {
4258 DebugLoc dl = Op.getDebugLoc();
4261 for (unsigned i = 0; i < 8; ++i) {
4262 bool isNonZero = (NonZeros & (1 << i)) != 0;
4266 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4268 V = DAG.getUNDEF(MVT::v8i16);
4271 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4272 MVT::v8i16, V, Op.getOperand(i),
4273 DAG.getIntPtrConstant(i));
4280 /// getVShift - Return a vector logical shift node.
4282 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4283 unsigned NumBits, SelectionDAG &DAG,
4284 const TargetLowering &TLI, DebugLoc dl) {
4285 EVT ShVT = MVT::v2i64;
4286 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4287 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4288 return DAG.getNode(ISD::BITCAST, dl, VT,
4289 DAG.getNode(Opc, dl, ShVT, SrcOp,
4290 DAG.getConstant(NumBits,
4291 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4295 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4296 SelectionDAG &DAG) const {
4298 // Check if the scalar load can be widened into a vector load. And if
4299 // the address is "base + cst" see if the cst can be "absorbed" into
4300 // the shuffle mask.
4301 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4302 SDValue Ptr = LD->getBasePtr();
4303 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4305 EVT PVT = LD->getValueType(0);
4306 if (PVT != MVT::i32 && PVT != MVT::f32)
4311 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4312 FI = FINode->getIndex();
4314 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4315 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4316 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4317 Offset = Ptr.getConstantOperandVal(1);
4318 Ptr = Ptr.getOperand(0);
4323 SDValue Chain = LD->getChain();
4324 // Make sure the stack object alignment is at least 16.
4325 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4326 if (DAG.InferPtrAlignment(Ptr) < 16) {
4327 if (MFI->isFixedObjectIndex(FI)) {
4328 // Can't change the alignment. FIXME: It's possible to compute
4329 // the exact stack offset and reference FI + adjust offset instead.
4330 // If someone *really* cares about this. That's the way to implement it.
4333 MFI->setObjectAlignment(FI, 16);
4337 // (Offset % 16) must be multiple of 4. Then address is then
4338 // Ptr + (Offset & ~15).
4341 if ((Offset % 16) & 3)
4343 int64_t StartOffset = Offset & ~15;
4345 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4346 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4348 int EltNo = (Offset - StartOffset) >> 2;
4349 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4350 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4351 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4352 LD->getPointerInfo().getWithOffset(StartOffset),
4354 // Canonicalize it to a v4i32 shuffle.
4355 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4356 return DAG.getNode(ISD::BITCAST, dl, VT,
4357 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4358 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4364 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4365 /// vector of type 'VT', see if the elements can be replaced by a single large
4366 /// load which has the same value as a build_vector whose operands are 'elts'.
4368 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4370 /// FIXME: we'd also like to handle the case where the last elements are zero
4371 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4372 /// There's even a handy isZeroNode for that purpose.
4373 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4374 DebugLoc &DL, SelectionDAG &DAG) {
4375 EVT EltVT = VT.getVectorElementType();
4376 unsigned NumElems = Elts.size();
4378 LoadSDNode *LDBase = NULL;
4379 unsigned LastLoadedElt = -1U;
4381 // For each element in the initializer, see if we've found a load or an undef.
4382 // If we don't find an initial load element, or later load elements are
4383 // non-consecutive, bail out.
4384 for (unsigned i = 0; i < NumElems; ++i) {
4385 SDValue Elt = Elts[i];
4387 if (!Elt.getNode() ||
4388 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4391 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4393 LDBase = cast<LoadSDNode>(Elt.getNode());
4397 if (Elt.getOpcode() == ISD::UNDEF)
4400 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4401 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4406 // If we have found an entire vector of loads and undefs, then return a large
4407 // load of the entire vector width starting at the base pointer. If we found
4408 // consecutive loads for the low half, generate a vzext_load node.
4409 if (LastLoadedElt == NumElems - 1) {
4410 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4411 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4412 LDBase->getPointerInfo(),
4413 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4414 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4415 LDBase->getPointerInfo(),
4416 LDBase->isVolatile(), LDBase->isNonTemporal(),
4417 LDBase->getAlignment());
4418 } else if (NumElems == 4 && LastLoadedElt == 1) {
4419 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4420 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4421 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4423 LDBase->getMemOperand());
4424 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4430 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4431 DebugLoc dl = Op.getDebugLoc();
4433 EVT VT = Op.getValueType();
4434 EVT ExtVT = VT.getVectorElementType();
4436 unsigned NumElems = Op.getNumOperands();
4438 // For AVX-length vectors, build the individual 128-bit pieces and
4439 // use shuffles to put them in place.
4440 if (VT.getSizeInBits() > 256 &&
4441 Subtarget->hasAVX() &&
4442 !ISD::isBuildVectorAllZeros(Op.getNode())) {
4443 SmallVector<SDValue, 8> V;
4445 for (unsigned i = 0; i < NumElems; ++i) {
4446 V[i] = Op.getOperand(i);
4449 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4451 // Build the lower subvector.
4452 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4453 // Build the upper subvector.
4454 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4457 return ConcatVectors(Lower, Upper, DAG);
4461 // - pxor (SSE2), xorps (SSE1), vpxor (128 AVX), xorp[s|d] (256 AVX)
4463 // - pcmpeqd (SSE2 and 128 AVX), fallback to constant pools (256 AVX)
4464 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4465 ISD::isBuildVectorAllOnes(Op.getNode())) {
4466 // Canonicalize this to <4 x i32> or <8 x 32> (SSE) to
4467 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4468 // eliminated on x86-32 hosts.
4469 if (Op.getValueType() == MVT::v4i32 ||
4470 Op.getValueType() == MVT::v8i32)
4473 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4474 return getOnesVector(Op.getValueType(), DAG, dl);
4475 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4478 unsigned EVTBits = ExtVT.getSizeInBits();
4480 unsigned NumZero = 0;
4481 unsigned NumNonZero = 0;
4482 unsigned NonZeros = 0;
4483 bool IsAllConstants = true;
4484 SmallSet<SDValue, 8> Values;
4485 for (unsigned i = 0; i < NumElems; ++i) {
4486 SDValue Elt = Op.getOperand(i);
4487 if (Elt.getOpcode() == ISD::UNDEF)
4490 if (Elt.getOpcode() != ISD::Constant &&
4491 Elt.getOpcode() != ISD::ConstantFP)
4492 IsAllConstants = false;
4493 if (X86::isZeroNode(Elt))
4496 NonZeros |= (1 << i);
4501 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4502 if (NumNonZero == 0)
4503 return DAG.getUNDEF(VT);
4505 // Special case for single non-zero, non-undef, element.
4506 if (NumNonZero == 1) {
4507 unsigned Idx = CountTrailingZeros_32(NonZeros);
4508 SDValue Item = Op.getOperand(Idx);
4510 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4511 // the value are obviously zero, truncate the value to i32 and do the
4512 // insertion that way. Only do this if the value is non-constant or if the
4513 // value is a constant being inserted into element 0. It is cheaper to do
4514 // a constant pool load than it is to do a movd + shuffle.
4515 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4516 (!IsAllConstants || Idx == 0)) {
4517 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4519 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4520 EVT VecVT = MVT::v4i32;
4521 unsigned VecElts = 4;
4523 // Truncate the value (which may itself be a constant) to i32, and
4524 // convert it to a vector with movd (S2V+shuffle to zero extend).
4525 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4526 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4527 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4528 Subtarget->hasSSE2(), DAG);
4530 // Now we have our 32-bit value zero extended in the low element of
4531 // a vector. If Idx != 0, swizzle it into place.
4533 SmallVector<int, 4> Mask;
4534 Mask.push_back(Idx);
4535 for (unsigned i = 1; i != VecElts; ++i)
4537 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4538 DAG.getUNDEF(Item.getValueType()),
4541 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4545 // If we have a constant or non-constant insertion into the low element of
4546 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4547 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4548 // depending on what the source datatype is.
4551 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4552 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4553 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4554 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4555 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4556 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4558 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4559 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4560 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4561 EVT MiddleVT = MVT::v4i32;
4562 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4563 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4564 Subtarget->hasSSE2(), DAG);
4565 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4569 // Is it a vector logical left shift?
4570 if (NumElems == 2 && Idx == 1 &&
4571 X86::isZeroNode(Op.getOperand(0)) &&
4572 !X86::isZeroNode(Op.getOperand(1))) {
4573 unsigned NumBits = VT.getSizeInBits();
4574 return getVShift(true, VT,
4575 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4576 VT, Op.getOperand(1)),
4577 NumBits/2, DAG, *this, dl);
4580 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4583 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4584 // is a non-constant being inserted into an element other than the low one,
4585 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4586 // movd/movss) to move this into the low element, then shuffle it into
4588 if (EVTBits == 32) {
4589 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4591 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4592 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4593 Subtarget->hasSSE2(), DAG);
4594 SmallVector<int, 8> MaskVec;
4595 for (unsigned i = 0; i < NumElems; i++)
4596 MaskVec.push_back(i == Idx ? 0 : 1);
4597 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4601 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4602 if (Values.size() == 1) {
4603 if (EVTBits == 32) {
4604 // Instead of a shuffle like this:
4605 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4606 // Check if it's possible to issue this instead.
4607 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4608 unsigned Idx = CountTrailingZeros_32(NonZeros);
4609 SDValue Item = Op.getOperand(Idx);
4610 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4611 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4616 // A vector full of immediates; various special cases are already
4617 // handled, so this is best done with a single constant-pool load.
4621 // Let legalizer expand 2-wide build_vectors.
4622 if (EVTBits == 64) {
4623 if (NumNonZero == 1) {
4624 // One half is zero or undef.
4625 unsigned Idx = CountTrailingZeros_32(NonZeros);
4626 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4627 Op.getOperand(Idx));
4628 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4629 Subtarget->hasSSE2(), DAG);
4634 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4635 if (EVTBits == 8 && NumElems == 16) {
4636 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4638 if (V.getNode()) return V;
4641 if (EVTBits == 16 && NumElems == 8) {
4642 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4644 if (V.getNode()) return V;
4647 // If element VT is == 32 bits, turn it into a number of shuffles.
4648 SmallVector<SDValue, 8> V;
4650 if (NumElems == 4 && NumZero > 0) {
4651 for (unsigned i = 0; i < 4; ++i) {
4652 bool isZero = !(NonZeros & (1 << i));
4654 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4656 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4659 for (unsigned i = 0; i < 2; ++i) {
4660 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4663 V[i] = V[i*2]; // Must be a zero vector.
4666 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4669 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4672 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4677 SmallVector<int, 8> MaskVec;
4678 bool Reverse = (NonZeros & 0x3) == 2;
4679 for (unsigned i = 0; i < 2; ++i)
4680 MaskVec.push_back(Reverse ? 1-i : i);
4681 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4682 for (unsigned i = 0; i < 2; ++i)
4683 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4684 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4687 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4688 // Check for a build vector of consecutive loads.
4689 for (unsigned i = 0; i < NumElems; ++i)
4690 V[i] = Op.getOperand(i);
4692 // Check for elements which are consecutive loads.
4693 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4697 // For SSE 4.1, use insertps to put the high elements into the low element.
4698 if (getSubtarget()->hasSSE41()) {
4700 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4701 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4703 Result = DAG.getUNDEF(VT);
4705 for (unsigned i = 1; i < NumElems; ++i) {
4706 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4707 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4708 Op.getOperand(i), DAG.getIntPtrConstant(i));
4713 // Otherwise, expand into a number of unpckl*, start by extending each of
4714 // our (non-undef) elements to the full vector width with the element in the
4715 // bottom slot of the vector (which generates no code for SSE).
4716 for (unsigned i = 0; i < NumElems; ++i) {
4717 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4718 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4720 V[i] = DAG.getUNDEF(VT);
4723 // Next, we iteratively mix elements, e.g. for v4f32:
4724 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4725 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4726 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4727 unsigned EltStride = NumElems >> 1;
4728 while (EltStride != 0) {
4729 for (unsigned i = 0; i < EltStride; ++i) {
4730 // If V[i+EltStride] is undef and this is the first round of mixing,
4731 // then it is safe to just drop this shuffle: V[i] is already in the
4732 // right place, the one element (since it's the first round) being
4733 // inserted as undef can be dropped. This isn't safe for successive
4734 // rounds because they will permute elements within both vectors.
4735 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4736 EltStride == NumElems/2)
4739 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4749 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4750 // We support concatenate two MMX registers and place them in a MMX
4751 // register. This is better than doing a stack convert.
4752 DebugLoc dl = Op.getDebugLoc();
4753 EVT ResVT = Op.getValueType();
4754 assert(Op.getNumOperands() == 2);
4755 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4756 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4758 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4759 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4760 InVec = Op.getOperand(1);
4761 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4762 unsigned NumElts = ResVT.getVectorNumElements();
4763 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4764 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4765 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4767 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4768 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4769 Mask[0] = 0; Mask[1] = 2;
4770 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4772 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4775 // v8i16 shuffles - Prefer shuffles in the following order:
4776 // 1. [all] pshuflw, pshufhw, optional move
4777 // 2. [ssse3] 1 x pshufb
4778 // 3. [ssse3] 2 x pshufb + 1 x por
4779 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4781 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4782 SelectionDAG &DAG) const {
4783 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4784 SDValue V1 = SVOp->getOperand(0);
4785 SDValue V2 = SVOp->getOperand(1);
4786 DebugLoc dl = SVOp->getDebugLoc();
4787 SmallVector<int, 8> MaskVals;
4789 // Determine if more than 1 of the words in each of the low and high quadwords
4790 // of the result come from the same quadword of one of the two inputs. Undef
4791 // mask values count as coming from any quadword, for better codegen.
4792 SmallVector<unsigned, 4> LoQuad(4);
4793 SmallVector<unsigned, 4> HiQuad(4);
4794 BitVector InputQuads(4);
4795 for (unsigned i = 0; i < 8; ++i) {
4796 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4797 int EltIdx = SVOp->getMaskElt(i);
4798 MaskVals.push_back(EltIdx);
4807 InputQuads.set(EltIdx / 4);
4810 int BestLoQuad = -1;
4811 unsigned MaxQuad = 1;
4812 for (unsigned i = 0; i < 4; ++i) {
4813 if (LoQuad[i] > MaxQuad) {
4815 MaxQuad = LoQuad[i];
4819 int BestHiQuad = -1;
4821 for (unsigned i = 0; i < 4; ++i) {
4822 if (HiQuad[i] > MaxQuad) {
4824 MaxQuad = HiQuad[i];
4828 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4829 // of the two input vectors, shuffle them into one input vector so only a
4830 // single pshufb instruction is necessary. If There are more than 2 input
4831 // quads, disable the next transformation since it does not help SSSE3.
4832 bool V1Used = InputQuads[0] || InputQuads[1];
4833 bool V2Used = InputQuads[2] || InputQuads[3];
4834 if (Subtarget->hasSSSE3()) {
4835 if (InputQuads.count() == 2 && V1Used && V2Used) {
4836 BestLoQuad = InputQuads.find_first();
4837 BestHiQuad = InputQuads.find_next(BestLoQuad);
4839 if (InputQuads.count() > 2) {
4845 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4846 // the shuffle mask. If a quad is scored as -1, that means that it contains
4847 // words from all 4 input quadwords.
4849 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4850 SmallVector<int, 8> MaskV;
4851 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4852 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4853 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4854 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4855 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4856 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4858 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4859 // source words for the shuffle, to aid later transformations.
4860 bool AllWordsInNewV = true;
4861 bool InOrder[2] = { true, true };
4862 for (unsigned i = 0; i != 8; ++i) {
4863 int idx = MaskVals[i];
4865 InOrder[i/4] = false;
4866 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4868 AllWordsInNewV = false;
4872 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4873 if (AllWordsInNewV) {
4874 for (int i = 0; i != 8; ++i) {
4875 int idx = MaskVals[i];
4878 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4879 if ((idx != i) && idx < 4)
4881 if ((idx != i) && idx > 3)
4890 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4891 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4892 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4893 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4894 unsigned TargetMask = 0;
4895 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4896 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4897 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4898 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4899 V1 = NewV.getOperand(0);
4900 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4904 // If we have SSSE3, and all words of the result are from 1 input vector,
4905 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4906 // is present, fall back to case 4.
4907 if (Subtarget->hasSSSE3()) {
4908 SmallVector<SDValue,16> pshufbMask;
4910 // If we have elements from both input vectors, set the high bit of the
4911 // shuffle mask element to zero out elements that come from V2 in the V1
4912 // mask, and elements that come from V1 in the V2 mask, so that the two
4913 // results can be OR'd together.
4914 bool TwoInputs = V1Used && V2Used;
4915 for (unsigned i = 0; i != 8; ++i) {
4916 int EltIdx = MaskVals[i] * 2;
4917 if (TwoInputs && (EltIdx >= 16)) {
4918 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4919 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4922 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4923 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4925 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4926 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4927 DAG.getNode(ISD::BUILD_VECTOR, dl,
4928 MVT::v16i8, &pshufbMask[0], 16));
4930 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4932 // Calculate the shuffle mask for the second input, shuffle it, and
4933 // OR it with the first shuffled input.
4935 for (unsigned i = 0; i != 8; ++i) {
4936 int EltIdx = MaskVals[i] * 2;
4938 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4939 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4942 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4943 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4945 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4946 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4947 DAG.getNode(ISD::BUILD_VECTOR, dl,
4948 MVT::v16i8, &pshufbMask[0], 16));
4949 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4950 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4953 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4954 // and update MaskVals with new element order.
4955 BitVector InOrder(8);
4956 if (BestLoQuad >= 0) {
4957 SmallVector<int, 8> MaskV;
4958 for (int i = 0; i != 4; ++i) {
4959 int idx = MaskVals[i];
4961 MaskV.push_back(-1);
4963 } else if ((idx / 4) == BestLoQuad) {
4964 MaskV.push_back(idx & 3);
4967 MaskV.push_back(-1);
4970 for (unsigned i = 4; i != 8; ++i)
4972 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4975 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4976 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4978 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4982 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4983 // and update MaskVals with the new element order.
4984 if (BestHiQuad >= 0) {
4985 SmallVector<int, 8> MaskV;
4986 for (unsigned i = 0; i != 4; ++i)
4988 for (unsigned i = 4; i != 8; ++i) {
4989 int idx = MaskVals[i];
4991 MaskV.push_back(-1);
4993 } else if ((idx / 4) == BestHiQuad) {
4994 MaskV.push_back((idx & 3) + 4);
4997 MaskV.push_back(-1);
5000 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5003 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5004 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5006 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5010 // In case BestHi & BestLo were both -1, which means each quadword has a word
5011 // from each of the four input quadwords, calculate the InOrder bitvector now
5012 // before falling through to the insert/extract cleanup.
5013 if (BestLoQuad == -1 && BestHiQuad == -1) {
5015 for (int i = 0; i != 8; ++i)
5016 if (MaskVals[i] < 0 || MaskVals[i] == i)
5020 // The other elements are put in the right place using pextrw and pinsrw.
5021 for (unsigned i = 0; i != 8; ++i) {
5024 int EltIdx = MaskVals[i];
5027 SDValue ExtOp = (EltIdx < 8)
5028 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5029 DAG.getIntPtrConstant(EltIdx))
5030 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5031 DAG.getIntPtrConstant(EltIdx - 8));
5032 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5033 DAG.getIntPtrConstant(i));
5038 // v16i8 shuffles - Prefer shuffles in the following order:
5039 // 1. [ssse3] 1 x pshufb
5040 // 2. [ssse3] 2 x pshufb + 1 x por
5041 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5043 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5045 const X86TargetLowering &TLI) {
5046 SDValue V1 = SVOp->getOperand(0);
5047 SDValue V2 = SVOp->getOperand(1);
5048 DebugLoc dl = SVOp->getDebugLoc();
5049 SmallVector<int, 16> MaskVals;
5050 SVOp->getMask(MaskVals);
5052 // If we have SSSE3, case 1 is generated when all result bytes come from
5053 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5054 // present, fall back to case 3.
5055 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5058 for (unsigned i = 0; i < 16; ++i) {
5059 int EltIdx = MaskVals[i];
5068 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5069 if (TLI.getSubtarget()->hasSSSE3()) {
5070 SmallVector<SDValue,16> pshufbMask;
5072 // If all result elements are from one input vector, then only translate
5073 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5075 // Otherwise, we have elements from both input vectors, and must zero out
5076 // elements that come from V2 in the first mask, and V1 in the second mask
5077 // so that we can OR them together.
5078 bool TwoInputs = !(V1Only || V2Only);
5079 for (unsigned i = 0; i != 16; ++i) {
5080 int EltIdx = MaskVals[i];
5081 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5082 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5085 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5087 // If all the elements are from V2, assign it to V1 and return after
5088 // building the first pshufb.
5091 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5092 DAG.getNode(ISD::BUILD_VECTOR, dl,
5093 MVT::v16i8, &pshufbMask[0], 16));
5097 // Calculate the shuffle mask for the second input, shuffle it, and
5098 // OR it with the first shuffled input.
5100 for (unsigned i = 0; i != 16; ++i) {
5101 int EltIdx = MaskVals[i];
5103 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5106 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5108 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5109 DAG.getNode(ISD::BUILD_VECTOR, dl,
5110 MVT::v16i8, &pshufbMask[0], 16));
5111 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5114 // No SSSE3 - Calculate in place words and then fix all out of place words
5115 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5116 // the 16 different words that comprise the two doublequadword input vectors.
5117 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5118 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5119 SDValue NewV = V2Only ? V2 : V1;
5120 for (int i = 0; i != 8; ++i) {
5121 int Elt0 = MaskVals[i*2];
5122 int Elt1 = MaskVals[i*2+1];
5124 // This word of the result is all undef, skip it.
5125 if (Elt0 < 0 && Elt1 < 0)
5128 // This word of the result is already in the correct place, skip it.
5129 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5131 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5134 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5135 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5138 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5139 // using a single extract together, load it and store it.
5140 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5141 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5142 DAG.getIntPtrConstant(Elt1 / 2));
5143 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5144 DAG.getIntPtrConstant(i));
5148 // If Elt1 is defined, extract it from the appropriate source. If the
5149 // source byte is not also odd, shift the extracted word left 8 bits
5150 // otherwise clear the bottom 8 bits if we need to do an or.
5152 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5153 DAG.getIntPtrConstant(Elt1 / 2));
5154 if ((Elt1 & 1) == 0)
5155 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5157 TLI.getShiftAmountTy(InsElt.getValueType())));
5159 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5160 DAG.getConstant(0xFF00, MVT::i16));
5162 // If Elt0 is defined, extract it from the appropriate source. If the
5163 // source byte is not also even, shift the extracted word right 8 bits. If
5164 // Elt1 was also defined, OR the extracted values together before
5165 // inserting them in the result.
5167 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5168 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5169 if ((Elt0 & 1) != 0)
5170 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5172 TLI.getShiftAmountTy(InsElt0.getValueType())));
5174 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5175 DAG.getConstant(0x00FF, MVT::i16));
5176 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5179 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5180 DAG.getIntPtrConstant(i));
5182 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5185 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5186 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5187 /// done when every pair / quad of shuffle mask elements point to elements in
5188 /// the right sequence. e.g.
5189 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5191 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5192 SelectionDAG &DAG, DebugLoc dl) {
5193 EVT VT = SVOp->getValueType(0);
5194 SDValue V1 = SVOp->getOperand(0);
5195 SDValue V2 = SVOp->getOperand(1);
5196 unsigned NumElems = VT.getVectorNumElements();
5197 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5199 switch (VT.getSimpleVT().SimpleTy) {
5200 default: assert(false && "Unexpected!");
5201 case MVT::v4f32: NewVT = MVT::v2f64; break;
5202 case MVT::v4i32: NewVT = MVT::v2i64; break;
5203 case MVT::v8i16: NewVT = MVT::v4i32; break;
5204 case MVT::v16i8: NewVT = MVT::v4i32; break;
5207 int Scale = NumElems / NewWidth;
5208 SmallVector<int, 8> MaskVec;
5209 for (unsigned i = 0; i < NumElems; i += Scale) {
5211 for (int j = 0; j < Scale; ++j) {
5212 int EltIdx = SVOp->getMaskElt(i+j);
5216 StartIdx = EltIdx - (EltIdx % Scale);
5217 if (EltIdx != StartIdx + j)
5221 MaskVec.push_back(-1);
5223 MaskVec.push_back(StartIdx / Scale);
5226 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5227 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5228 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5231 /// getVZextMovL - Return a zero-extending vector move low node.
5233 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5234 SDValue SrcOp, SelectionDAG &DAG,
5235 const X86Subtarget *Subtarget, DebugLoc dl) {
5236 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5237 LoadSDNode *LD = NULL;
5238 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5239 LD = dyn_cast<LoadSDNode>(SrcOp);
5241 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5243 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5244 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5245 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5246 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5247 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5249 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5250 return DAG.getNode(ISD::BITCAST, dl, VT,
5251 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5252 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5260 return DAG.getNode(ISD::BITCAST, dl, VT,
5261 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5262 DAG.getNode(ISD::BITCAST, dl,
5266 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5269 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5270 SDValue V1 = SVOp->getOperand(0);
5271 SDValue V2 = SVOp->getOperand(1);
5272 DebugLoc dl = SVOp->getDebugLoc();
5273 EVT VT = SVOp->getValueType(0);
5275 SmallVector<std::pair<int, int>, 8> Locs;
5277 SmallVector<int, 8> Mask1(4U, -1);
5278 SmallVector<int, 8> PermMask;
5279 SVOp->getMask(PermMask);
5283 for (unsigned i = 0; i != 4; ++i) {
5284 int Idx = PermMask[i];
5286 Locs[i] = std::make_pair(-1, -1);
5288 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5290 Locs[i] = std::make_pair(0, NumLo);
5294 Locs[i] = std::make_pair(1, NumHi);
5296 Mask1[2+NumHi] = Idx;
5302 if (NumLo <= 2 && NumHi <= 2) {
5303 // If no more than two elements come from either vector. This can be
5304 // implemented with two shuffles. First shuffle gather the elements.
5305 // The second shuffle, which takes the first shuffle as both of its
5306 // vector operands, put the elements into the right order.
5307 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5309 SmallVector<int, 8> Mask2(4U, -1);
5311 for (unsigned i = 0; i != 4; ++i) {
5312 if (Locs[i].first == -1)
5315 unsigned Idx = (i < 2) ? 0 : 4;
5316 Idx += Locs[i].first * 2 + Locs[i].second;
5321 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5322 } else if (NumLo == 3 || NumHi == 3) {
5323 // Otherwise, we must have three elements from one vector, call it X, and
5324 // one element from the other, call it Y. First, use a shufps to build an
5325 // intermediate vector with the one element from Y and the element from X
5326 // that will be in the same half in the final destination (the indexes don't
5327 // matter). Then, use a shufps to build the final vector, taking the half
5328 // containing the element from Y from the intermediate, and the other half
5331 // Normalize it so the 3 elements come from V1.
5332 CommuteVectorShuffleMask(PermMask, VT);
5336 // Find the element from V2.
5338 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5339 int Val = PermMask[HiIndex];
5346 Mask1[0] = PermMask[HiIndex];
5348 Mask1[2] = PermMask[HiIndex^1];
5350 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5353 Mask1[0] = PermMask[0];
5354 Mask1[1] = PermMask[1];
5355 Mask1[2] = HiIndex & 1 ? 6 : 4;
5356 Mask1[3] = HiIndex & 1 ? 4 : 6;
5357 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5359 Mask1[0] = HiIndex & 1 ? 2 : 0;
5360 Mask1[1] = HiIndex & 1 ? 0 : 2;
5361 Mask1[2] = PermMask[2];
5362 Mask1[3] = PermMask[3];
5367 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5371 // Break it into (shuffle shuffle_hi, shuffle_lo).
5374 SmallVector<int,8> LoMask(4U, -1);
5375 SmallVector<int,8> HiMask(4U, -1);
5377 SmallVector<int,8> *MaskPtr = &LoMask;
5378 unsigned MaskIdx = 0;
5381 for (unsigned i = 0; i != 4; ++i) {
5388 int Idx = PermMask[i];
5390 Locs[i] = std::make_pair(-1, -1);
5391 } else if (Idx < 4) {
5392 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5393 (*MaskPtr)[LoIdx] = Idx;
5396 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5397 (*MaskPtr)[HiIdx] = Idx;
5402 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5403 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5404 SmallVector<int, 8> MaskOps;
5405 for (unsigned i = 0; i != 4; ++i) {
5406 if (Locs[i].first == -1) {
5407 MaskOps.push_back(-1);
5409 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5410 MaskOps.push_back(Idx);
5413 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5416 static bool MayFoldVectorLoad(SDValue V) {
5417 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5418 V = V.getOperand(0);
5419 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5420 V = V.getOperand(0);
5426 // FIXME: the version above should always be used. Since there's
5427 // a bug where several vector shuffles can't be folded because the
5428 // DAG is not updated during lowering and a node claims to have two
5429 // uses while it only has one, use this version, and let isel match
5430 // another instruction if the load really happens to have more than
5431 // one use. Remove this version after this bug get fixed.
5432 // rdar://8434668, PR8156
5433 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5434 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5435 V = V.getOperand(0);
5436 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5437 V = V.getOperand(0);
5438 if (ISD::isNormalLoad(V.getNode()))
5443 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5444 /// a vector extract, and if both can be later optimized into a single load.
5445 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5446 /// here because otherwise a target specific shuffle node is going to be
5447 /// emitted for this shuffle, and the optimization not done.
5448 /// FIXME: This is probably not the best approach, but fix the problem
5449 /// until the right path is decided.
5451 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5452 const TargetLowering &TLI) {
5453 EVT VT = V.getValueType();
5454 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5456 // Be sure that the vector shuffle is present in a pattern like this:
5457 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5461 SDNode *N = *V.getNode()->use_begin();
5462 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5465 SDValue EltNo = N->getOperand(1);
5466 if (!isa<ConstantSDNode>(EltNo))
5469 // If the bit convert changed the number of elements, it is unsafe
5470 // to examine the mask.
5471 bool HasShuffleIntoBitcast = false;
5472 if (V.getOpcode() == ISD::BITCAST) {
5473 EVT SrcVT = V.getOperand(0).getValueType();
5474 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5476 V = V.getOperand(0);
5477 HasShuffleIntoBitcast = true;
5480 // Select the input vector, guarding against out of range extract vector.
5481 unsigned NumElems = VT.getVectorNumElements();
5482 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5483 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5484 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5486 // Skip one more bit_convert if necessary
5487 if (V.getOpcode() == ISD::BITCAST)
5488 V = V.getOperand(0);
5490 if (ISD::isNormalLoad(V.getNode())) {
5491 // Is the original load suitable?
5492 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5494 // FIXME: avoid the multi-use bug that is preventing lots of
5495 // of foldings to be detected, this is still wrong of course, but
5496 // give the temporary desired behavior, and if it happens that
5497 // the load has real more uses, during isel it will not fold, and
5498 // will generate poor code.
5499 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5502 if (!HasShuffleIntoBitcast)
5505 // If there's a bitcast before the shuffle, check if the load type and
5506 // alignment is valid.
5507 unsigned Align = LN0->getAlignment();
5509 TLI.getTargetData()->getABITypeAlignment(
5510 VT.getTypeForEVT(*DAG.getContext()));
5512 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5520 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5521 EVT VT = Op.getValueType();
5523 // Canonizalize to v2f64.
5524 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5525 return DAG.getNode(ISD::BITCAST, dl, VT,
5526 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5531 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5533 SDValue V1 = Op.getOperand(0);
5534 SDValue V2 = Op.getOperand(1);
5535 EVT VT = Op.getValueType();
5537 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5539 if (HasSSE2 && VT == MVT::v2f64)
5540 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5543 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5547 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5548 SDValue V1 = Op.getOperand(0);
5549 SDValue V2 = Op.getOperand(1);
5550 EVT VT = Op.getValueType();
5552 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5553 "unsupported shuffle type");
5555 if (V2.getOpcode() == ISD::UNDEF)
5559 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5563 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5564 SDValue V1 = Op.getOperand(0);
5565 SDValue V2 = Op.getOperand(1);
5566 EVT VT = Op.getValueType();
5567 unsigned NumElems = VT.getVectorNumElements();
5569 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5570 // operand of these instructions is only memory, so check if there's a
5571 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5573 bool CanFoldLoad = false;
5575 // Trivial case, when V2 comes from a load.
5576 if (MayFoldVectorLoad(V2))
5579 // When V1 is a load, it can be folded later into a store in isel, example:
5580 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5582 // (MOVLPSmr addr:$src1, VR128:$src2)
5583 // So, recognize this potential and also use MOVLPS or MOVLPD
5584 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5587 // Both of them can't be memory operations though.
5588 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5589 CanFoldLoad = false;
5592 if (HasSSE2 && NumElems == 2)
5593 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5596 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5599 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5600 // movl and movlp will both match v2i64, but v2i64 is never matched by
5601 // movl earlier because we make it strict to avoid messing with the movlp load
5602 // folding logic (see the code above getMOVLP call). Match it here then,
5603 // this is horrible, but will stay like this until we move all shuffle
5604 // matching to x86 specific nodes. Note that for the 1st condition all
5605 // types are matched with movsd.
5606 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5607 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5609 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5612 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5614 // Invert the operand order and use SHUFPS to match it.
5615 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5616 X86::getShuffleSHUFImmediate(SVOp), DAG);
5619 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5620 switch(VT.getSimpleVT().SimpleTy) {
5621 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5622 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5624 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5626 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5627 case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5628 case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5629 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5630 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5632 llvm_unreachable("Unknown type for unpckl");
5637 static inline unsigned getUNPCKHOpcode(EVT VT) {
5638 switch(VT.getSimpleVT().SimpleTy) {
5639 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5640 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5641 case MVT::v4f32: return X86ISD::UNPCKHPS;
5642 case MVT::v2f64: return X86ISD::UNPCKHPD;
5643 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5644 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5646 llvm_unreachable("Unknown type for unpckh");
5652 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5653 const TargetLowering &TLI,
5654 const X86Subtarget *Subtarget) {
5655 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5656 EVT VT = Op.getValueType();
5657 DebugLoc dl = Op.getDebugLoc();
5658 SDValue V1 = Op.getOperand(0);
5659 SDValue V2 = Op.getOperand(1);
5661 if (isZeroShuffle(SVOp))
5662 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5664 // Handle splat operations
5665 if (SVOp->isSplat()) {
5666 // Special case, this is the only place now where it's
5667 // allowed to return a vector_shuffle operation without
5668 // using a target specific node, because *hopefully* it
5669 // will be optimized away by the dag combiner.
5670 if (VT.getVectorNumElements() <= 4 &&
5671 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5674 // Handle splats by matching through known masks
5675 if (VT.getVectorNumElements() <= 4)
5678 // Canonicalize all of the remaining to v4f32.
5679 return PromoteSplat(SVOp, DAG);
5682 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5684 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5685 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5686 if (NewOp.getNode())
5687 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5688 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5689 // FIXME: Figure out a cleaner way to do this.
5690 // Try to make use of movq to zero out the top part.
5691 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5692 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5693 if (NewOp.getNode()) {
5694 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5695 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5696 DAG, Subtarget, dl);
5698 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5699 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5700 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5701 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5702 DAG, Subtarget, dl);
5709 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5710 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5711 SDValue V1 = Op.getOperand(0);
5712 SDValue V2 = Op.getOperand(1);
5713 EVT VT = Op.getValueType();
5714 DebugLoc dl = Op.getDebugLoc();
5715 unsigned NumElems = VT.getVectorNumElements();
5716 bool isMMX = VT.getSizeInBits() == 64;
5717 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5718 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5719 bool V1IsSplat = false;
5720 bool V2IsSplat = false;
5721 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5722 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5723 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5724 MachineFunction &MF = DAG.getMachineFunction();
5725 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5727 // Shuffle operations on MMX not supported.
5731 // Vector shuffle lowering takes 3 steps:
5733 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5734 // narrowing and commutation of operands should be handled.
5735 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5737 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5738 // so the shuffle can be broken into other shuffles and the legalizer can
5739 // try the lowering again.
5741 // The general ideia is that no vector_shuffle operation should be left to
5742 // be matched during isel, all of them must be converted to a target specific
5745 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5746 // narrowing and commutation of operands should be handled. The actual code
5747 // doesn't include all of those, work in progress...
5748 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5749 if (NewOp.getNode())
5752 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5753 // unpckh_undef). Only use pshufd if speed is more important than size.
5754 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5755 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5756 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5757 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5758 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5759 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5761 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5762 RelaxedMayFoldVectorLoad(V1))
5763 return getMOVDDup(Op, dl, V1, DAG);
5765 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5766 return getMOVHighToLow(Op, dl, DAG);
5768 // Use to match splats
5769 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5770 (VT == MVT::v2f64 || VT == MVT::v2i64))
5771 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5773 if (X86::isPSHUFDMask(SVOp)) {
5774 // The actual implementation will match the mask in the if above and then
5775 // during isel it can match several different instructions, not only pshufd
5776 // as its name says, sad but true, emulate the behavior for now...
5777 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5778 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5780 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5782 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5783 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5785 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5786 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5789 if (VT == MVT::v4f32)
5790 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5794 // Check if this can be converted into a logical shift.
5795 bool isLeft = false;
5798 bool isShift = getSubtarget()->hasSSE2() &&
5799 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5800 if (isShift && ShVal.hasOneUse()) {
5801 // If the shifted value has multiple uses, it may be cheaper to use
5802 // v_set0 + movlhps or movhlps, etc.
5803 EVT EltVT = VT.getVectorElementType();
5804 ShAmt *= EltVT.getSizeInBits();
5805 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5808 if (X86::isMOVLMask(SVOp)) {
5811 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5812 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5813 if (!X86::isMOVLPMask(SVOp)) {
5814 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5815 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5817 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5818 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5822 // FIXME: fold these into legal mask.
5823 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5824 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5826 if (X86::isMOVHLPSMask(SVOp))
5827 return getMOVHighToLow(Op, dl, DAG);
5829 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5830 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5832 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5833 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5835 if (X86::isMOVLPMask(SVOp))
5836 return getMOVLP(Op, dl, DAG, HasSSE2);
5838 if (ShouldXformToMOVHLPS(SVOp) ||
5839 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5840 return CommuteVectorShuffle(SVOp, DAG);
5843 // No better options. Use a vshl / vsrl.
5844 EVT EltVT = VT.getVectorElementType();
5845 ShAmt *= EltVT.getSizeInBits();
5846 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5849 bool Commuted = false;
5850 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5851 // 1,1,1,1 -> v8i16 though.
5852 V1IsSplat = isSplatVector(V1.getNode());
5853 V2IsSplat = isSplatVector(V2.getNode());
5855 // Canonicalize the splat or undef, if present, to be on the RHS.
5856 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5857 Op = CommuteVectorShuffle(SVOp, DAG);
5858 SVOp = cast<ShuffleVectorSDNode>(Op);
5859 V1 = SVOp->getOperand(0);
5860 V2 = SVOp->getOperand(1);
5861 std::swap(V1IsSplat, V2IsSplat);
5862 std::swap(V1IsUndef, V2IsUndef);
5866 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5867 // Shuffling low element of v1 into undef, just return v1.
5870 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5871 // the instruction selector will not match, so get a canonical MOVL with
5872 // swapped operands to undo the commute.
5873 return getMOVL(DAG, dl, VT, V2, V1);
5876 if (X86::isUNPCKLMask(SVOp))
5877 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5878 dl, VT, V1, V2, DAG);
5880 if (X86::isUNPCKHMask(SVOp))
5881 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5884 // Normalize mask so all entries that point to V2 points to its first
5885 // element then try to match unpck{h|l} again. If match, return a
5886 // new vector_shuffle with the corrected mask.
5887 SDValue NewMask = NormalizeMask(SVOp, DAG);
5888 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5889 if (NSVOp != SVOp) {
5890 if (X86::isUNPCKLMask(NSVOp, true)) {
5892 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5899 // Commute is back and try unpck* again.
5900 // FIXME: this seems wrong.
5901 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5902 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5904 if (X86::isUNPCKLMask(NewSVOp))
5905 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5906 dl, VT, V2, V1, DAG);
5908 if (X86::isUNPCKHMask(NewSVOp))
5909 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5912 // Normalize the node to match x86 shuffle ops if needed
5913 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5914 return CommuteVectorShuffle(SVOp, DAG);
5916 // The checks below are all present in isShuffleMaskLegal, but they are
5917 // inlined here right now to enable us to directly emit target specific
5918 // nodes, and remove one by one until they don't return Op anymore.
5919 SmallVector<int, 16> M;
5922 if (isPALIGNRMask(M, VT, HasSSSE3))
5923 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5924 X86::getShufflePALIGNRImmediate(SVOp),
5927 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5928 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5929 if (VT == MVT::v2f64) {
5930 X86ISD::NodeType Opcode =
5931 getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5932 return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5934 if (VT == MVT::v2i64)
5935 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5938 if (isPSHUFHWMask(M, VT))
5939 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5940 X86::getShufflePSHUFHWImmediate(SVOp),
5943 if (isPSHUFLWMask(M, VT))
5944 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5945 X86::getShufflePSHUFLWImmediate(SVOp),
5948 if (isSHUFPMask(M, VT)) {
5949 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5950 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5951 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5953 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5954 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5958 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5959 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5960 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5961 dl, VT, V1, V1, DAG);
5962 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5963 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5964 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5966 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5967 if (VT == MVT::v8i16) {
5968 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5969 if (NewOp.getNode())
5973 if (VT == MVT::v16i8) {
5974 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5975 if (NewOp.getNode())
5979 // Handle all 4 wide cases with a number of shuffles.
5981 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5987 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5988 SelectionDAG &DAG) const {
5989 EVT VT = Op.getValueType();
5990 DebugLoc dl = Op.getDebugLoc();
5991 if (VT.getSizeInBits() == 8) {
5992 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5993 Op.getOperand(0), Op.getOperand(1));
5994 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5995 DAG.getValueType(VT));
5996 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5997 } else if (VT.getSizeInBits() == 16) {
5998 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5999 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6001 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6002 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6003 DAG.getNode(ISD::BITCAST, dl,
6007 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6008 Op.getOperand(0), Op.getOperand(1));
6009 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6010 DAG.getValueType(VT));
6011 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6012 } else if (VT == MVT::f32) {
6013 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6014 // the result back to FR32 register. It's only worth matching if the
6015 // result has a single use which is a store or a bitcast to i32. And in
6016 // the case of a store, it's not worth it if the index is a constant 0,
6017 // because a MOVSSmr can be used instead, which is smaller and faster.
6018 if (!Op.hasOneUse())
6020 SDNode *User = *Op.getNode()->use_begin();
6021 if ((User->getOpcode() != ISD::STORE ||
6022 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6023 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6024 (User->getOpcode() != ISD::BITCAST ||
6025 User->getValueType(0) != MVT::i32))
6027 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6028 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6031 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6032 } else if (VT == MVT::i32) {
6033 // ExtractPS works with constant index.
6034 if (isa<ConstantSDNode>(Op.getOperand(1)))
6042 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6043 SelectionDAG &DAG) const {
6044 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6047 SDValue Vec = Op.getOperand(0);
6048 EVT VecVT = Vec.getValueType();
6050 // If this is a 256-bit vector result, first extract the 128-bit
6051 // vector and then extract from the 128-bit vector.
6052 if (VecVT.getSizeInBits() > 128) {
6053 DebugLoc dl = Op.getNode()->getDebugLoc();
6054 unsigned NumElems = VecVT.getVectorNumElements();
6055 SDValue Idx = Op.getOperand(1);
6057 if (!isa<ConstantSDNode>(Idx))
6060 unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6061 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6063 // Get the 128-bit vector.
6064 bool Upper = IdxVal >= ExtractNumElems;
6065 Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6068 SDValue ScaledIdx = Idx;
6070 ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6071 DAG.getConstant(ExtractNumElems,
6072 Idx.getValueType()));
6073 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6077 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6079 if (Subtarget->hasSSE41()) {
6080 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6085 EVT VT = Op.getValueType();
6086 DebugLoc dl = Op.getDebugLoc();
6087 // TODO: handle v16i8.
6088 if (VT.getSizeInBits() == 16) {
6089 SDValue Vec = Op.getOperand(0);
6090 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6092 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6093 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6094 DAG.getNode(ISD::BITCAST, dl,
6097 // Transform it so it match pextrw which produces a 32-bit result.
6098 EVT EltVT = MVT::i32;
6099 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6100 Op.getOperand(0), Op.getOperand(1));
6101 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6102 DAG.getValueType(VT));
6103 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6104 } else if (VT.getSizeInBits() == 32) {
6105 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6109 // SHUFPS the element to the lowest double word, then movss.
6110 int Mask[4] = { Idx, -1, -1, -1 };
6111 EVT VVT = Op.getOperand(0).getValueType();
6112 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6113 DAG.getUNDEF(VVT), Mask);
6114 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6115 DAG.getIntPtrConstant(0));
6116 } else if (VT.getSizeInBits() == 64) {
6117 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6118 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6119 // to match extract_elt for f64.
6120 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6124 // UNPCKHPD the element to the lowest double word, then movsd.
6125 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6126 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6127 int Mask[2] = { 1, -1 };
6128 EVT VVT = Op.getOperand(0).getValueType();
6129 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6130 DAG.getUNDEF(VVT), Mask);
6131 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6132 DAG.getIntPtrConstant(0));
6139 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6140 SelectionDAG &DAG) const {
6141 EVT VT = Op.getValueType();
6142 EVT EltVT = VT.getVectorElementType();
6143 DebugLoc dl = Op.getDebugLoc();
6145 SDValue N0 = Op.getOperand(0);
6146 SDValue N1 = Op.getOperand(1);
6147 SDValue N2 = Op.getOperand(2);
6149 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6150 isa<ConstantSDNode>(N2)) {
6152 if (VT == MVT::v8i16)
6153 Opc = X86ISD::PINSRW;
6154 else if (VT == MVT::v16i8)
6155 Opc = X86ISD::PINSRB;
6157 Opc = X86ISD::PINSRB;
6159 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6161 if (N1.getValueType() != MVT::i32)
6162 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6163 if (N2.getValueType() != MVT::i32)
6164 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6165 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6166 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6167 // Bits [7:6] of the constant are the source select. This will always be
6168 // zero here. The DAG Combiner may combine an extract_elt index into these
6169 // bits. For example (insert (extract, 3), 2) could be matched by putting
6170 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6171 // Bits [5:4] of the constant are the destination select. This is the
6172 // value of the incoming immediate.
6173 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6174 // combine either bitwise AND or insert of float 0.0 to set these bits.
6175 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6176 // Create this as a scalar to vector..
6177 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6178 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6179 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6180 // PINSR* works with constant index.
6187 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6188 EVT VT = Op.getValueType();
6189 EVT EltVT = VT.getVectorElementType();
6191 DebugLoc dl = Op.getDebugLoc();
6192 SDValue N0 = Op.getOperand(0);
6193 SDValue N1 = Op.getOperand(1);
6194 SDValue N2 = Op.getOperand(2);
6196 // If this is a 256-bit vector result, first insert into a 128-bit
6197 // vector and then insert into the 256-bit vector.
6198 if (VT.getSizeInBits() > 128) {
6199 if (!isa<ConstantSDNode>(N2))
6202 // Get the 128-bit vector.
6203 unsigned NumElems = VT.getVectorNumElements();
6204 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6205 bool Upper = IdxVal >= NumElems / 2;
6207 SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6210 SDValue ScaledN2 = N2;
6212 ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6213 DAG.getConstant(NumElems /
6214 (VT.getSizeInBits() / 128),
6215 N2.getValueType()));
6216 Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6219 // Insert the 128-bit vector
6220 // FIXME: Why UNDEF?
6221 return Insert128BitVector(N0, Op, N2, DAG, dl);
6224 if (Subtarget->hasSSE41())
6225 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6227 if (EltVT == MVT::i8)
6230 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6231 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6232 // as its second argument.
6233 if (N1.getValueType() != MVT::i32)
6234 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6235 if (N2.getValueType() != MVT::i32)
6236 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6237 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6243 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6244 LLVMContext *Context = DAG.getContext();
6245 DebugLoc dl = Op.getDebugLoc();
6246 EVT OpVT = Op.getValueType();
6248 // If this is a 256-bit vector result, first insert into a 128-bit
6249 // vector and then insert into the 256-bit vector.
6250 if (OpVT.getSizeInBits() > 128) {
6251 // Insert into a 128-bit vector.
6252 EVT VT128 = EVT::getVectorVT(*Context,
6253 OpVT.getVectorElementType(),
6254 OpVT.getVectorNumElements() / 2);
6256 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6258 // Insert the 128-bit vector.
6259 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6260 DAG.getConstant(0, MVT::i32),
6264 if (Op.getValueType() == MVT::v1i64 &&
6265 Op.getOperand(0).getValueType() == MVT::i64)
6266 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6268 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6269 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6270 "Expected an SSE type!");
6271 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6272 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6275 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
6276 // a simple subregister reference or explicit instructions to grab
6277 // upper bits of a vector.
6279 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6280 if (Subtarget->hasAVX()) {
6281 DebugLoc dl = Op.getNode()->getDebugLoc();
6282 SDValue Vec = Op.getNode()->getOperand(0);
6283 SDValue Idx = Op.getNode()->getOperand(1);
6285 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6286 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6287 return Extract128BitVector(Vec, Idx, DAG, dl);
6293 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
6294 // simple superregister reference or explicit instructions to insert
6295 // the upper bits of a vector.
6297 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6298 if (Subtarget->hasAVX()) {
6299 DebugLoc dl = Op.getNode()->getDebugLoc();
6300 SDValue Vec = Op.getNode()->getOperand(0);
6301 SDValue SubVec = Op.getNode()->getOperand(1);
6302 SDValue Idx = Op.getNode()->getOperand(2);
6304 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6305 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6306 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6312 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6313 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6314 // one of the above mentioned nodes. It has to be wrapped because otherwise
6315 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6316 // be used to form addressing mode. These wrapped nodes will be selected
6319 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6320 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6322 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6324 unsigned char OpFlag = 0;
6325 unsigned WrapperKind = X86ISD::Wrapper;
6326 CodeModel::Model M = getTargetMachine().getCodeModel();
6328 if (Subtarget->isPICStyleRIPRel() &&
6329 (M == CodeModel::Small || M == CodeModel::Kernel))
6330 WrapperKind = X86ISD::WrapperRIP;
6331 else if (Subtarget->isPICStyleGOT())
6332 OpFlag = X86II::MO_GOTOFF;
6333 else if (Subtarget->isPICStyleStubPIC())
6334 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6336 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6338 CP->getOffset(), OpFlag);
6339 DebugLoc DL = CP->getDebugLoc();
6340 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6341 // With PIC, the address is actually $g + Offset.
6343 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6344 DAG.getNode(X86ISD::GlobalBaseReg,
6345 DebugLoc(), getPointerTy()),
6352 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6353 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6355 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6357 unsigned char OpFlag = 0;
6358 unsigned WrapperKind = X86ISD::Wrapper;
6359 CodeModel::Model M = getTargetMachine().getCodeModel();
6361 if (Subtarget->isPICStyleRIPRel() &&
6362 (M == CodeModel::Small || M == CodeModel::Kernel))
6363 WrapperKind = X86ISD::WrapperRIP;
6364 else if (Subtarget->isPICStyleGOT())
6365 OpFlag = X86II::MO_GOTOFF;
6366 else if (Subtarget->isPICStyleStubPIC())
6367 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6369 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6371 DebugLoc DL = JT->getDebugLoc();
6372 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6374 // With PIC, the address is actually $g + Offset.
6376 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6377 DAG.getNode(X86ISD::GlobalBaseReg,
6378 DebugLoc(), getPointerTy()),
6385 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6386 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6388 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6390 unsigned char OpFlag = 0;
6391 unsigned WrapperKind = X86ISD::Wrapper;
6392 CodeModel::Model M = getTargetMachine().getCodeModel();
6394 if (Subtarget->isPICStyleRIPRel() &&
6395 (M == CodeModel::Small || M == CodeModel::Kernel))
6396 WrapperKind = X86ISD::WrapperRIP;
6397 else if (Subtarget->isPICStyleGOT())
6398 OpFlag = X86II::MO_GOTOFF;
6399 else if (Subtarget->isPICStyleStubPIC())
6400 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6402 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6404 DebugLoc DL = Op.getDebugLoc();
6405 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6408 // With PIC, the address is actually $g + Offset.
6409 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6410 !Subtarget->is64Bit()) {
6411 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6412 DAG.getNode(X86ISD::GlobalBaseReg,
6413 DebugLoc(), getPointerTy()),
6421 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6422 // Create the TargetBlockAddressAddress node.
6423 unsigned char OpFlags =
6424 Subtarget->ClassifyBlockAddressReference();
6425 CodeModel::Model M = getTargetMachine().getCodeModel();
6426 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6427 DebugLoc dl = Op.getDebugLoc();
6428 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6429 /*isTarget=*/true, OpFlags);
6431 if (Subtarget->isPICStyleRIPRel() &&
6432 (M == CodeModel::Small || M == CodeModel::Kernel))
6433 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6435 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6437 // With PIC, the address is actually $g + Offset.
6438 if (isGlobalRelativeToPICBase(OpFlags)) {
6439 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6440 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6448 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6450 SelectionDAG &DAG) const {
6451 // Create the TargetGlobalAddress node, folding in the constant
6452 // offset if it is legal.
6453 unsigned char OpFlags =
6454 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6455 CodeModel::Model M = getTargetMachine().getCodeModel();
6457 if (OpFlags == X86II::MO_NO_FLAG &&
6458 X86::isOffsetSuitableForCodeModel(Offset, M)) {
6459 // A direct static reference to a global.
6460 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6463 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6466 if (Subtarget->isPICStyleRIPRel() &&
6467 (M == CodeModel::Small || M == CodeModel::Kernel))
6468 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6470 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6472 // With PIC, the address is actually $g + Offset.
6473 if (isGlobalRelativeToPICBase(OpFlags)) {
6474 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6475 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6479 // For globals that require a load from a stub to get the address, emit the
6481 if (isGlobalStubReference(OpFlags))
6482 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6483 MachinePointerInfo::getGOT(), false, false, 0);
6485 // If there was a non-zero offset that we didn't fold, create an explicit
6488 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6489 DAG.getConstant(Offset, getPointerTy()));
6495 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6496 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6497 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6498 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6502 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6503 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6504 unsigned char OperandFlags) {
6505 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6506 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6507 DebugLoc dl = GA->getDebugLoc();
6508 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6509 GA->getValueType(0),
6513 SDValue Ops[] = { Chain, TGA, *InFlag };
6514 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6516 SDValue Ops[] = { Chain, TGA };
6517 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6520 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6521 MFI->setAdjustsStack(true);
6523 SDValue Flag = Chain.getValue(1);
6524 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6527 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6529 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6532 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6533 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6534 DAG.getNode(X86ISD::GlobalBaseReg,
6535 DebugLoc(), PtrVT), InFlag);
6536 InFlag = Chain.getValue(1);
6538 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6541 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6543 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6545 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6546 X86::RAX, X86II::MO_TLSGD);
6549 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6550 // "local exec" model.
6551 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6552 const EVT PtrVT, TLSModel::Model model,
6554 DebugLoc dl = GA->getDebugLoc();
6556 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6557 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6558 is64Bit ? 257 : 256));
6560 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6561 DAG.getIntPtrConstant(0),
6562 MachinePointerInfo(Ptr), false, false, 0);
6564 unsigned char OperandFlags = 0;
6565 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6567 unsigned WrapperKind = X86ISD::Wrapper;
6568 if (model == TLSModel::LocalExec) {
6569 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6570 } else if (is64Bit) {
6571 assert(model == TLSModel::InitialExec);
6572 OperandFlags = X86II::MO_GOTTPOFF;
6573 WrapperKind = X86ISD::WrapperRIP;
6575 assert(model == TLSModel::InitialExec);
6576 OperandFlags = X86II::MO_INDNTPOFF;
6579 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6581 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6582 GA->getValueType(0),
6583 GA->getOffset(), OperandFlags);
6584 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6586 if (model == TLSModel::InitialExec)
6587 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6588 MachinePointerInfo::getGOT(), false, false, 0);
6590 // The address of the thread local variable is the add of the thread
6591 // pointer with the offset of the variable.
6592 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6596 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6598 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6599 const GlobalValue *GV = GA->getGlobal();
6601 if (Subtarget->isTargetELF()) {
6602 // TODO: implement the "local dynamic" model
6603 // TODO: implement the "initial exec"model for pic executables
6605 // If GV is an alias then use the aliasee for determining
6606 // thread-localness.
6607 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6608 GV = GA->resolveAliasedGlobal(false);
6610 TLSModel::Model model
6611 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6614 case TLSModel::GeneralDynamic:
6615 case TLSModel::LocalDynamic: // not implemented
6616 if (Subtarget->is64Bit())
6617 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6618 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6620 case TLSModel::InitialExec:
6621 case TLSModel::LocalExec:
6622 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6623 Subtarget->is64Bit());
6625 } else if (Subtarget->isTargetDarwin()) {
6626 // Darwin only has one model of TLS. Lower to that.
6627 unsigned char OpFlag = 0;
6628 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6629 X86ISD::WrapperRIP : X86ISD::Wrapper;
6631 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6633 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6634 !Subtarget->is64Bit();
6636 OpFlag = X86II::MO_TLVP_PIC_BASE;
6638 OpFlag = X86II::MO_TLVP;
6639 DebugLoc DL = Op.getDebugLoc();
6640 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6641 GA->getValueType(0),
6642 GA->getOffset(), OpFlag);
6643 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6645 // With PIC32, the address is actually $g + Offset.
6647 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6648 DAG.getNode(X86ISD::GlobalBaseReg,
6649 DebugLoc(), getPointerTy()),
6652 // Lowering the machine isd will make sure everything is in the right
6654 SDValue Chain = DAG.getEntryNode();
6655 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6656 SDValue Args[] = { Chain, Offset };
6657 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6659 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6660 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6661 MFI->setAdjustsStack(true);
6663 // And our return value (tls address) is in the standard call return value
6665 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6666 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6670 "TLS not implemented for this target.");
6672 llvm_unreachable("Unreachable");
6677 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6678 /// take a 2 x i32 value to shift plus a shift amount.
6679 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6680 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6681 EVT VT = Op.getValueType();
6682 unsigned VTBits = VT.getSizeInBits();
6683 DebugLoc dl = Op.getDebugLoc();
6684 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6685 SDValue ShOpLo = Op.getOperand(0);
6686 SDValue ShOpHi = Op.getOperand(1);
6687 SDValue ShAmt = Op.getOperand(2);
6688 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6689 DAG.getConstant(VTBits - 1, MVT::i8))
6690 : DAG.getConstant(0, VT);
6693 if (Op.getOpcode() == ISD::SHL_PARTS) {
6694 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6695 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6697 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6698 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6701 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6702 DAG.getConstant(VTBits, MVT::i8));
6703 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6704 AndNode, DAG.getConstant(0, MVT::i8));
6707 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6708 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6709 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6711 if (Op.getOpcode() == ISD::SHL_PARTS) {
6712 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6713 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6715 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6716 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6719 SDValue Ops[2] = { Lo, Hi };
6720 return DAG.getMergeValues(Ops, 2, dl);
6723 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6724 SelectionDAG &DAG) const {
6725 EVT SrcVT = Op.getOperand(0).getValueType();
6727 if (SrcVT.isVector())
6730 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6731 "Unknown SINT_TO_FP to lower!");
6733 // These are really Legal; return the operand so the caller accepts it as
6735 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6737 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6738 Subtarget->is64Bit()) {
6742 DebugLoc dl = Op.getDebugLoc();
6743 unsigned Size = SrcVT.getSizeInBits()/8;
6744 MachineFunction &MF = DAG.getMachineFunction();
6745 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6746 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6747 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6749 MachinePointerInfo::getFixedStack(SSFI),
6751 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6754 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6756 SelectionDAG &DAG) const {
6758 DebugLoc DL = Op.getDebugLoc();
6760 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6762 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6764 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6766 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6768 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
6769 MachineMemOperand *MMO;
6771 int SSFI = FI->getIndex();
6773 DAG.getMachineFunction()
6774 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6775 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6777 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
6778 StackSlot = StackSlot.getOperand(1);
6780 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6781 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6783 Tys, Ops, array_lengthof(Ops),
6787 Chain = Result.getValue(1);
6788 SDValue InFlag = Result.getValue(2);
6790 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6791 // shouldn't be necessary except that RFP cannot be live across
6792 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6793 MachineFunction &MF = DAG.getMachineFunction();
6794 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6795 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6796 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6797 Tys = DAG.getVTList(MVT::Other);
6799 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6801 MachineMemOperand *MMO =
6802 DAG.getMachineFunction()
6803 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6804 MachineMemOperand::MOStore, SSFISize, SSFISize);
6806 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6807 Ops, array_lengthof(Ops),
6808 Op.getValueType(), MMO);
6809 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6810 MachinePointerInfo::getFixedStack(SSFI),
6817 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6818 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6819 SelectionDAG &DAG) const {
6820 // This algorithm is not obvious. Here it is in C code, more or less:
6822 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6823 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6824 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6826 // Copy ints to xmm registers.
6827 __m128i xh = _mm_cvtsi32_si128( hi );
6828 __m128i xl = _mm_cvtsi32_si128( lo );
6830 // Combine into low half of a single xmm register.
6831 __m128i x = _mm_unpacklo_epi32( xh, xl );
6835 // Merge in appropriate exponents to give the integer bits the right
6837 x = _mm_unpacklo_epi32( x, exp );
6839 // Subtract away the biases to deal with the IEEE-754 double precision
6841 d = _mm_sub_pd( (__m128d) x, bias );
6843 // All conversions up to here are exact. The correctly rounded result is
6844 // calculated using the current rounding mode using the following
6846 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6847 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6848 // store doesn't really need to be here (except
6849 // maybe to zero the other double)
6854 DebugLoc dl = Op.getDebugLoc();
6855 LLVMContext *Context = DAG.getContext();
6857 // Build some magic constants.
6858 std::vector<Constant*> CV0;
6859 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6860 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6861 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6862 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6863 Constant *C0 = ConstantVector::get(CV0);
6864 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6866 std::vector<Constant*> CV1;
6868 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6870 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6871 Constant *C1 = ConstantVector::get(CV1);
6872 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6874 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6875 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6877 DAG.getIntPtrConstant(1)));
6878 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6879 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6881 DAG.getIntPtrConstant(0)));
6882 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6883 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6884 MachinePointerInfo::getConstantPool(),
6886 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6887 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6888 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6889 MachinePointerInfo::getConstantPool(),
6891 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6893 // Add the halves; easiest way is to swap them into another reg first.
6894 int ShufMask[2] = { 1, -1 };
6895 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6896 DAG.getUNDEF(MVT::v2f64), ShufMask);
6897 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6898 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6899 DAG.getIntPtrConstant(0));
6902 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6903 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6904 SelectionDAG &DAG) const {
6905 DebugLoc dl = Op.getDebugLoc();
6906 // FP constant to bias correct the final result.
6907 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6910 // Load the 32-bit value into an XMM register.
6911 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6912 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6914 DAG.getIntPtrConstant(0)));
6916 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6917 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6918 DAG.getIntPtrConstant(0));
6920 // Or the load with the bias.
6921 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6922 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6923 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6925 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6926 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6927 MVT::v2f64, Bias)));
6928 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6929 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6930 DAG.getIntPtrConstant(0));
6932 // Subtract the bias.
6933 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6935 // Handle final rounding.
6936 EVT DestVT = Op.getValueType();
6938 if (DestVT.bitsLT(MVT::f64)) {
6939 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6940 DAG.getIntPtrConstant(0));
6941 } else if (DestVT.bitsGT(MVT::f64)) {
6942 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6945 // Handle final rounding.
6949 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6950 SelectionDAG &DAG) const {
6951 SDValue N0 = Op.getOperand(0);
6952 DebugLoc dl = Op.getDebugLoc();
6954 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6955 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6956 // the optimization here.
6957 if (DAG.SignBitIsZero(N0))
6958 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6960 EVT SrcVT = N0.getValueType();
6961 EVT DstVT = Op.getValueType();
6962 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6963 return LowerUINT_TO_FP_i64(Op, DAG);
6964 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6965 return LowerUINT_TO_FP_i32(Op, DAG);
6967 // Make a 64-bit buffer, and use it to build an FILD.
6968 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6969 if (SrcVT == MVT::i32) {
6970 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6971 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6972 getPointerTy(), StackSlot, WordOff);
6973 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6974 StackSlot, MachinePointerInfo(),
6976 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6977 OffsetSlot, MachinePointerInfo(),
6979 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6983 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6984 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6985 StackSlot, MachinePointerInfo(),
6987 // For i64 source, we need to add the appropriate power of 2 if the input
6988 // was negative. This is the same as the optimization in
6989 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6990 // we must be careful to do the computation in x87 extended precision, not
6991 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6992 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6993 MachineMemOperand *MMO =
6994 DAG.getMachineFunction()
6995 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6996 MachineMemOperand::MOLoad, 8, 8);
6998 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6999 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7000 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7003 APInt FF(32, 0x5F800000ULL);
7005 // Check whether the sign bit is set.
7006 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7007 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7010 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7011 SDValue FudgePtr = DAG.getConstantPool(
7012 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7015 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7016 SDValue Zero = DAG.getIntPtrConstant(0);
7017 SDValue Four = DAG.getIntPtrConstant(4);
7018 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7020 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7022 // Load the value out, extending it from f32 to f80.
7023 // FIXME: Avoid the extend by constructing the right constant pool?
7024 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7025 FudgePtr, MachinePointerInfo::getConstantPool(),
7026 MVT::f32, false, false, 4);
7027 // Extend everything to 80 bits to force it to be done on x87.
7028 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7029 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7032 std::pair<SDValue,SDValue> X86TargetLowering::
7033 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7034 DebugLoc DL = Op.getDebugLoc();
7036 EVT DstTy = Op.getValueType();
7039 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7043 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7044 DstTy.getSimpleVT() >= MVT::i16 &&
7045 "Unknown FP_TO_SINT to lower!");
7047 // These are really Legal.
7048 if (DstTy == MVT::i32 &&
7049 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7050 return std::make_pair(SDValue(), SDValue());
7051 if (Subtarget->is64Bit() &&
7052 DstTy == MVT::i64 &&
7053 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7054 return std::make_pair(SDValue(), SDValue());
7056 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7058 MachineFunction &MF = DAG.getMachineFunction();
7059 unsigned MemSize = DstTy.getSizeInBits()/8;
7060 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7061 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7066 switch (DstTy.getSimpleVT().SimpleTy) {
7067 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7068 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7069 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7070 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7073 SDValue Chain = DAG.getEntryNode();
7074 SDValue Value = Op.getOperand(0);
7075 EVT TheVT = Op.getOperand(0).getValueType();
7076 if (isScalarFPTypeInSSEReg(TheVT)) {
7077 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7078 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7079 MachinePointerInfo::getFixedStack(SSFI),
7081 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7083 Chain, StackSlot, DAG.getValueType(TheVT)
7086 MachineMemOperand *MMO =
7087 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7088 MachineMemOperand::MOLoad, MemSize, MemSize);
7089 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7091 Chain = Value.getValue(1);
7092 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7093 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7096 MachineMemOperand *MMO =
7097 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7098 MachineMemOperand::MOStore, MemSize, MemSize);
7100 // Build the FP_TO_INT*_IN_MEM
7101 SDValue Ops[] = { Chain, Value, StackSlot };
7102 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7103 Ops, 3, DstTy, MMO);
7105 return std::make_pair(FIST, StackSlot);
7108 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7109 SelectionDAG &DAG) const {
7110 if (Op.getValueType().isVector())
7113 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7114 SDValue FIST = Vals.first, StackSlot = Vals.second;
7115 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7116 if (FIST.getNode() == 0) return Op;
7119 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7120 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7123 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7124 SelectionDAG &DAG) const {
7125 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7126 SDValue FIST = Vals.first, StackSlot = Vals.second;
7127 assert(FIST.getNode() && "Unexpected failure");
7130 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7131 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7134 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7135 SelectionDAG &DAG) const {
7136 LLVMContext *Context = DAG.getContext();
7137 DebugLoc dl = Op.getDebugLoc();
7138 EVT VT = Op.getValueType();
7141 EltVT = VT.getVectorElementType();
7142 std::vector<Constant*> CV;
7143 if (EltVT == MVT::f64) {
7144 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7148 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7154 Constant *C = ConstantVector::get(CV);
7155 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7156 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7157 MachinePointerInfo::getConstantPool(),
7159 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7162 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7163 LLVMContext *Context = DAG.getContext();
7164 DebugLoc dl = Op.getDebugLoc();
7165 EVT VT = Op.getValueType();
7168 EltVT = VT.getVectorElementType();
7169 std::vector<Constant*> CV;
7170 if (EltVT == MVT::f64) {
7171 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7175 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7181 Constant *C = ConstantVector::get(CV);
7182 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7183 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7184 MachinePointerInfo::getConstantPool(),
7186 if (VT.isVector()) {
7187 return DAG.getNode(ISD::BITCAST, dl, VT,
7188 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7189 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7191 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7193 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7197 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7198 LLVMContext *Context = DAG.getContext();
7199 SDValue Op0 = Op.getOperand(0);
7200 SDValue Op1 = Op.getOperand(1);
7201 DebugLoc dl = Op.getDebugLoc();
7202 EVT VT = Op.getValueType();
7203 EVT SrcVT = Op1.getValueType();
7205 // If second operand is smaller, extend it first.
7206 if (SrcVT.bitsLT(VT)) {
7207 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7210 // And if it is bigger, shrink it first.
7211 if (SrcVT.bitsGT(VT)) {
7212 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7216 // At this point the operands and the result should have the same
7217 // type, and that won't be f80 since that is not custom lowered.
7219 // First get the sign bit of second operand.
7220 std::vector<Constant*> CV;
7221 if (SrcVT == MVT::f64) {
7222 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7223 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7225 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7226 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7227 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7228 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7230 Constant *C = ConstantVector::get(CV);
7231 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7232 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7233 MachinePointerInfo::getConstantPool(),
7235 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7237 // Shift sign bit right or left if the two operands have different types.
7238 if (SrcVT.bitsGT(VT)) {
7239 // Op0 is MVT::f32, Op1 is MVT::f64.
7240 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7241 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7242 DAG.getConstant(32, MVT::i32));
7243 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7244 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7245 DAG.getIntPtrConstant(0));
7248 // Clear first operand sign bit.
7250 if (VT == MVT::f64) {
7251 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7252 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7254 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7255 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7256 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7257 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7259 C = ConstantVector::get(CV);
7260 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7261 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7262 MachinePointerInfo::getConstantPool(),
7264 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7266 // Or the value with the sign bit.
7267 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7270 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7271 SDValue N0 = Op.getOperand(0);
7272 DebugLoc dl = Op.getDebugLoc();
7273 EVT VT = Op.getValueType();
7275 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7276 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7277 DAG.getConstant(1, VT));
7278 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7281 /// Emit nodes that will be selected as "test Op0,Op0", or something
7283 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7284 SelectionDAG &DAG) const {
7285 DebugLoc dl = Op.getDebugLoc();
7287 // CF and OF aren't always set the way we want. Determine which
7288 // of these we need.
7289 bool NeedCF = false;
7290 bool NeedOF = false;
7293 case X86::COND_A: case X86::COND_AE:
7294 case X86::COND_B: case X86::COND_BE:
7297 case X86::COND_G: case X86::COND_GE:
7298 case X86::COND_L: case X86::COND_LE:
7299 case X86::COND_O: case X86::COND_NO:
7304 // See if we can use the EFLAGS value from the operand instead of
7305 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7306 // we prove that the arithmetic won't overflow, we can't use OF or CF.
7307 if (Op.getResNo() != 0 || NeedOF || NeedCF)
7308 // Emit a CMP with 0, which is the TEST pattern.
7309 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7310 DAG.getConstant(0, Op.getValueType()));
7312 unsigned Opcode = 0;
7313 unsigned NumOperands = 0;
7314 switch (Op.getNode()->getOpcode()) {
7316 // Due to an isel shortcoming, be conservative if this add is likely to be
7317 // selected as part of a load-modify-store instruction. When the root node
7318 // in a match is a store, isel doesn't know how to remap non-chain non-flag
7319 // uses of other nodes in the match, such as the ADD in this case. This
7320 // leads to the ADD being left around and reselected, with the result being
7321 // two adds in the output. Alas, even if none our users are stores, that
7322 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
7323 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
7324 // climbing the DAG back to the root, and it doesn't seem to be worth the
7326 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7327 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7328 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7331 if (ConstantSDNode *C =
7332 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7333 // An add of one will be selected as an INC.
7334 if (C->getAPIntValue() == 1) {
7335 Opcode = X86ISD::INC;
7340 // An add of negative one (subtract of one) will be selected as a DEC.
7341 if (C->getAPIntValue().isAllOnesValue()) {
7342 Opcode = X86ISD::DEC;
7348 // Otherwise use a regular EFLAGS-setting add.
7349 Opcode = X86ISD::ADD;
7353 // If the primary and result isn't used, don't bother using X86ISD::AND,
7354 // because a TEST instruction will be better.
7355 bool NonFlagUse = false;
7356 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7357 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7359 unsigned UOpNo = UI.getOperandNo();
7360 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7361 // Look pass truncate.
7362 UOpNo = User->use_begin().getOperandNo();
7363 User = *User->use_begin();
7366 if (User->getOpcode() != ISD::BRCOND &&
7367 User->getOpcode() != ISD::SETCC &&
7368 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7381 // Due to the ISEL shortcoming noted above, be conservative if this op is
7382 // likely to be selected as part of a load-modify-store instruction.
7383 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7384 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7385 if (UI->getOpcode() == ISD::STORE)
7388 // Otherwise use a regular EFLAGS-setting instruction.
7389 switch (Op.getNode()->getOpcode()) {
7390 default: llvm_unreachable("unexpected operator!");
7391 case ISD::SUB: Opcode = X86ISD::SUB; break;
7392 case ISD::OR: Opcode = X86ISD::OR; break;
7393 case ISD::XOR: Opcode = X86ISD::XOR; break;
7394 case ISD::AND: Opcode = X86ISD::AND; break;
7406 return SDValue(Op.getNode(), 1);
7413 // Emit a CMP with 0, which is the TEST pattern.
7414 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7415 DAG.getConstant(0, Op.getValueType()));
7417 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7418 SmallVector<SDValue, 4> Ops;
7419 for (unsigned i = 0; i != NumOperands; ++i)
7420 Ops.push_back(Op.getOperand(i));
7422 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7423 DAG.ReplaceAllUsesWith(Op, New);
7424 return SDValue(New.getNode(), 1);
7427 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7429 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7430 SelectionDAG &DAG) const {
7431 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7432 if (C->getAPIntValue() == 0)
7433 return EmitTest(Op0, X86CC, DAG);
7435 DebugLoc dl = Op0.getDebugLoc();
7436 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7439 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7440 /// if it's possible.
7441 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7442 DebugLoc dl, SelectionDAG &DAG) const {
7443 SDValue Op0 = And.getOperand(0);
7444 SDValue Op1 = And.getOperand(1);
7445 if (Op0.getOpcode() == ISD::TRUNCATE)
7446 Op0 = Op0.getOperand(0);
7447 if (Op1.getOpcode() == ISD::TRUNCATE)
7448 Op1 = Op1.getOperand(0);
7451 if (Op1.getOpcode() == ISD::SHL)
7452 std::swap(Op0, Op1);
7453 if (Op0.getOpcode() == ISD::SHL) {
7454 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7455 if (And00C->getZExtValue() == 1) {
7456 // If we looked past a truncate, check that it's only truncating away
7458 unsigned BitWidth = Op0.getValueSizeInBits();
7459 unsigned AndBitWidth = And.getValueSizeInBits();
7460 if (BitWidth > AndBitWidth) {
7461 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7462 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7463 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7467 RHS = Op0.getOperand(1);
7469 } else if (Op1.getOpcode() == ISD::Constant) {
7470 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7471 SDValue AndLHS = Op0;
7472 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7473 LHS = AndLHS.getOperand(0);
7474 RHS = AndLHS.getOperand(1);
7478 if (LHS.getNode()) {
7479 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
7480 // instruction. Since the shift amount is in-range-or-undefined, we know
7481 // that doing a bittest on the i32 value is ok. We extend to i32 because
7482 // the encoding for the i16 version is larger than the i32 version.
7483 // Also promote i16 to i32 for performance / code size reason.
7484 if (LHS.getValueType() == MVT::i8 ||
7485 LHS.getValueType() == MVT::i16)
7486 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7488 // If the operand types disagree, extend the shift amount to match. Since
7489 // BT ignores high bits (like shifts) we can use anyextend.
7490 if (LHS.getValueType() != RHS.getValueType())
7491 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7493 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7494 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7495 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7496 DAG.getConstant(Cond, MVT::i8), BT);
7502 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7503 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7504 SDValue Op0 = Op.getOperand(0);
7505 SDValue Op1 = Op.getOperand(1);
7506 DebugLoc dl = Op.getDebugLoc();
7507 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7509 // Optimize to BT if possible.
7510 // Lower (X & (1 << N)) == 0 to BT(X, N).
7511 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7512 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7513 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7514 Op1.getOpcode() == ISD::Constant &&
7515 cast<ConstantSDNode>(Op1)->isNullValue() &&
7516 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7517 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7518 if (NewSetCC.getNode())
7522 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
7524 if (Op1.getOpcode() == ISD::Constant &&
7525 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7526 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7527 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7529 // If the input is a setcc, then reuse the input setcc or use a new one with
7530 // the inverted condition.
7531 if (Op0.getOpcode() == X86ISD::SETCC) {
7532 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7533 bool Invert = (CC == ISD::SETNE) ^
7534 cast<ConstantSDNode>(Op1)->isNullValue();
7535 if (!Invert) return Op0;
7537 CCode = X86::GetOppositeBranchCondition(CCode);
7538 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7539 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7543 bool isFP = Op1.getValueType().isFloatingPoint();
7544 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7545 if (X86CC == X86::COND_INVALID)
7548 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7549 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7550 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7553 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7555 SDValue Op0 = Op.getOperand(0);
7556 SDValue Op1 = Op.getOperand(1);
7557 SDValue CC = Op.getOperand(2);
7558 EVT VT = Op.getValueType();
7559 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7560 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7561 DebugLoc dl = Op.getDebugLoc();
7565 EVT VT0 = Op0.getValueType();
7566 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7567 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7570 switch (SetCCOpcode) {
7573 case ISD::SETEQ: SSECC = 0; break;
7575 case ISD::SETGT: Swap = true; // Fallthrough
7577 case ISD::SETOLT: SSECC = 1; break;
7579 case ISD::SETGE: Swap = true; // Fallthrough
7581 case ISD::SETOLE: SSECC = 2; break;
7582 case ISD::SETUO: SSECC = 3; break;
7584 case ISD::SETNE: SSECC = 4; break;
7585 case ISD::SETULE: Swap = true;
7586 case ISD::SETUGE: SSECC = 5; break;
7587 case ISD::SETULT: Swap = true;
7588 case ISD::SETUGT: SSECC = 6; break;
7589 case ISD::SETO: SSECC = 7; break;
7592 std::swap(Op0, Op1);
7594 // In the two special cases we can't handle, emit two comparisons.
7596 if (SetCCOpcode == ISD::SETUEQ) {
7598 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7599 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7600 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7602 else if (SetCCOpcode == ISD::SETONE) {
7604 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7605 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7606 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7608 llvm_unreachable("Illegal FP comparison");
7610 // Handle all other FP comparisons here.
7611 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7614 // We are handling one of the integer comparisons here. Since SSE only has
7615 // GT and EQ comparisons for integer, swapping operands and multiple
7616 // operations may be required for some comparisons.
7617 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7618 bool Swap = false, Invert = false, FlipSigns = false;
7620 switch (VT.getSimpleVT().SimpleTy) {
7622 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7623 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7624 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7625 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7628 switch (SetCCOpcode) {
7630 case ISD::SETNE: Invert = true;
7631 case ISD::SETEQ: Opc = EQOpc; break;
7632 case ISD::SETLT: Swap = true;
7633 case ISD::SETGT: Opc = GTOpc; break;
7634 case ISD::SETGE: Swap = true;
7635 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7636 case ISD::SETULT: Swap = true;
7637 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7638 case ISD::SETUGE: Swap = true;
7639 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7642 std::swap(Op0, Op1);
7644 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7645 // bits of the inputs before performing those operations.
7647 EVT EltVT = VT.getVectorElementType();
7648 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7650 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7651 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7653 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7654 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7657 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7659 // If the logical-not of the result is required, perform that now.
7661 Result = DAG.getNOT(dl, Result, VT);
7666 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7667 static bool isX86LogicalCmp(SDValue Op) {
7668 unsigned Opc = Op.getNode()->getOpcode();
7669 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7671 if (Op.getResNo() == 1 &&
7672 (Opc == X86ISD::ADD ||
7673 Opc == X86ISD::SUB ||
7674 Opc == X86ISD::ADC ||
7675 Opc == X86ISD::SBB ||
7676 Opc == X86ISD::SMUL ||
7677 Opc == X86ISD::UMUL ||
7678 Opc == X86ISD::INC ||
7679 Opc == X86ISD::DEC ||
7680 Opc == X86ISD::OR ||
7681 Opc == X86ISD::XOR ||
7682 Opc == X86ISD::AND))
7685 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7691 static bool isZero(SDValue V) {
7692 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7693 return C && C->isNullValue();
7696 static bool isAllOnes(SDValue V) {
7697 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7698 return C && C->isAllOnesValue();
7701 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7702 bool addTest = true;
7703 SDValue Cond = Op.getOperand(0);
7704 SDValue Op1 = Op.getOperand(1);
7705 SDValue Op2 = Op.getOperand(2);
7706 DebugLoc DL = Op.getDebugLoc();
7709 if (Cond.getOpcode() == ISD::SETCC) {
7710 SDValue NewCond = LowerSETCC(Cond, DAG);
7711 if (NewCond.getNode())
7715 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7716 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7717 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7718 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7719 if (Cond.getOpcode() == X86ISD::SETCC &&
7720 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7721 isZero(Cond.getOperand(1).getOperand(1))) {
7722 SDValue Cmp = Cond.getOperand(1);
7724 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7726 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7727 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7728 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7730 SDValue CmpOp0 = Cmp.getOperand(0);
7731 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7732 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7734 SDValue Res = // Res = 0 or -1.
7735 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7736 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7738 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7739 Res = DAG.getNOT(DL, Res, Res.getValueType());
7741 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7742 if (N2C == 0 || !N2C->isNullValue())
7743 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7748 // Look past (and (setcc_carry (cmp ...)), 1).
7749 if (Cond.getOpcode() == ISD::AND &&
7750 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7751 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7752 if (C && C->getAPIntValue() == 1)
7753 Cond = Cond.getOperand(0);
7756 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7757 // setting operand in place of the X86ISD::SETCC.
7758 if (Cond.getOpcode() == X86ISD::SETCC ||
7759 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7760 CC = Cond.getOperand(0);
7762 SDValue Cmp = Cond.getOperand(1);
7763 unsigned Opc = Cmp.getOpcode();
7764 EVT VT = Op.getValueType();
7766 bool IllegalFPCMov = false;
7767 if (VT.isFloatingPoint() && !VT.isVector() &&
7768 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7769 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7771 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7772 Opc == X86ISD::BT) { // FIXME
7779 // Look pass the truncate.
7780 if (Cond.getOpcode() == ISD::TRUNCATE)
7781 Cond = Cond.getOperand(0);
7783 // We know the result of AND is compared against zero. Try to match
7785 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7786 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7787 if (NewSetCC.getNode()) {
7788 CC = NewSetCC.getOperand(0);
7789 Cond = NewSetCC.getOperand(1);
7796 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7797 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7800 // a < b ? -1 : 0 -> RES = ~setcc_carry
7801 // a < b ? 0 : -1 -> RES = setcc_carry
7802 // a >= b ? -1 : 0 -> RES = setcc_carry
7803 // a >= b ? 0 : -1 -> RES = ~setcc_carry
7804 if (Cond.getOpcode() == X86ISD::CMP) {
7805 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7807 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7808 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7809 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7810 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7811 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7812 return DAG.getNOT(DL, Res, Res.getValueType());
7817 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7818 // condition is true.
7819 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7820 SDValue Ops[] = { Op2, Op1, CC, Cond };
7821 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7824 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7825 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7826 // from the AND / OR.
7827 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7828 Opc = Op.getOpcode();
7829 if (Opc != ISD::OR && Opc != ISD::AND)
7831 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7832 Op.getOperand(0).hasOneUse() &&
7833 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7834 Op.getOperand(1).hasOneUse());
7837 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7838 // 1 and that the SETCC node has a single use.
7839 static bool isXor1OfSetCC(SDValue Op) {
7840 if (Op.getOpcode() != ISD::XOR)
7842 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7843 if (N1C && N1C->getAPIntValue() == 1) {
7844 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7845 Op.getOperand(0).hasOneUse();
7850 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7851 bool addTest = true;
7852 SDValue Chain = Op.getOperand(0);
7853 SDValue Cond = Op.getOperand(1);
7854 SDValue Dest = Op.getOperand(2);
7855 DebugLoc dl = Op.getDebugLoc();
7858 if (Cond.getOpcode() == ISD::SETCC) {
7859 SDValue NewCond = LowerSETCC(Cond, DAG);
7860 if (NewCond.getNode())
7864 // FIXME: LowerXALUO doesn't handle these!!
7865 else if (Cond.getOpcode() == X86ISD::ADD ||
7866 Cond.getOpcode() == X86ISD::SUB ||
7867 Cond.getOpcode() == X86ISD::SMUL ||
7868 Cond.getOpcode() == X86ISD::UMUL)
7869 Cond = LowerXALUO(Cond, DAG);
7872 // Look pass (and (setcc_carry (cmp ...)), 1).
7873 if (Cond.getOpcode() == ISD::AND &&
7874 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7875 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7876 if (C && C->getAPIntValue() == 1)
7877 Cond = Cond.getOperand(0);
7880 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7881 // setting operand in place of the X86ISD::SETCC.
7882 if (Cond.getOpcode() == X86ISD::SETCC ||
7883 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7884 CC = Cond.getOperand(0);
7886 SDValue Cmp = Cond.getOperand(1);
7887 unsigned Opc = Cmp.getOpcode();
7888 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7889 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7893 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7897 // These can only come from an arithmetic instruction with overflow,
7898 // e.g. SADDO, UADDO.
7899 Cond = Cond.getNode()->getOperand(1);
7906 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7907 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7908 if (CondOpc == ISD::OR) {
7909 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7910 // two branches instead of an explicit OR instruction with a
7912 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7913 isX86LogicalCmp(Cmp)) {
7914 CC = Cond.getOperand(0).getOperand(0);
7915 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7916 Chain, Dest, CC, Cmp);
7917 CC = Cond.getOperand(1).getOperand(0);
7921 } else { // ISD::AND
7922 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7923 // two branches instead of an explicit AND instruction with a
7924 // separate test. However, we only do this if this block doesn't
7925 // have a fall-through edge, because this requires an explicit
7926 // jmp when the condition is false.
7927 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7928 isX86LogicalCmp(Cmp) &&
7929 Op.getNode()->hasOneUse()) {
7930 X86::CondCode CCode =
7931 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7932 CCode = X86::GetOppositeBranchCondition(CCode);
7933 CC = DAG.getConstant(CCode, MVT::i8);
7934 SDNode *User = *Op.getNode()->use_begin();
7935 // Look for an unconditional branch following this conditional branch.
7936 // We need this because we need to reverse the successors in order
7937 // to implement FCMP_OEQ.
7938 if (User->getOpcode() == ISD::BR) {
7939 SDValue FalseBB = User->getOperand(1);
7941 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7942 assert(NewBR == User);
7946 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7947 Chain, Dest, CC, Cmp);
7948 X86::CondCode CCode =
7949 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7950 CCode = X86::GetOppositeBranchCondition(CCode);
7951 CC = DAG.getConstant(CCode, MVT::i8);
7957 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7958 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7959 // It should be transformed during dag combiner except when the condition
7960 // is set by a arithmetics with overflow node.
7961 X86::CondCode CCode =
7962 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7963 CCode = X86::GetOppositeBranchCondition(CCode);
7964 CC = DAG.getConstant(CCode, MVT::i8);
7965 Cond = Cond.getOperand(0).getOperand(1);
7971 // Look pass the truncate.
7972 if (Cond.getOpcode() == ISD::TRUNCATE)
7973 Cond = Cond.getOperand(0);
7975 // We know the result of AND is compared against zero. Try to match
7977 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7978 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7979 if (NewSetCC.getNode()) {
7980 CC = NewSetCC.getOperand(0);
7981 Cond = NewSetCC.getOperand(1);
7988 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7989 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7991 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7992 Chain, Dest, CC, Cond);
7996 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7997 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7998 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7999 // that the guard pages used by the OS virtual memory manager are allocated in
8000 // correct sequence.
8002 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8003 SelectionDAG &DAG) const {
8004 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8005 "This should be used only on Windows targets");
8006 assert(!Subtarget->isTargetEnvMacho());
8007 DebugLoc dl = Op.getDebugLoc();
8010 SDValue Chain = Op.getOperand(0);
8011 SDValue Size = Op.getOperand(1);
8012 // FIXME: Ensure alignment here
8016 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8017 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8019 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8020 Flag = Chain.getValue(1);
8022 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8024 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8025 Flag = Chain.getValue(1);
8027 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8029 SDValue Ops1[2] = { Chain.getValue(0), Chain };
8030 return DAG.getMergeValues(Ops1, 2, dl);
8033 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8034 MachineFunction &MF = DAG.getMachineFunction();
8035 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8037 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8038 DebugLoc DL = Op.getDebugLoc();
8040 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8041 // vastart just stores the address of the VarArgsFrameIndex slot into the
8042 // memory location argument.
8043 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8045 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8046 MachinePointerInfo(SV), false, false, 0);
8050 // gp_offset (0 - 6 * 8)
8051 // fp_offset (48 - 48 + 8 * 16)
8052 // overflow_arg_area (point to parameters coming in memory).
8054 SmallVector<SDValue, 8> MemOps;
8055 SDValue FIN = Op.getOperand(1);
8057 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8058 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8060 FIN, MachinePointerInfo(SV), false, false, 0);
8061 MemOps.push_back(Store);
8064 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8065 FIN, DAG.getIntPtrConstant(4));
8066 Store = DAG.getStore(Op.getOperand(0), DL,
8067 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8069 FIN, MachinePointerInfo(SV, 4), false, false, 0);
8070 MemOps.push_back(Store);
8072 // Store ptr to overflow_arg_area
8073 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8074 FIN, DAG.getIntPtrConstant(4));
8075 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8077 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8078 MachinePointerInfo(SV, 8),
8080 MemOps.push_back(Store);
8082 // Store ptr to reg_save_area.
8083 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8084 FIN, DAG.getIntPtrConstant(8));
8085 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8087 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8088 MachinePointerInfo(SV, 16), false, false, 0);
8089 MemOps.push_back(Store);
8090 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8091 &MemOps[0], MemOps.size());
8094 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8095 assert(Subtarget->is64Bit() &&
8096 "LowerVAARG only handles 64-bit va_arg!");
8097 assert((Subtarget->isTargetLinux() ||
8098 Subtarget->isTargetDarwin()) &&
8099 "Unhandled target in LowerVAARG");
8100 assert(Op.getNode()->getNumOperands() == 4);
8101 SDValue Chain = Op.getOperand(0);
8102 SDValue SrcPtr = Op.getOperand(1);
8103 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8104 unsigned Align = Op.getConstantOperandVal(3);
8105 DebugLoc dl = Op.getDebugLoc();
8107 EVT ArgVT = Op.getNode()->getValueType(0);
8108 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8109 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8112 // Decide which area this value should be read from.
8113 // TODO: Implement the AMD64 ABI in its entirety. This simple
8114 // selection mechanism works only for the basic types.
8115 if (ArgVT == MVT::f80) {
8116 llvm_unreachable("va_arg for f80 not yet implemented");
8117 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8118 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
8119 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8120 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
8122 llvm_unreachable("Unhandled argument type in LowerVAARG");
8126 // Sanity Check: Make sure using fp_offset makes sense.
8127 assert(!UseSoftFloat &&
8128 !(DAG.getMachineFunction()
8129 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8130 Subtarget->hasXMM());
8133 // Insert VAARG_64 node into the DAG
8134 // VAARG_64 returns two values: Variable Argument Address, Chain
8135 SmallVector<SDValue, 11> InstOps;
8136 InstOps.push_back(Chain);
8137 InstOps.push_back(SrcPtr);
8138 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8139 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8140 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8141 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8142 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8143 VTs, &InstOps[0], InstOps.size(),
8145 MachinePointerInfo(SV),
8150 Chain = VAARG.getValue(1);
8152 // Load the next argument and return it
8153 return DAG.getLoad(ArgVT, dl,
8156 MachinePointerInfo(),
8160 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8161 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8162 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8163 SDValue Chain = Op.getOperand(0);
8164 SDValue DstPtr = Op.getOperand(1);
8165 SDValue SrcPtr = Op.getOperand(2);
8166 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8167 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8168 DebugLoc DL = Op.getDebugLoc();
8170 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8171 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8173 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8177 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8178 DebugLoc dl = Op.getDebugLoc();
8179 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8181 default: return SDValue(); // Don't custom lower most intrinsics.
8182 // Comparison intrinsics.
8183 case Intrinsic::x86_sse_comieq_ss:
8184 case Intrinsic::x86_sse_comilt_ss:
8185 case Intrinsic::x86_sse_comile_ss:
8186 case Intrinsic::x86_sse_comigt_ss:
8187 case Intrinsic::x86_sse_comige_ss:
8188 case Intrinsic::x86_sse_comineq_ss:
8189 case Intrinsic::x86_sse_ucomieq_ss:
8190 case Intrinsic::x86_sse_ucomilt_ss:
8191 case Intrinsic::x86_sse_ucomile_ss:
8192 case Intrinsic::x86_sse_ucomigt_ss:
8193 case Intrinsic::x86_sse_ucomige_ss:
8194 case Intrinsic::x86_sse_ucomineq_ss:
8195 case Intrinsic::x86_sse2_comieq_sd:
8196 case Intrinsic::x86_sse2_comilt_sd:
8197 case Intrinsic::x86_sse2_comile_sd:
8198 case Intrinsic::x86_sse2_comigt_sd:
8199 case Intrinsic::x86_sse2_comige_sd:
8200 case Intrinsic::x86_sse2_comineq_sd:
8201 case Intrinsic::x86_sse2_ucomieq_sd:
8202 case Intrinsic::x86_sse2_ucomilt_sd:
8203 case Intrinsic::x86_sse2_ucomile_sd:
8204 case Intrinsic::x86_sse2_ucomigt_sd:
8205 case Intrinsic::x86_sse2_ucomige_sd:
8206 case Intrinsic::x86_sse2_ucomineq_sd: {
8208 ISD::CondCode CC = ISD::SETCC_INVALID;
8211 case Intrinsic::x86_sse_comieq_ss:
8212 case Intrinsic::x86_sse2_comieq_sd:
8216 case Intrinsic::x86_sse_comilt_ss:
8217 case Intrinsic::x86_sse2_comilt_sd:
8221 case Intrinsic::x86_sse_comile_ss:
8222 case Intrinsic::x86_sse2_comile_sd:
8226 case Intrinsic::x86_sse_comigt_ss:
8227 case Intrinsic::x86_sse2_comigt_sd:
8231 case Intrinsic::x86_sse_comige_ss:
8232 case Intrinsic::x86_sse2_comige_sd:
8236 case Intrinsic::x86_sse_comineq_ss:
8237 case Intrinsic::x86_sse2_comineq_sd:
8241 case Intrinsic::x86_sse_ucomieq_ss:
8242 case Intrinsic::x86_sse2_ucomieq_sd:
8243 Opc = X86ISD::UCOMI;
8246 case Intrinsic::x86_sse_ucomilt_ss:
8247 case Intrinsic::x86_sse2_ucomilt_sd:
8248 Opc = X86ISD::UCOMI;
8251 case Intrinsic::x86_sse_ucomile_ss:
8252 case Intrinsic::x86_sse2_ucomile_sd:
8253 Opc = X86ISD::UCOMI;
8256 case Intrinsic::x86_sse_ucomigt_ss:
8257 case Intrinsic::x86_sse2_ucomigt_sd:
8258 Opc = X86ISD::UCOMI;
8261 case Intrinsic::x86_sse_ucomige_ss:
8262 case Intrinsic::x86_sse2_ucomige_sd:
8263 Opc = X86ISD::UCOMI;
8266 case Intrinsic::x86_sse_ucomineq_ss:
8267 case Intrinsic::x86_sse2_ucomineq_sd:
8268 Opc = X86ISD::UCOMI;
8273 SDValue LHS = Op.getOperand(1);
8274 SDValue RHS = Op.getOperand(2);
8275 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8276 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8277 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8278 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8279 DAG.getConstant(X86CC, MVT::i8), Cond);
8280 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8282 // ptest and testp intrinsics. The intrinsic these come from are designed to
8283 // return an integer value, not just an instruction so lower it to the ptest
8284 // or testp pattern and a setcc for the result.
8285 case Intrinsic::x86_sse41_ptestz:
8286 case Intrinsic::x86_sse41_ptestc:
8287 case Intrinsic::x86_sse41_ptestnzc:
8288 case Intrinsic::x86_avx_ptestz_256:
8289 case Intrinsic::x86_avx_ptestc_256:
8290 case Intrinsic::x86_avx_ptestnzc_256:
8291 case Intrinsic::x86_avx_vtestz_ps:
8292 case Intrinsic::x86_avx_vtestc_ps:
8293 case Intrinsic::x86_avx_vtestnzc_ps:
8294 case Intrinsic::x86_avx_vtestz_pd:
8295 case Intrinsic::x86_avx_vtestc_pd:
8296 case Intrinsic::x86_avx_vtestnzc_pd:
8297 case Intrinsic::x86_avx_vtestz_ps_256:
8298 case Intrinsic::x86_avx_vtestc_ps_256:
8299 case Intrinsic::x86_avx_vtestnzc_ps_256:
8300 case Intrinsic::x86_avx_vtestz_pd_256:
8301 case Intrinsic::x86_avx_vtestc_pd_256:
8302 case Intrinsic::x86_avx_vtestnzc_pd_256: {
8303 bool IsTestPacked = false;
8306 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8307 case Intrinsic::x86_avx_vtestz_ps:
8308 case Intrinsic::x86_avx_vtestz_pd:
8309 case Intrinsic::x86_avx_vtestz_ps_256:
8310 case Intrinsic::x86_avx_vtestz_pd_256:
8311 IsTestPacked = true; // Fallthrough
8312 case Intrinsic::x86_sse41_ptestz:
8313 case Intrinsic::x86_avx_ptestz_256:
8315 X86CC = X86::COND_E;
8317 case Intrinsic::x86_avx_vtestc_ps:
8318 case Intrinsic::x86_avx_vtestc_pd:
8319 case Intrinsic::x86_avx_vtestc_ps_256:
8320 case Intrinsic::x86_avx_vtestc_pd_256:
8321 IsTestPacked = true; // Fallthrough
8322 case Intrinsic::x86_sse41_ptestc:
8323 case Intrinsic::x86_avx_ptestc_256:
8325 X86CC = X86::COND_B;
8327 case Intrinsic::x86_avx_vtestnzc_ps:
8328 case Intrinsic::x86_avx_vtestnzc_pd:
8329 case Intrinsic::x86_avx_vtestnzc_ps_256:
8330 case Intrinsic::x86_avx_vtestnzc_pd_256:
8331 IsTestPacked = true; // Fallthrough
8332 case Intrinsic::x86_sse41_ptestnzc:
8333 case Intrinsic::x86_avx_ptestnzc_256:
8335 X86CC = X86::COND_A;
8339 SDValue LHS = Op.getOperand(1);
8340 SDValue RHS = Op.getOperand(2);
8341 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8342 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8343 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8344 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8345 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8348 // Fix vector shift instructions where the last operand is a non-immediate
8350 case Intrinsic::x86_sse2_pslli_w:
8351 case Intrinsic::x86_sse2_pslli_d:
8352 case Intrinsic::x86_sse2_pslli_q:
8353 case Intrinsic::x86_sse2_psrli_w:
8354 case Intrinsic::x86_sse2_psrli_d:
8355 case Intrinsic::x86_sse2_psrli_q:
8356 case Intrinsic::x86_sse2_psrai_w:
8357 case Intrinsic::x86_sse2_psrai_d:
8358 case Intrinsic::x86_mmx_pslli_w:
8359 case Intrinsic::x86_mmx_pslli_d:
8360 case Intrinsic::x86_mmx_pslli_q:
8361 case Intrinsic::x86_mmx_psrli_w:
8362 case Intrinsic::x86_mmx_psrli_d:
8363 case Intrinsic::x86_mmx_psrli_q:
8364 case Intrinsic::x86_mmx_psrai_w:
8365 case Intrinsic::x86_mmx_psrai_d: {
8366 SDValue ShAmt = Op.getOperand(2);
8367 if (isa<ConstantSDNode>(ShAmt))
8370 unsigned NewIntNo = 0;
8371 EVT ShAmtVT = MVT::v4i32;
8373 case Intrinsic::x86_sse2_pslli_w:
8374 NewIntNo = Intrinsic::x86_sse2_psll_w;
8376 case Intrinsic::x86_sse2_pslli_d:
8377 NewIntNo = Intrinsic::x86_sse2_psll_d;
8379 case Intrinsic::x86_sse2_pslli_q:
8380 NewIntNo = Intrinsic::x86_sse2_psll_q;
8382 case Intrinsic::x86_sse2_psrli_w:
8383 NewIntNo = Intrinsic::x86_sse2_psrl_w;
8385 case Intrinsic::x86_sse2_psrli_d:
8386 NewIntNo = Intrinsic::x86_sse2_psrl_d;
8388 case Intrinsic::x86_sse2_psrli_q:
8389 NewIntNo = Intrinsic::x86_sse2_psrl_q;
8391 case Intrinsic::x86_sse2_psrai_w:
8392 NewIntNo = Intrinsic::x86_sse2_psra_w;
8394 case Intrinsic::x86_sse2_psrai_d:
8395 NewIntNo = Intrinsic::x86_sse2_psra_d;
8398 ShAmtVT = MVT::v2i32;
8400 case Intrinsic::x86_mmx_pslli_w:
8401 NewIntNo = Intrinsic::x86_mmx_psll_w;
8403 case Intrinsic::x86_mmx_pslli_d:
8404 NewIntNo = Intrinsic::x86_mmx_psll_d;
8406 case Intrinsic::x86_mmx_pslli_q:
8407 NewIntNo = Intrinsic::x86_mmx_psll_q;
8409 case Intrinsic::x86_mmx_psrli_w:
8410 NewIntNo = Intrinsic::x86_mmx_psrl_w;
8412 case Intrinsic::x86_mmx_psrli_d:
8413 NewIntNo = Intrinsic::x86_mmx_psrl_d;
8415 case Intrinsic::x86_mmx_psrli_q:
8416 NewIntNo = Intrinsic::x86_mmx_psrl_q;
8418 case Intrinsic::x86_mmx_psrai_w:
8419 NewIntNo = Intrinsic::x86_mmx_psra_w;
8421 case Intrinsic::x86_mmx_psrai_d:
8422 NewIntNo = Intrinsic::x86_mmx_psra_d;
8424 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8430 // The vector shift intrinsics with scalars uses 32b shift amounts but
8431 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8435 ShOps[1] = DAG.getConstant(0, MVT::i32);
8436 if (ShAmtVT == MVT::v4i32) {
8437 ShOps[2] = DAG.getUNDEF(MVT::i32);
8438 ShOps[3] = DAG.getUNDEF(MVT::i32);
8439 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8441 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8442 // FIXME this must be lowered to get rid of the invalid type.
8445 EVT VT = Op.getValueType();
8446 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8447 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8448 DAG.getConstant(NewIntNo, MVT::i32),
8449 Op.getOperand(1), ShAmt);
8454 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8455 SelectionDAG &DAG) const {
8456 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8457 MFI->setReturnAddressIsTaken(true);
8459 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8460 DebugLoc dl = Op.getDebugLoc();
8463 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8465 DAG.getConstant(TD->getPointerSize(),
8466 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8467 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8468 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8470 MachinePointerInfo(), false, false, 0);
8473 // Just load the return address.
8474 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8475 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8476 RetAddrFI, MachinePointerInfo(), false, false, 0);
8479 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8480 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8481 MFI->setFrameAddressIsTaken(true);
8483 EVT VT = Op.getValueType();
8484 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
8485 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8486 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8487 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8489 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8490 MachinePointerInfo(),
8495 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8496 SelectionDAG &DAG) const {
8497 return DAG.getIntPtrConstant(2*TD->getPointerSize());
8500 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8501 MachineFunction &MF = DAG.getMachineFunction();
8502 SDValue Chain = Op.getOperand(0);
8503 SDValue Offset = Op.getOperand(1);
8504 SDValue Handler = Op.getOperand(2);
8505 DebugLoc dl = Op.getDebugLoc();
8507 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8508 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8510 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8512 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8513 DAG.getIntPtrConstant(TD->getPointerSize()));
8514 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8515 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8517 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8518 MF.getRegInfo().addLiveOut(StoreAddrReg);
8520 return DAG.getNode(X86ISD::EH_RETURN, dl,
8522 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8525 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8526 SelectionDAG &DAG) const {
8527 SDValue Root = Op.getOperand(0);
8528 SDValue Trmp = Op.getOperand(1); // trampoline
8529 SDValue FPtr = Op.getOperand(2); // nested function
8530 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8531 DebugLoc dl = Op.getDebugLoc();
8533 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8535 if (Subtarget->is64Bit()) {
8536 SDValue OutChains[6];
8538 // Large code-model.
8539 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8540 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8542 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
8543 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
8545 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8547 // Load the pointer to the nested function into R11.
8548 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8549 SDValue Addr = Trmp;
8550 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8551 Addr, MachinePointerInfo(TrmpAddr),
8554 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8555 DAG.getConstant(2, MVT::i64));
8556 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8557 MachinePointerInfo(TrmpAddr, 2),
8560 // Load the 'nest' parameter value into R10.
8561 // R10 is specified in X86CallingConv.td
8562 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8563 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8564 DAG.getConstant(10, MVT::i64));
8565 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8566 Addr, MachinePointerInfo(TrmpAddr, 10),
8569 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8570 DAG.getConstant(12, MVT::i64));
8571 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8572 MachinePointerInfo(TrmpAddr, 12),
8575 // Jump to the nested function.
8576 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8577 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8578 DAG.getConstant(20, MVT::i64));
8579 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8580 Addr, MachinePointerInfo(TrmpAddr, 20),
8583 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8584 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8585 DAG.getConstant(22, MVT::i64));
8586 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8587 MachinePointerInfo(TrmpAddr, 22),
8591 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8592 return DAG.getMergeValues(Ops, 2, dl);
8594 const Function *Func =
8595 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8596 CallingConv::ID CC = Func->getCallingConv();
8601 llvm_unreachable("Unsupported calling convention");
8602 case CallingConv::C:
8603 case CallingConv::X86_StdCall: {
8604 // Pass 'nest' parameter in ECX.
8605 // Must be kept in sync with X86CallingConv.td
8608 // Check that ECX wasn't needed by an 'inreg' parameter.
8609 FunctionType *FTy = Func->getFunctionType();
8610 const AttrListPtr &Attrs = Func->getAttributes();
8612 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8613 unsigned InRegCount = 0;
8616 for (FunctionType::param_iterator I = FTy->param_begin(),
8617 E = FTy->param_end(); I != E; ++I, ++Idx)
8618 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8619 // FIXME: should only count parameters that are lowered to integers.
8620 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8622 if (InRegCount > 2) {
8623 report_fatal_error("Nest register in use - reduce number of inreg"
8629 case CallingConv::X86_FastCall:
8630 case CallingConv::X86_ThisCall:
8631 case CallingConv::Fast:
8632 // Pass 'nest' parameter in EAX.
8633 // Must be kept in sync with X86CallingConv.td
8638 SDValue OutChains[4];
8641 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8642 DAG.getConstant(10, MVT::i32));
8643 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8645 // This is storing the opcode for MOV32ri.
8646 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8647 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
8648 OutChains[0] = DAG.getStore(Root, dl,
8649 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8650 Trmp, MachinePointerInfo(TrmpAddr),
8653 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8654 DAG.getConstant(1, MVT::i32));
8655 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8656 MachinePointerInfo(TrmpAddr, 1),
8659 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8660 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8661 DAG.getConstant(5, MVT::i32));
8662 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8663 MachinePointerInfo(TrmpAddr, 5),
8666 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8667 DAG.getConstant(6, MVT::i32));
8668 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8669 MachinePointerInfo(TrmpAddr, 6),
8673 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8674 return DAG.getMergeValues(Ops, 2, dl);
8678 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8679 SelectionDAG &DAG) const {
8681 The rounding mode is in bits 11:10 of FPSR, and has the following
8688 FLT_ROUNDS, on the other hand, expects the following:
8695 To perform the conversion, we do:
8696 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8699 MachineFunction &MF = DAG.getMachineFunction();
8700 const TargetMachine &TM = MF.getTarget();
8701 const TargetFrameLowering &TFI = *TM.getFrameLowering();
8702 unsigned StackAlignment = TFI.getStackAlignment();
8703 EVT VT = Op.getValueType();
8704 DebugLoc DL = Op.getDebugLoc();
8706 // Save FP Control Word to stack slot
8707 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8708 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8711 MachineMemOperand *MMO =
8712 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8713 MachineMemOperand::MOStore, 2, 2);
8715 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8716 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8717 DAG.getVTList(MVT::Other),
8718 Ops, 2, MVT::i16, MMO);
8720 // Load FP Control Word from stack slot
8721 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8722 MachinePointerInfo(), false, false, 0);
8724 // Transform as necessary
8726 DAG.getNode(ISD::SRL, DL, MVT::i16,
8727 DAG.getNode(ISD::AND, DL, MVT::i16,
8728 CWD, DAG.getConstant(0x800, MVT::i16)),
8729 DAG.getConstant(11, MVT::i8));
8731 DAG.getNode(ISD::SRL, DL, MVT::i16,
8732 DAG.getNode(ISD::AND, DL, MVT::i16,
8733 CWD, DAG.getConstant(0x400, MVT::i16)),
8734 DAG.getConstant(9, MVT::i8));
8737 DAG.getNode(ISD::AND, DL, MVT::i16,
8738 DAG.getNode(ISD::ADD, DL, MVT::i16,
8739 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8740 DAG.getConstant(1, MVT::i16)),
8741 DAG.getConstant(3, MVT::i16));
8744 return DAG.getNode((VT.getSizeInBits() < 16 ?
8745 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8748 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8749 EVT VT = Op.getValueType();
8751 unsigned NumBits = VT.getSizeInBits();
8752 DebugLoc dl = Op.getDebugLoc();
8754 Op = Op.getOperand(0);
8755 if (VT == MVT::i8) {
8756 // Zero extend to i32 since there is not an i8 bsr.
8758 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8761 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8762 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8763 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8765 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8768 DAG.getConstant(NumBits+NumBits-1, OpVT),
8769 DAG.getConstant(X86::COND_E, MVT::i8),
8772 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8774 // Finally xor with NumBits-1.
8775 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8778 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8782 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8783 EVT VT = Op.getValueType();
8785 unsigned NumBits = VT.getSizeInBits();
8786 DebugLoc dl = Op.getDebugLoc();
8788 Op = Op.getOperand(0);
8789 if (VT == MVT::i8) {
8791 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8794 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8795 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8796 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8798 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8801 DAG.getConstant(NumBits, OpVT),
8802 DAG.getConstant(X86::COND_E, MVT::i8),
8805 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8808 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8812 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8813 EVT VT = Op.getValueType();
8814 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8815 DebugLoc dl = Op.getDebugLoc();
8817 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8818 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8819 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8820 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8821 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8823 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8824 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8825 // return AloBlo + AloBhi + AhiBlo;
8827 SDValue A = Op.getOperand(0);
8828 SDValue B = Op.getOperand(1);
8830 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8831 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8832 A, DAG.getConstant(32, MVT::i32));
8833 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8834 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8835 B, DAG.getConstant(32, MVT::i32));
8836 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8837 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8839 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8840 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8842 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8843 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8845 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8846 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8847 AloBhi, DAG.getConstant(32, MVT::i32));
8848 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8849 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8850 AhiBlo, DAG.getConstant(32, MVT::i32));
8851 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8852 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8856 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8858 EVT VT = Op.getValueType();
8859 DebugLoc dl = Op.getDebugLoc();
8860 SDValue R = Op.getOperand(0);
8861 SDValue Amt = Op.getOperand(1);
8863 LLVMContext *Context = DAG.getContext();
8866 if (!Subtarget->hasSSE2()) return SDValue();
8868 // Optimize shl/srl/sra with constant shift amount.
8869 if (isSplatVector(Amt.getNode())) {
8870 SDValue SclrAmt = Amt->getOperand(0);
8871 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8872 uint64_t ShiftAmt = C->getZExtValue();
8874 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8875 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8876 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8877 R, DAG.getConstant(ShiftAmt, MVT::i32));
8879 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
8880 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8881 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8882 R, DAG.getConstant(ShiftAmt, MVT::i32));
8884 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
8885 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8886 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8887 R, DAG.getConstant(ShiftAmt, MVT::i32));
8889 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
8890 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8891 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8892 R, DAG.getConstant(ShiftAmt, MVT::i32));
8894 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
8895 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8896 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8897 R, DAG.getConstant(ShiftAmt, MVT::i32));
8899 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
8900 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8901 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8902 R, DAG.getConstant(ShiftAmt, MVT::i32));
8904 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
8905 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8906 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8907 R, DAG.getConstant(ShiftAmt, MVT::i32));
8909 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
8910 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8911 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8912 R, DAG.getConstant(ShiftAmt, MVT::i32));
8916 // Lower SHL with variable shift amount.
8917 // Cannot lower SHL without SSE2 or later.
8918 if (!Subtarget->hasSSE2()) return SDValue();
8920 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
8921 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8922 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8923 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8925 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8927 std::vector<Constant*> CV(4, CI);
8928 Constant *C = ConstantVector::get(CV);
8929 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8930 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8931 MachinePointerInfo::getConstantPool(),
8934 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8935 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8936 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8937 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8939 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
8941 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8942 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8943 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8945 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8946 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8948 std::vector<Constant*> CVM1(16, CM1);
8949 std::vector<Constant*> CVM2(16, CM2);
8950 Constant *C = ConstantVector::get(CVM1);
8951 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8952 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8953 MachinePointerInfo::getConstantPool(),
8956 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8957 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8958 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8959 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8960 DAG.getConstant(4, MVT::i32));
8961 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8963 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8965 C = ConstantVector::get(CVM2);
8966 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8967 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8968 MachinePointerInfo::getConstantPool(),
8971 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8972 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8973 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8974 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8975 DAG.getConstant(2, MVT::i32));
8976 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8978 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8980 // return pblendv(r, r+r, a);
8981 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8982 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8988 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8989 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8990 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8991 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8992 // has only one use.
8993 SDNode *N = Op.getNode();
8994 SDValue LHS = N->getOperand(0);
8995 SDValue RHS = N->getOperand(1);
8996 unsigned BaseOp = 0;
8998 DebugLoc DL = Op.getDebugLoc();
8999 switch (Op.getOpcode()) {
9000 default: llvm_unreachable("Unknown ovf instruction!");
9002 // A subtract of one will be selected as a INC. Note that INC doesn't
9003 // set CF, so we can't do this for UADDO.
9004 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9006 BaseOp = X86ISD::INC;
9010 BaseOp = X86ISD::ADD;
9014 BaseOp = X86ISD::ADD;
9018 // A subtract of one will be selected as a DEC. Note that DEC doesn't
9019 // set CF, so we can't do this for USUBO.
9020 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9022 BaseOp = X86ISD::DEC;
9026 BaseOp = X86ISD::SUB;
9030 BaseOp = X86ISD::SUB;
9034 BaseOp = X86ISD::SMUL;
9037 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9038 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9040 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9043 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9044 DAG.getConstant(X86::COND_O, MVT::i32),
9045 SDValue(Sum.getNode(), 2));
9047 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9052 // Also sets EFLAGS.
9053 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9054 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9057 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9058 DAG.getConstant(Cond, MVT::i32),
9059 SDValue(Sum.getNode(), 1));
9061 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9065 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
9066 DebugLoc dl = Op.getDebugLoc();
9067 SDNode* Node = Op.getNode();
9068 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
9069 EVT VT = Node->getValueType(0);
9071 if (Subtarget->hasSSE2() && VT.isVector()) {
9072 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
9073 ExtraVT.getScalarType().getSizeInBits();
9074 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
9076 unsigned SHLIntrinsicsID = 0;
9077 unsigned SRAIntrinsicsID = 0;
9078 switch (VT.getSimpleVT().SimpleTy) {
9082 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q;
9083 SRAIntrinsicsID = 0;
9087 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
9088 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
9092 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
9093 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
9098 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9099 DAG.getConstant(SHLIntrinsicsID, MVT::i32),
9100 Node->getOperand(0), ShAmt);
9102 // In case of 1 bit sext, no need to shr
9103 if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
9105 if (SRAIntrinsicsID) {
9106 Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9107 DAG.getConstant(SRAIntrinsicsID, MVT::i32),
9117 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9118 DebugLoc dl = Op.getDebugLoc();
9120 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
9121 // There isn't any reason to disable it if the target processor supports it.
9122 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
9123 SDValue Chain = Op.getOperand(0);
9124 SDValue Zero = DAG.getConstant(0, MVT::i32);
9126 DAG.getRegister(X86::ESP, MVT::i32), // Base
9127 DAG.getTargetConstant(1, MVT::i8), // Scale
9128 DAG.getRegister(0, MVT::i32), // Index
9129 DAG.getTargetConstant(0, MVT::i32), // Disp
9130 DAG.getRegister(0, MVT::i32), // Segment.
9135 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9136 array_lengthof(Ops));
9137 return SDValue(Res, 0);
9140 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9142 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9144 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9145 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9146 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9147 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9149 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9150 if (!Op1 && !Op2 && !Op3 && Op4)
9151 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9153 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9154 if (Op1 && !Op2 && !Op3 && !Op4)
9155 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9157 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9159 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9162 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9163 EVT T = Op.getValueType();
9164 DebugLoc DL = Op.getDebugLoc();
9167 switch(T.getSimpleVT().SimpleTy) {
9169 assert(false && "Invalid value type!");
9170 case MVT::i8: Reg = X86::AL; size = 1; break;
9171 case MVT::i16: Reg = X86::AX; size = 2; break;
9172 case MVT::i32: Reg = X86::EAX; size = 4; break;
9174 assert(Subtarget->is64Bit() && "Node not type legal!");
9175 Reg = X86::RAX; size = 8;
9178 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9179 Op.getOperand(2), SDValue());
9180 SDValue Ops[] = { cpIn.getValue(0),
9183 DAG.getTargetConstant(size, MVT::i8),
9185 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9186 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9187 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9190 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9194 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9195 SelectionDAG &DAG) const {
9196 assert(Subtarget->is64Bit() && "Result not type legalized?");
9197 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9198 SDValue TheChain = Op.getOperand(0);
9199 DebugLoc dl = Op.getDebugLoc();
9200 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9201 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9202 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9204 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9205 DAG.getConstant(32, MVT::i8));
9207 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9210 return DAG.getMergeValues(Ops, 2, dl);
9213 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9214 SelectionDAG &DAG) const {
9215 EVT SrcVT = Op.getOperand(0).getValueType();
9216 EVT DstVT = Op.getValueType();
9217 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9218 Subtarget->hasMMX() && "Unexpected custom BITCAST");
9219 assert((DstVT == MVT::i64 ||
9220 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9221 "Unexpected custom BITCAST");
9222 // i64 <=> MMX conversions are Legal.
9223 if (SrcVT==MVT::i64 && DstVT.isVector())
9225 if (DstVT==MVT::i64 && SrcVT.isVector())
9227 // MMX <=> MMX conversions are Legal.
9228 if (SrcVT.isVector() && DstVT.isVector())
9230 // All other conversions need to be expanded.
9234 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9235 SDNode *Node = Op.getNode();
9236 DebugLoc dl = Node->getDebugLoc();
9237 EVT T = Node->getValueType(0);
9238 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9239 DAG.getConstant(0, T), Node->getOperand(2));
9240 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9241 cast<AtomicSDNode>(Node)->getMemoryVT(),
9242 Node->getOperand(0),
9243 Node->getOperand(1), negOp,
9244 cast<AtomicSDNode>(Node)->getSrcValue(),
9245 cast<AtomicSDNode>(Node)->getAlignment());
9248 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9249 EVT VT = Op.getNode()->getValueType(0);
9251 // Let legalize expand this if it isn't a legal type yet.
9252 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9255 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9258 bool ExtraOp = false;
9259 switch (Op.getOpcode()) {
9260 default: assert(0 && "Invalid code");
9261 case ISD::ADDC: Opc = X86ISD::ADD; break;
9262 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9263 case ISD::SUBC: Opc = X86ISD::SUB; break;
9264 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9268 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9270 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9271 Op.getOperand(1), Op.getOperand(2));
9274 /// LowerOperation - Provide custom lowering hooks for some operations.
9276 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9277 switch (Op.getOpcode()) {
9278 default: llvm_unreachable("Should not custom lower this!");
9279 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
9280 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
9281 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
9282 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
9283 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
9284 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
9285 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
9286 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9287 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9288 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
9289 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
9290 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
9291 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9292 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9293 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9294 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
9295 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
9296 case ISD::SHL_PARTS:
9297 case ISD::SRA_PARTS:
9298 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
9299 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
9300 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
9301 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
9302 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
9303 case ISD::FABS: return LowerFABS(Op, DAG);
9304 case ISD::FNEG: return LowerFNEG(Op, DAG);
9305 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
9306 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
9307 case ISD::SETCC: return LowerSETCC(Op, DAG);
9308 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
9309 case ISD::SELECT: return LowerSELECT(Op, DAG);
9310 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
9311 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
9312 case ISD::VASTART: return LowerVASTART(Op, DAG);
9313 case ISD::VAARG: return LowerVAARG(Op, DAG);
9314 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
9315 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9316 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9317 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9318 case ISD::FRAME_TO_ARGS_OFFSET:
9319 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9320 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9321 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
9322 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
9323 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9324 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
9325 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
9326 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
9329 case ISD::SHL: return LowerShift(Op, DAG);
9335 case ISD::UMULO: return LowerXALUO(Op, DAG);
9336 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
9337 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
9341 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9345 void X86TargetLowering::
9346 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9347 SelectionDAG &DAG, unsigned NewOp) const {
9348 EVT T = Node->getValueType(0);
9349 DebugLoc dl = Node->getDebugLoc();
9350 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9352 SDValue Chain = Node->getOperand(0);
9353 SDValue In1 = Node->getOperand(1);
9354 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9355 Node->getOperand(2), DAG.getIntPtrConstant(0));
9356 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9357 Node->getOperand(2), DAG.getIntPtrConstant(1));
9358 SDValue Ops[] = { Chain, In1, In2L, In2H };
9359 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9361 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9362 cast<MemSDNode>(Node)->getMemOperand());
9363 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9364 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9365 Results.push_back(Result.getValue(2));
9368 /// ReplaceNodeResults - Replace a node with an illegal result type
9369 /// with a new node built out of custom code.
9370 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9371 SmallVectorImpl<SDValue>&Results,
9372 SelectionDAG &DAG) const {
9373 DebugLoc dl = N->getDebugLoc();
9374 switch (N->getOpcode()) {
9376 assert(false && "Do not know how to custom type legalize this operation!");
9378 case ISD::SIGN_EXTEND_INREG:
9383 // We don't want to expand or promote these.
9385 case ISD::FP_TO_SINT: {
9386 std::pair<SDValue,SDValue> Vals =
9387 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9388 SDValue FIST = Vals.first, StackSlot = Vals.second;
9389 if (FIST.getNode() != 0) {
9390 EVT VT = N->getValueType(0);
9391 // Return a load from the stack slot.
9392 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9393 MachinePointerInfo(), false, false, 0));
9397 case ISD::READCYCLECOUNTER: {
9398 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9399 SDValue TheChain = N->getOperand(0);
9400 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9401 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9403 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9405 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9406 SDValue Ops[] = { eax, edx };
9407 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9408 Results.push_back(edx.getValue(1));
9411 case ISD::ATOMIC_CMP_SWAP: {
9412 EVT T = N->getValueType(0);
9413 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9414 SDValue cpInL, cpInH;
9415 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9416 DAG.getConstant(0, MVT::i32));
9417 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9418 DAG.getConstant(1, MVT::i32));
9419 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9420 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9422 SDValue swapInL, swapInH;
9423 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9424 DAG.getConstant(0, MVT::i32));
9425 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9426 DAG.getConstant(1, MVT::i32));
9427 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9429 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9430 swapInL.getValue(1));
9431 SDValue Ops[] = { swapInH.getValue(0),
9433 swapInH.getValue(1) };
9434 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9435 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9436 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9438 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9439 MVT::i32, Result.getValue(1));
9440 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9441 MVT::i32, cpOutL.getValue(2));
9442 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9443 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9444 Results.push_back(cpOutH.getValue(1));
9447 case ISD::ATOMIC_LOAD_ADD:
9448 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9450 case ISD::ATOMIC_LOAD_AND:
9451 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9453 case ISD::ATOMIC_LOAD_NAND:
9454 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9456 case ISD::ATOMIC_LOAD_OR:
9457 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9459 case ISD::ATOMIC_LOAD_SUB:
9460 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9462 case ISD::ATOMIC_LOAD_XOR:
9463 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9465 case ISD::ATOMIC_SWAP:
9466 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9471 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9473 default: return NULL;
9474 case X86ISD::BSF: return "X86ISD::BSF";
9475 case X86ISD::BSR: return "X86ISD::BSR";
9476 case X86ISD::SHLD: return "X86ISD::SHLD";
9477 case X86ISD::SHRD: return "X86ISD::SHRD";
9478 case X86ISD::FAND: return "X86ISD::FAND";
9479 case X86ISD::FOR: return "X86ISD::FOR";
9480 case X86ISD::FXOR: return "X86ISD::FXOR";
9481 case X86ISD::FSRL: return "X86ISD::FSRL";
9482 case X86ISD::FILD: return "X86ISD::FILD";
9483 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
9484 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9485 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9486 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9487 case X86ISD::FLD: return "X86ISD::FLD";
9488 case X86ISD::FST: return "X86ISD::FST";
9489 case X86ISD::CALL: return "X86ISD::CALL";
9490 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
9491 case X86ISD::BT: return "X86ISD::BT";
9492 case X86ISD::CMP: return "X86ISD::CMP";
9493 case X86ISD::COMI: return "X86ISD::COMI";
9494 case X86ISD::UCOMI: return "X86ISD::UCOMI";
9495 case X86ISD::SETCC: return "X86ISD::SETCC";
9496 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
9497 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
9498 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
9499 case X86ISD::CMOV: return "X86ISD::CMOV";
9500 case X86ISD::BRCOND: return "X86ISD::BRCOND";
9501 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
9502 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
9503 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
9504 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
9505 case X86ISD::Wrapper: return "X86ISD::Wrapper";
9506 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
9507 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
9508 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
9509 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
9510 case X86ISD::PINSRB: return "X86ISD::PINSRB";
9511 case X86ISD::PINSRW: return "X86ISD::PINSRW";
9512 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
9513 case X86ISD::ANDNP: return "X86ISD::ANDNP";
9514 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
9515 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
9516 case X86ISD::PSIGND: return "X86ISD::PSIGND";
9517 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB";
9518 case X86ISD::FMAX: return "X86ISD::FMAX";
9519 case X86ISD::FMIN: return "X86ISD::FMIN";
9520 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
9521 case X86ISD::FRCP: return "X86ISD::FRCP";
9522 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
9523 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
9524 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
9525 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
9526 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
9527 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
9528 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
9529 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
9530 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
9531 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
9532 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
9533 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
9534 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
9535 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
9536 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
9537 case X86ISD::VSHL: return "X86ISD::VSHL";
9538 case X86ISD::VSRL: return "X86ISD::VSRL";
9539 case X86ISD::CMPPD: return "X86ISD::CMPPD";
9540 case X86ISD::CMPPS: return "X86ISD::CMPPS";
9541 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
9542 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
9543 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
9544 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
9545 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
9546 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
9547 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
9548 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
9549 case X86ISD::ADD: return "X86ISD::ADD";
9550 case X86ISD::SUB: return "X86ISD::SUB";
9551 case X86ISD::ADC: return "X86ISD::ADC";
9552 case X86ISD::SBB: return "X86ISD::SBB";
9553 case X86ISD::SMUL: return "X86ISD::SMUL";
9554 case X86ISD::UMUL: return "X86ISD::UMUL";
9555 case X86ISD::INC: return "X86ISD::INC";
9556 case X86ISD::DEC: return "X86ISD::DEC";
9557 case X86ISD::OR: return "X86ISD::OR";
9558 case X86ISD::XOR: return "X86ISD::XOR";
9559 case X86ISD::AND: return "X86ISD::AND";
9560 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
9561 case X86ISD::PTEST: return "X86ISD::PTEST";
9562 case X86ISD::TESTP: return "X86ISD::TESTP";
9563 case X86ISD::PALIGN: return "X86ISD::PALIGN";
9564 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
9565 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
9566 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
9567 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
9568 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
9569 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
9570 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
9571 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
9572 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
9573 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
9574 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
9575 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
9576 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
9577 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
9578 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
9579 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
9580 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
9581 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
9582 case X86ISD::MOVSD: return "X86ISD::MOVSD";
9583 case X86ISD::MOVSS: return "X86ISD::MOVSS";
9584 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
9585 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
9586 case X86ISD::VUNPCKLPS: return "X86ISD::VUNPCKLPS";
9587 case X86ISD::VUNPCKLPD: return "X86ISD::VUNPCKLPD";
9588 case X86ISD::VUNPCKLPSY: return "X86ISD::VUNPCKLPSY";
9589 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
9590 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
9591 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
9592 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
9593 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
9594 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
9595 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
9596 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
9597 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
9598 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
9599 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
9600 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9601 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
9602 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
9606 // isLegalAddressingMode - Return true if the addressing mode represented
9607 // by AM is legal for this target, for a load/store of the specified type.
9608 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9610 // X86 supports extremely general addressing modes.
9611 CodeModel::Model M = getTargetMachine().getCodeModel();
9612 Reloc::Model R = getTargetMachine().getRelocationModel();
9614 // X86 allows a sign-extended 32-bit immediate field as a displacement.
9615 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9620 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9622 // If a reference to this global requires an extra load, we can't fold it.
9623 if (isGlobalStubReference(GVFlags))
9626 // If BaseGV requires a register for the PIC base, we cannot also have a
9627 // BaseReg specified.
9628 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9631 // If lower 4G is not available, then we must use rip-relative addressing.
9632 if ((M != CodeModel::Small || R != Reloc::Static) &&
9633 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9643 // These scales always work.
9648 // These scales are formed with basereg+scalereg. Only accept if there is
9653 default: // Other stuff never works.
9661 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9662 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9664 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9665 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9666 if (NumBits1 <= NumBits2)
9671 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9672 if (!VT1.isInteger() || !VT2.isInteger())
9674 unsigned NumBits1 = VT1.getSizeInBits();
9675 unsigned NumBits2 = VT2.getSizeInBits();
9676 if (NumBits1 <= NumBits2)
9681 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
9682 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9683 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9686 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9687 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9688 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9691 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9692 // i16 instructions are longer (0x66 prefix) and potentially slower.
9693 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9696 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9697 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9698 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9699 /// are assumed to be legal.
9701 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9703 // Very little shuffling can be done for 64-bit vectors right now.
9704 if (VT.getSizeInBits() == 64)
9705 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9707 // FIXME: pshufb, blends, shifts.
9708 return (VT.getVectorNumElements() == 2 ||
9709 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9710 isMOVLMask(M, VT) ||
9711 isSHUFPMask(M, VT) ||
9712 isPSHUFDMask(M, VT) ||
9713 isPSHUFHWMask(M, VT) ||
9714 isPSHUFLWMask(M, VT) ||
9715 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9716 isUNPCKLMask(M, VT) ||
9717 isUNPCKHMask(M, VT) ||
9718 isUNPCKL_v_undef_Mask(M, VT) ||
9719 isUNPCKH_v_undef_Mask(M, VT));
9723 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9725 unsigned NumElts = VT.getVectorNumElements();
9726 // FIXME: This collection of masks seems suspect.
9729 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9730 return (isMOVLMask(Mask, VT) ||
9731 isCommutedMOVLMask(Mask, VT, true) ||
9732 isSHUFPMask(Mask, VT) ||
9733 isCommutedSHUFPMask(Mask, VT));
9738 //===----------------------------------------------------------------------===//
9739 // X86 Scheduler Hooks
9740 //===----------------------------------------------------------------------===//
9742 // private utility function
9744 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9745 MachineBasicBlock *MBB,
9752 TargetRegisterClass *RC,
9753 bool invSrc) const {
9754 // For the atomic bitwise operator, we generate
9757 // ld t1 = [bitinstr.addr]
9758 // op t2 = t1, [bitinstr.val]
9760 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9762 // fallthrough -->nextMBB
9763 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9764 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9765 MachineFunction::iterator MBBIter = MBB;
9768 /// First build the CFG
9769 MachineFunction *F = MBB->getParent();
9770 MachineBasicBlock *thisMBB = MBB;
9771 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9772 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9773 F->insert(MBBIter, newMBB);
9774 F->insert(MBBIter, nextMBB);
9776 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9777 nextMBB->splice(nextMBB->begin(), thisMBB,
9778 llvm::next(MachineBasicBlock::iterator(bInstr)),
9780 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9782 // Update thisMBB to fall through to newMBB
9783 thisMBB->addSuccessor(newMBB);
9785 // newMBB jumps to itself and fall through to nextMBB
9786 newMBB->addSuccessor(nextMBB);
9787 newMBB->addSuccessor(newMBB);
9789 // Insert instructions into newMBB based on incoming instruction
9790 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9791 "unexpected number of operands");
9792 DebugLoc dl = bInstr->getDebugLoc();
9793 MachineOperand& destOper = bInstr->getOperand(0);
9794 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9795 int numArgs = bInstr->getNumOperands() - 1;
9796 for (int i=0; i < numArgs; ++i)
9797 argOpers[i] = &bInstr->getOperand(i+1);
9799 // x86 address has 4 operands: base, index, scale, and displacement
9800 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9801 int valArgIndx = lastAddrIndx + 1;
9803 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9804 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9805 for (int i=0; i <= lastAddrIndx; ++i)
9806 (*MIB).addOperand(*argOpers[i]);
9808 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9810 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9815 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9816 assert((argOpers[valArgIndx]->isReg() ||
9817 argOpers[valArgIndx]->isImm()) &&
9819 if (argOpers[valArgIndx]->isReg())
9820 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9822 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9824 (*MIB).addOperand(*argOpers[valArgIndx]);
9826 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9829 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9830 for (int i=0; i <= lastAddrIndx; ++i)
9831 (*MIB).addOperand(*argOpers[i]);
9833 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9834 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9835 bInstr->memoperands_end());
9837 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9841 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9843 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9847 // private utility function: 64 bit atomics on 32 bit host.
9849 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9850 MachineBasicBlock *MBB,
9855 bool invSrc) const {
9856 // For the atomic bitwise operator, we generate
9857 // thisMBB (instructions are in pairs, except cmpxchg8b)
9858 // ld t1,t2 = [bitinstr.addr]
9860 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9861 // op t5, t6 <- out1, out2, [bitinstr.val]
9862 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9863 // mov ECX, EBX <- t5, t6
9864 // mov EAX, EDX <- t1, t2
9865 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9866 // mov t3, t4 <- EAX, EDX
9868 // result in out1, out2
9869 // fallthrough -->nextMBB
9871 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9872 const unsigned LoadOpc = X86::MOV32rm;
9873 const unsigned NotOpc = X86::NOT32r;
9874 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9875 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9876 MachineFunction::iterator MBBIter = MBB;
9879 /// First build the CFG
9880 MachineFunction *F = MBB->getParent();
9881 MachineBasicBlock *thisMBB = MBB;
9882 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9883 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9884 F->insert(MBBIter, newMBB);
9885 F->insert(MBBIter, nextMBB);
9887 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9888 nextMBB->splice(nextMBB->begin(), thisMBB,
9889 llvm::next(MachineBasicBlock::iterator(bInstr)),
9891 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9893 // Update thisMBB to fall through to newMBB
9894 thisMBB->addSuccessor(newMBB);
9896 // newMBB jumps to itself and fall through to nextMBB
9897 newMBB->addSuccessor(nextMBB);
9898 newMBB->addSuccessor(newMBB);
9900 DebugLoc dl = bInstr->getDebugLoc();
9901 // Insert instructions into newMBB based on incoming instruction
9902 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9903 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9904 "unexpected number of operands");
9905 MachineOperand& dest1Oper = bInstr->getOperand(0);
9906 MachineOperand& dest2Oper = bInstr->getOperand(1);
9907 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9908 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9909 argOpers[i] = &bInstr->getOperand(i+2);
9911 // We use some of the operands multiple times, so conservatively just
9912 // clear any kill flags that might be present.
9913 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9914 argOpers[i]->setIsKill(false);
9917 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9918 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9920 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9921 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9922 for (int i=0; i <= lastAddrIndx; ++i)
9923 (*MIB).addOperand(*argOpers[i]);
9924 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9925 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9926 // add 4 to displacement.
9927 for (int i=0; i <= lastAddrIndx-2; ++i)
9928 (*MIB).addOperand(*argOpers[i]);
9929 MachineOperand newOp3 = *(argOpers[3]);
9931 newOp3.setImm(newOp3.getImm()+4);
9933 newOp3.setOffset(newOp3.getOffset()+4);
9934 (*MIB).addOperand(newOp3);
9935 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9937 // t3/4 are defined later, at the bottom of the loop
9938 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9939 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9940 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9941 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9942 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9943 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9945 // The subsequent operations should be using the destination registers of
9946 //the PHI instructions.
9948 t1 = F->getRegInfo().createVirtualRegister(RC);
9949 t2 = F->getRegInfo().createVirtualRegister(RC);
9950 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9951 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9953 t1 = dest1Oper.getReg();
9954 t2 = dest2Oper.getReg();
9957 int valArgIndx = lastAddrIndx + 1;
9958 assert((argOpers[valArgIndx]->isReg() ||
9959 argOpers[valArgIndx]->isImm()) &&
9961 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9962 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9963 if (argOpers[valArgIndx]->isReg())
9964 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9966 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9967 if (regOpcL != X86::MOV32rr)
9969 (*MIB).addOperand(*argOpers[valArgIndx]);
9970 assert(argOpers[valArgIndx + 1]->isReg() ==
9971 argOpers[valArgIndx]->isReg());
9972 assert(argOpers[valArgIndx + 1]->isImm() ==
9973 argOpers[valArgIndx]->isImm());
9974 if (argOpers[valArgIndx + 1]->isReg())
9975 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9977 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9978 if (regOpcH != X86::MOV32rr)
9980 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9982 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9984 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9987 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9989 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9992 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9993 for (int i=0; i <= lastAddrIndx; ++i)
9994 (*MIB).addOperand(*argOpers[i]);
9996 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9997 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9998 bInstr->memoperands_end());
10000 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
10001 MIB.addReg(X86::EAX);
10002 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
10003 MIB.addReg(X86::EDX);
10006 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10008 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
10012 // private utility function
10013 MachineBasicBlock *
10014 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
10015 MachineBasicBlock *MBB,
10016 unsigned cmovOpc) const {
10017 // For the atomic min/max operator, we generate
10020 // ld t1 = [min/max.addr]
10021 // mov t2 = [min/max.val]
10023 // cmov[cond] t2 = t1
10025 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
10027 // fallthrough -->nextMBB
10029 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10030 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10031 MachineFunction::iterator MBBIter = MBB;
10034 /// First build the CFG
10035 MachineFunction *F = MBB->getParent();
10036 MachineBasicBlock *thisMBB = MBB;
10037 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10038 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10039 F->insert(MBBIter, newMBB);
10040 F->insert(MBBIter, nextMBB);
10042 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10043 nextMBB->splice(nextMBB->begin(), thisMBB,
10044 llvm::next(MachineBasicBlock::iterator(mInstr)),
10046 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10048 // Update thisMBB to fall through to newMBB
10049 thisMBB->addSuccessor(newMBB);
10051 // newMBB jumps to newMBB and fall through to nextMBB
10052 newMBB->addSuccessor(nextMBB);
10053 newMBB->addSuccessor(newMBB);
10055 DebugLoc dl = mInstr->getDebugLoc();
10056 // Insert instructions into newMBB based on incoming instruction
10057 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10058 "unexpected number of operands");
10059 MachineOperand& destOper = mInstr->getOperand(0);
10060 MachineOperand* argOpers[2 + X86::AddrNumOperands];
10061 int numArgs = mInstr->getNumOperands() - 1;
10062 for (int i=0; i < numArgs; ++i)
10063 argOpers[i] = &mInstr->getOperand(i+1);
10065 // x86 address has 4 operands: base, index, scale, and displacement
10066 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10067 int valArgIndx = lastAddrIndx + 1;
10069 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10070 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10071 for (int i=0; i <= lastAddrIndx; ++i)
10072 (*MIB).addOperand(*argOpers[i]);
10074 // We only support register and immediate values
10075 assert((argOpers[valArgIndx]->isReg() ||
10076 argOpers[valArgIndx]->isImm()) &&
10077 "invalid operand");
10079 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10080 if (argOpers[valArgIndx]->isReg())
10081 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10083 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10084 (*MIB).addOperand(*argOpers[valArgIndx]);
10086 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10089 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10094 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10095 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10099 // Cmp and exchange if none has modified the memory location
10100 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10101 for (int i=0; i <= lastAddrIndx; ++i)
10102 (*MIB).addOperand(*argOpers[i]);
10104 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10105 (*MIB).setMemRefs(mInstr->memoperands_begin(),
10106 mInstr->memoperands_end());
10108 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10109 MIB.addReg(X86::EAX);
10112 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10114 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
10118 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10119 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10120 // in the .td file.
10121 MachineBasicBlock *
10122 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10123 unsigned numArgs, bool memArg) const {
10124 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10125 "Target must have SSE4.2 or AVX features enabled");
10127 DebugLoc dl = MI->getDebugLoc();
10128 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10130 if (!Subtarget->hasAVX()) {
10132 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10134 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10137 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10139 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10142 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10143 for (unsigned i = 0; i < numArgs; ++i) {
10144 MachineOperand &Op = MI->getOperand(i+1);
10145 if (!(Op.isReg() && Op.isImplicit()))
10146 MIB.addOperand(Op);
10148 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10149 .addReg(X86::XMM0);
10151 MI->eraseFromParent();
10155 MachineBasicBlock *
10156 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10157 DebugLoc dl = MI->getDebugLoc();
10158 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10160 // Address into RAX/EAX, other two args into ECX, EDX.
10161 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10162 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10163 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10164 for (int i = 0; i < X86::AddrNumOperands; ++i)
10165 MIB.addOperand(MI->getOperand(i));
10167 unsigned ValOps = X86::AddrNumOperands;
10168 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10169 .addReg(MI->getOperand(ValOps).getReg());
10170 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10171 .addReg(MI->getOperand(ValOps+1).getReg());
10173 // The instruction doesn't actually take any operands though.
10174 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10176 MI->eraseFromParent(); // The pseudo is gone now.
10180 MachineBasicBlock *
10181 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10182 DebugLoc dl = MI->getDebugLoc();
10183 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10185 // First arg in ECX, the second in EAX.
10186 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10187 .addReg(MI->getOperand(0).getReg());
10188 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10189 .addReg(MI->getOperand(1).getReg());
10191 // The instruction doesn't actually take any operands though.
10192 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10194 MI->eraseFromParent(); // The pseudo is gone now.
10198 MachineBasicBlock *
10199 X86TargetLowering::EmitVAARG64WithCustomInserter(
10201 MachineBasicBlock *MBB) const {
10202 // Emit va_arg instruction on X86-64.
10204 // Operands to this pseudo-instruction:
10205 // 0 ) Output : destination address (reg)
10206 // 1-5) Input : va_list address (addr, i64mem)
10207 // 6 ) ArgSize : Size (in bytes) of vararg type
10208 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10209 // 8 ) Align : Alignment of type
10210 // 9 ) EFLAGS (implicit-def)
10212 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10213 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10215 unsigned DestReg = MI->getOperand(0).getReg();
10216 MachineOperand &Base = MI->getOperand(1);
10217 MachineOperand &Scale = MI->getOperand(2);
10218 MachineOperand &Index = MI->getOperand(3);
10219 MachineOperand &Disp = MI->getOperand(4);
10220 MachineOperand &Segment = MI->getOperand(5);
10221 unsigned ArgSize = MI->getOperand(6).getImm();
10222 unsigned ArgMode = MI->getOperand(7).getImm();
10223 unsigned Align = MI->getOperand(8).getImm();
10225 // Memory Reference
10226 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10227 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10228 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10230 // Machine Information
10231 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10232 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10233 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10234 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10235 DebugLoc DL = MI->getDebugLoc();
10237 // struct va_list {
10240 // i64 overflow_area (address)
10241 // i64 reg_save_area (address)
10243 // sizeof(va_list) = 24
10244 // alignment(va_list) = 8
10246 unsigned TotalNumIntRegs = 6;
10247 unsigned TotalNumXMMRegs = 8;
10248 bool UseGPOffset = (ArgMode == 1);
10249 bool UseFPOffset = (ArgMode == 2);
10250 unsigned MaxOffset = TotalNumIntRegs * 8 +
10251 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10253 /* Align ArgSize to a multiple of 8 */
10254 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10255 bool NeedsAlign = (Align > 8);
10257 MachineBasicBlock *thisMBB = MBB;
10258 MachineBasicBlock *overflowMBB;
10259 MachineBasicBlock *offsetMBB;
10260 MachineBasicBlock *endMBB;
10262 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
10263 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
10264 unsigned OffsetReg = 0;
10266 if (!UseGPOffset && !UseFPOffset) {
10267 // If we only pull from the overflow region, we don't create a branch.
10268 // We don't need to alter control flow.
10269 OffsetDestReg = 0; // unused
10270 OverflowDestReg = DestReg;
10273 overflowMBB = thisMBB;
10276 // First emit code to check if gp_offset (or fp_offset) is below the bound.
10277 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10278 // If not, pull from overflow_area. (branch to overflowMBB)
10283 // offsetMBB overflowMBB
10288 // Registers for the PHI in endMBB
10289 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10290 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10292 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10293 MachineFunction *MF = MBB->getParent();
10294 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10295 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10296 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10298 MachineFunction::iterator MBBIter = MBB;
10301 // Insert the new basic blocks
10302 MF->insert(MBBIter, offsetMBB);
10303 MF->insert(MBBIter, overflowMBB);
10304 MF->insert(MBBIter, endMBB);
10306 // Transfer the remainder of MBB and its successor edges to endMBB.
10307 endMBB->splice(endMBB->begin(), thisMBB,
10308 llvm::next(MachineBasicBlock::iterator(MI)),
10310 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10312 // Make offsetMBB and overflowMBB successors of thisMBB
10313 thisMBB->addSuccessor(offsetMBB);
10314 thisMBB->addSuccessor(overflowMBB);
10316 // endMBB is a successor of both offsetMBB and overflowMBB
10317 offsetMBB->addSuccessor(endMBB);
10318 overflowMBB->addSuccessor(endMBB);
10320 // Load the offset value into a register
10321 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10322 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10326 .addDisp(Disp, UseFPOffset ? 4 : 0)
10327 .addOperand(Segment)
10328 .setMemRefs(MMOBegin, MMOEnd);
10330 // Check if there is enough room left to pull this argument.
10331 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10333 .addImm(MaxOffset + 8 - ArgSizeA8);
10335 // Branch to "overflowMBB" if offset >= max
10336 // Fall through to "offsetMBB" otherwise
10337 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10338 .addMBB(overflowMBB);
10341 // In offsetMBB, emit code to use the reg_save_area.
10343 assert(OffsetReg != 0);
10345 // Read the reg_save_area address.
10346 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10347 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10352 .addOperand(Segment)
10353 .setMemRefs(MMOBegin, MMOEnd);
10355 // Zero-extend the offset
10356 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10357 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10360 .addImm(X86::sub_32bit);
10362 // Add the offset to the reg_save_area to get the final address.
10363 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10364 .addReg(OffsetReg64)
10365 .addReg(RegSaveReg);
10367 // Compute the offset for the next argument
10368 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10369 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10371 .addImm(UseFPOffset ? 16 : 8);
10373 // Store it back into the va_list.
10374 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10378 .addDisp(Disp, UseFPOffset ? 4 : 0)
10379 .addOperand(Segment)
10380 .addReg(NextOffsetReg)
10381 .setMemRefs(MMOBegin, MMOEnd);
10384 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10389 // Emit code to use overflow area
10392 // Load the overflow_area address into a register.
10393 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10394 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10399 .addOperand(Segment)
10400 .setMemRefs(MMOBegin, MMOEnd);
10402 // If we need to align it, do so. Otherwise, just copy the address
10403 // to OverflowDestReg.
10405 // Align the overflow address
10406 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10407 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10409 // aligned_addr = (addr + (align-1)) & ~(align-1)
10410 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10411 .addReg(OverflowAddrReg)
10414 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10416 .addImm(~(uint64_t)(Align-1));
10418 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10419 .addReg(OverflowAddrReg);
10422 // Compute the next overflow address after this argument.
10423 // (the overflow address should be kept 8-byte aligned)
10424 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10425 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10426 .addReg(OverflowDestReg)
10427 .addImm(ArgSizeA8);
10429 // Store the new overflow address.
10430 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10435 .addOperand(Segment)
10436 .addReg(NextAddrReg)
10437 .setMemRefs(MMOBegin, MMOEnd);
10439 // If we branched, emit the PHI to the front of endMBB.
10441 BuildMI(*endMBB, endMBB->begin(), DL,
10442 TII->get(X86::PHI), DestReg)
10443 .addReg(OffsetDestReg).addMBB(offsetMBB)
10444 .addReg(OverflowDestReg).addMBB(overflowMBB);
10447 // Erase the pseudo instruction
10448 MI->eraseFromParent();
10453 MachineBasicBlock *
10454 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10456 MachineBasicBlock *MBB) const {
10457 // Emit code to save XMM registers to the stack. The ABI says that the
10458 // number of registers to save is given in %al, so it's theoretically
10459 // possible to do an indirect jump trick to avoid saving all of them,
10460 // however this code takes a simpler approach and just executes all
10461 // of the stores if %al is non-zero. It's less code, and it's probably
10462 // easier on the hardware branch predictor, and stores aren't all that
10463 // expensive anyway.
10465 // Create the new basic blocks. One block contains all the XMM stores,
10466 // and one block is the final destination regardless of whether any
10467 // stores were performed.
10468 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10469 MachineFunction *F = MBB->getParent();
10470 MachineFunction::iterator MBBIter = MBB;
10472 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10473 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10474 F->insert(MBBIter, XMMSaveMBB);
10475 F->insert(MBBIter, EndMBB);
10477 // Transfer the remainder of MBB and its successor edges to EndMBB.
10478 EndMBB->splice(EndMBB->begin(), MBB,
10479 llvm::next(MachineBasicBlock::iterator(MI)),
10481 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10483 // The original block will now fall through to the XMM save block.
10484 MBB->addSuccessor(XMMSaveMBB);
10485 // The XMMSaveMBB will fall through to the end block.
10486 XMMSaveMBB->addSuccessor(EndMBB);
10488 // Now add the instructions.
10489 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10490 DebugLoc DL = MI->getDebugLoc();
10492 unsigned CountReg = MI->getOperand(0).getReg();
10493 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10494 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10496 if (!Subtarget->isTargetWin64()) {
10497 // If %al is 0, branch around the XMM save block.
10498 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10499 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10500 MBB->addSuccessor(EndMBB);
10503 // In the XMM save block, save all the XMM argument registers.
10504 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10505 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10506 MachineMemOperand *MMO =
10507 F->getMachineMemOperand(
10508 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10509 MachineMemOperand::MOStore,
10510 /*Size=*/16, /*Align=*/16);
10511 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10512 .addFrameIndex(RegSaveFrameIndex)
10513 .addImm(/*Scale=*/1)
10514 .addReg(/*IndexReg=*/0)
10515 .addImm(/*Disp=*/Offset)
10516 .addReg(/*Segment=*/0)
10517 .addReg(MI->getOperand(i).getReg())
10518 .addMemOperand(MMO);
10521 MI->eraseFromParent(); // The pseudo instruction is gone now.
10526 MachineBasicBlock *
10527 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10528 MachineBasicBlock *BB) const {
10529 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10530 DebugLoc DL = MI->getDebugLoc();
10532 // To "insert" a SELECT_CC instruction, we actually have to insert the
10533 // diamond control-flow pattern. The incoming instruction knows the
10534 // destination vreg to set, the condition code register to branch on, the
10535 // true/false values to select between, and a branch opcode to use.
10536 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10537 MachineFunction::iterator It = BB;
10543 // cmpTY ccX, r1, r2
10545 // fallthrough --> copy0MBB
10546 MachineBasicBlock *thisMBB = BB;
10547 MachineFunction *F = BB->getParent();
10548 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10549 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10550 F->insert(It, copy0MBB);
10551 F->insert(It, sinkMBB);
10553 // If the EFLAGS register isn't dead in the terminator, then claim that it's
10554 // live into the sink and copy blocks.
10555 const MachineFunction *MF = BB->getParent();
10556 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10557 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10559 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10560 const MachineOperand &MO = MI->getOperand(I);
10561 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10562 unsigned Reg = MO.getReg();
10563 if (Reg != X86::EFLAGS) continue;
10564 copy0MBB->addLiveIn(Reg);
10565 sinkMBB->addLiveIn(Reg);
10568 // Transfer the remainder of BB and its successor edges to sinkMBB.
10569 sinkMBB->splice(sinkMBB->begin(), BB,
10570 llvm::next(MachineBasicBlock::iterator(MI)),
10572 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10574 // Add the true and fallthrough blocks as its successors.
10575 BB->addSuccessor(copy0MBB);
10576 BB->addSuccessor(sinkMBB);
10578 // Create the conditional branch instruction.
10580 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10581 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10584 // %FalseValue = ...
10585 // # fallthrough to sinkMBB
10586 copy0MBB->addSuccessor(sinkMBB);
10589 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10591 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10592 TII->get(X86::PHI), MI->getOperand(0).getReg())
10593 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10594 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10596 MI->eraseFromParent(); // The pseudo instruction is gone now.
10600 MachineBasicBlock *
10601 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10602 MachineBasicBlock *BB) const {
10603 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10604 DebugLoc DL = MI->getDebugLoc();
10606 assert(!Subtarget->isTargetEnvMacho());
10608 // The lowering is pretty easy: we're just emitting the call to _alloca. The
10609 // non-trivial part is impdef of ESP.
10611 if (Subtarget->isTargetWin64()) {
10612 if (Subtarget->isTargetCygMing()) {
10613 // ___chkstk(Mingw64):
10614 // Clobbers R10, R11, RAX and EFLAGS.
10616 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10617 .addExternalSymbol("___chkstk")
10618 .addReg(X86::RAX, RegState::Implicit)
10619 .addReg(X86::RSP, RegState::Implicit)
10620 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10621 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10622 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10624 // __chkstk(MSVCRT): does not update stack pointer.
10625 // Clobbers R10, R11 and EFLAGS.
10626 // FIXME: RAX(allocated size) might be reused and not killed.
10627 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10628 .addExternalSymbol("__chkstk")
10629 .addReg(X86::RAX, RegState::Implicit)
10630 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10631 // RAX has the offset to subtracted from RSP.
10632 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10637 const char *StackProbeSymbol =
10638 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10640 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10641 .addExternalSymbol(StackProbeSymbol)
10642 .addReg(X86::EAX, RegState::Implicit)
10643 .addReg(X86::ESP, RegState::Implicit)
10644 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10645 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10646 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10649 MI->eraseFromParent(); // The pseudo instruction is gone now.
10653 MachineBasicBlock *
10654 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10655 MachineBasicBlock *BB) const {
10656 // This is pretty easy. We're taking the value that we received from
10657 // our load from the relocation, sticking it in either RDI (x86-64)
10658 // or EAX and doing an indirect call. The return value will then
10659 // be in the normal return register.
10660 const X86InstrInfo *TII
10661 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10662 DebugLoc DL = MI->getDebugLoc();
10663 MachineFunction *F = BB->getParent();
10665 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10666 assert(MI->getOperand(3).isGlobal() && "This should be a global");
10668 if (Subtarget->is64Bit()) {
10669 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10670 TII->get(X86::MOV64rm), X86::RDI)
10672 .addImm(0).addReg(0)
10673 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10674 MI->getOperand(3).getTargetFlags())
10676 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10677 addDirectMem(MIB, X86::RDI);
10678 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10679 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10680 TII->get(X86::MOV32rm), X86::EAX)
10682 .addImm(0).addReg(0)
10683 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10684 MI->getOperand(3).getTargetFlags())
10686 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10687 addDirectMem(MIB, X86::EAX);
10689 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10690 TII->get(X86::MOV32rm), X86::EAX)
10691 .addReg(TII->getGlobalBaseReg(F))
10692 .addImm(0).addReg(0)
10693 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10694 MI->getOperand(3).getTargetFlags())
10696 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10697 addDirectMem(MIB, X86::EAX);
10700 MI->eraseFromParent(); // The pseudo instruction is gone now.
10704 MachineBasicBlock *
10705 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10706 MachineBasicBlock *BB) const {
10707 switch (MI->getOpcode()) {
10708 default: assert(false && "Unexpected instr type to insert");
10709 case X86::TAILJMPd64:
10710 case X86::TAILJMPr64:
10711 case X86::TAILJMPm64:
10712 assert(!"TAILJMP64 would not be touched here.");
10713 case X86::TCRETURNdi64:
10714 case X86::TCRETURNri64:
10715 case X86::TCRETURNmi64:
10716 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10717 // On AMD64, additional defs should be added before register allocation.
10718 if (!Subtarget->isTargetWin64()) {
10719 MI->addRegisterDefined(X86::RSI);
10720 MI->addRegisterDefined(X86::RDI);
10721 MI->addRegisterDefined(X86::XMM6);
10722 MI->addRegisterDefined(X86::XMM7);
10723 MI->addRegisterDefined(X86::XMM8);
10724 MI->addRegisterDefined(X86::XMM9);
10725 MI->addRegisterDefined(X86::XMM10);
10726 MI->addRegisterDefined(X86::XMM11);
10727 MI->addRegisterDefined(X86::XMM12);
10728 MI->addRegisterDefined(X86::XMM13);
10729 MI->addRegisterDefined(X86::XMM14);
10730 MI->addRegisterDefined(X86::XMM15);
10733 case X86::WIN_ALLOCA:
10734 return EmitLoweredWinAlloca(MI, BB);
10735 case X86::TLSCall_32:
10736 case X86::TLSCall_64:
10737 return EmitLoweredTLSCall(MI, BB);
10738 case X86::CMOV_GR8:
10739 case X86::CMOV_FR32:
10740 case X86::CMOV_FR64:
10741 case X86::CMOV_V4F32:
10742 case X86::CMOV_V2F64:
10743 case X86::CMOV_V2I64:
10744 case X86::CMOV_GR16:
10745 case X86::CMOV_GR32:
10746 case X86::CMOV_RFP32:
10747 case X86::CMOV_RFP64:
10748 case X86::CMOV_RFP80:
10749 return EmitLoweredSelect(MI, BB);
10751 case X86::FP32_TO_INT16_IN_MEM:
10752 case X86::FP32_TO_INT32_IN_MEM:
10753 case X86::FP32_TO_INT64_IN_MEM:
10754 case X86::FP64_TO_INT16_IN_MEM:
10755 case X86::FP64_TO_INT32_IN_MEM:
10756 case X86::FP64_TO_INT64_IN_MEM:
10757 case X86::FP80_TO_INT16_IN_MEM:
10758 case X86::FP80_TO_INT32_IN_MEM:
10759 case X86::FP80_TO_INT64_IN_MEM: {
10760 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10761 DebugLoc DL = MI->getDebugLoc();
10763 // Change the floating point control register to use "round towards zero"
10764 // mode when truncating to an integer value.
10765 MachineFunction *F = BB->getParent();
10766 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10767 addFrameReference(BuildMI(*BB, MI, DL,
10768 TII->get(X86::FNSTCW16m)), CWFrameIdx);
10770 // Load the old value of the high byte of the control word...
10772 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10773 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10776 // Set the high part to be round to zero...
10777 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10780 // Reload the modified control word now...
10781 addFrameReference(BuildMI(*BB, MI, DL,
10782 TII->get(X86::FLDCW16m)), CWFrameIdx);
10784 // Restore the memory image of control word to original value
10785 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10788 // Get the X86 opcode to use.
10790 switch (MI->getOpcode()) {
10791 default: llvm_unreachable("illegal opcode!");
10792 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10793 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10794 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10795 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10796 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10797 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10798 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10799 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10800 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10804 MachineOperand &Op = MI->getOperand(0);
10806 AM.BaseType = X86AddressMode::RegBase;
10807 AM.Base.Reg = Op.getReg();
10809 AM.BaseType = X86AddressMode::FrameIndexBase;
10810 AM.Base.FrameIndex = Op.getIndex();
10812 Op = MI->getOperand(1);
10814 AM.Scale = Op.getImm();
10815 Op = MI->getOperand(2);
10817 AM.IndexReg = Op.getImm();
10818 Op = MI->getOperand(3);
10819 if (Op.isGlobal()) {
10820 AM.GV = Op.getGlobal();
10822 AM.Disp = Op.getImm();
10824 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10825 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10827 // Reload the original control word now.
10828 addFrameReference(BuildMI(*BB, MI, DL,
10829 TII->get(X86::FLDCW16m)), CWFrameIdx);
10831 MI->eraseFromParent(); // The pseudo instruction is gone now.
10834 // String/text processing lowering.
10835 case X86::PCMPISTRM128REG:
10836 case X86::VPCMPISTRM128REG:
10837 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10838 case X86::PCMPISTRM128MEM:
10839 case X86::VPCMPISTRM128MEM:
10840 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10841 case X86::PCMPESTRM128REG:
10842 case X86::VPCMPESTRM128REG:
10843 return EmitPCMP(MI, BB, 5, false /* in mem */);
10844 case X86::PCMPESTRM128MEM:
10845 case X86::VPCMPESTRM128MEM:
10846 return EmitPCMP(MI, BB, 5, true /* in mem */);
10848 // Thread synchronization.
10850 return EmitMonitor(MI, BB);
10852 return EmitMwait(MI, BB);
10854 // Atomic Lowering.
10855 case X86::ATOMAND32:
10856 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10857 X86::AND32ri, X86::MOV32rm,
10859 X86::NOT32r, X86::EAX,
10860 X86::GR32RegisterClass);
10861 case X86::ATOMOR32:
10862 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10863 X86::OR32ri, X86::MOV32rm,
10865 X86::NOT32r, X86::EAX,
10866 X86::GR32RegisterClass);
10867 case X86::ATOMXOR32:
10868 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10869 X86::XOR32ri, X86::MOV32rm,
10871 X86::NOT32r, X86::EAX,
10872 X86::GR32RegisterClass);
10873 case X86::ATOMNAND32:
10874 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10875 X86::AND32ri, X86::MOV32rm,
10877 X86::NOT32r, X86::EAX,
10878 X86::GR32RegisterClass, true);
10879 case X86::ATOMMIN32:
10880 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10881 case X86::ATOMMAX32:
10882 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10883 case X86::ATOMUMIN32:
10884 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10885 case X86::ATOMUMAX32:
10886 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10888 case X86::ATOMAND16:
10889 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10890 X86::AND16ri, X86::MOV16rm,
10892 X86::NOT16r, X86::AX,
10893 X86::GR16RegisterClass);
10894 case X86::ATOMOR16:
10895 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10896 X86::OR16ri, X86::MOV16rm,
10898 X86::NOT16r, X86::AX,
10899 X86::GR16RegisterClass);
10900 case X86::ATOMXOR16:
10901 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10902 X86::XOR16ri, X86::MOV16rm,
10904 X86::NOT16r, X86::AX,
10905 X86::GR16RegisterClass);
10906 case X86::ATOMNAND16:
10907 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10908 X86::AND16ri, X86::MOV16rm,
10910 X86::NOT16r, X86::AX,
10911 X86::GR16RegisterClass, true);
10912 case X86::ATOMMIN16:
10913 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10914 case X86::ATOMMAX16:
10915 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10916 case X86::ATOMUMIN16:
10917 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10918 case X86::ATOMUMAX16:
10919 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10921 case X86::ATOMAND8:
10922 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10923 X86::AND8ri, X86::MOV8rm,
10925 X86::NOT8r, X86::AL,
10926 X86::GR8RegisterClass);
10928 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10929 X86::OR8ri, X86::MOV8rm,
10931 X86::NOT8r, X86::AL,
10932 X86::GR8RegisterClass);
10933 case X86::ATOMXOR8:
10934 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10935 X86::XOR8ri, X86::MOV8rm,
10937 X86::NOT8r, X86::AL,
10938 X86::GR8RegisterClass);
10939 case X86::ATOMNAND8:
10940 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10941 X86::AND8ri, X86::MOV8rm,
10943 X86::NOT8r, X86::AL,
10944 X86::GR8RegisterClass, true);
10945 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10946 // This group is for 64-bit host.
10947 case X86::ATOMAND64:
10948 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10949 X86::AND64ri32, X86::MOV64rm,
10951 X86::NOT64r, X86::RAX,
10952 X86::GR64RegisterClass);
10953 case X86::ATOMOR64:
10954 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10955 X86::OR64ri32, X86::MOV64rm,
10957 X86::NOT64r, X86::RAX,
10958 X86::GR64RegisterClass);
10959 case X86::ATOMXOR64:
10960 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10961 X86::XOR64ri32, X86::MOV64rm,
10963 X86::NOT64r, X86::RAX,
10964 X86::GR64RegisterClass);
10965 case X86::ATOMNAND64:
10966 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10967 X86::AND64ri32, X86::MOV64rm,
10969 X86::NOT64r, X86::RAX,
10970 X86::GR64RegisterClass, true);
10971 case X86::ATOMMIN64:
10972 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10973 case X86::ATOMMAX64:
10974 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10975 case X86::ATOMUMIN64:
10976 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10977 case X86::ATOMUMAX64:
10978 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10980 // This group does 64-bit operations on a 32-bit host.
10981 case X86::ATOMAND6432:
10982 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10983 X86::AND32rr, X86::AND32rr,
10984 X86::AND32ri, X86::AND32ri,
10986 case X86::ATOMOR6432:
10987 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10988 X86::OR32rr, X86::OR32rr,
10989 X86::OR32ri, X86::OR32ri,
10991 case X86::ATOMXOR6432:
10992 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10993 X86::XOR32rr, X86::XOR32rr,
10994 X86::XOR32ri, X86::XOR32ri,
10996 case X86::ATOMNAND6432:
10997 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10998 X86::AND32rr, X86::AND32rr,
10999 X86::AND32ri, X86::AND32ri,
11001 case X86::ATOMADD6432:
11002 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11003 X86::ADD32rr, X86::ADC32rr,
11004 X86::ADD32ri, X86::ADC32ri,
11006 case X86::ATOMSUB6432:
11007 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11008 X86::SUB32rr, X86::SBB32rr,
11009 X86::SUB32ri, X86::SBB32ri,
11011 case X86::ATOMSWAP6432:
11012 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11013 X86::MOV32rr, X86::MOV32rr,
11014 X86::MOV32ri, X86::MOV32ri,
11016 case X86::VASTART_SAVE_XMM_REGS:
11017 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
11019 case X86::VAARG_64:
11020 return EmitVAARG64WithCustomInserter(MI, BB);
11024 //===----------------------------------------------------------------------===//
11025 // X86 Optimization Hooks
11026 //===----------------------------------------------------------------------===//
11028 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
11032 const SelectionDAG &DAG,
11033 unsigned Depth) const {
11034 unsigned Opc = Op.getOpcode();
11035 assert((Opc >= ISD::BUILTIN_OP_END ||
11036 Opc == ISD::INTRINSIC_WO_CHAIN ||
11037 Opc == ISD::INTRINSIC_W_CHAIN ||
11038 Opc == ISD::INTRINSIC_VOID) &&
11039 "Should use MaskedValueIsZero if you don't know whether Op"
11040 " is a target node!");
11042 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
11056 // These nodes' second result is a boolean.
11057 if (Op.getResNo() == 0)
11060 case X86ISD::SETCC:
11061 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11062 Mask.getBitWidth() - 1);
11067 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11068 unsigned Depth) const {
11069 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11070 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11071 return Op.getValueType().getScalarType().getSizeInBits();
11077 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11078 /// node is a GlobalAddress + offset.
11079 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11080 const GlobalValue* &GA,
11081 int64_t &Offset) const {
11082 if (N->getOpcode() == X86ISD::Wrapper) {
11083 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11084 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11085 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11089 return TargetLowering::isGAPlusOffset(N, GA, Offset);
11092 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
11093 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
11094 /// if the load addresses are consecutive, non-overlapping, and in the right
11096 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11097 TargetLowering::DAGCombinerInfo &DCI) {
11098 DebugLoc dl = N->getDebugLoc();
11099 EVT VT = N->getValueType(0);
11101 if (VT.getSizeInBits() != 128)
11104 // Don't create instructions with illegal types after legalize types has run.
11105 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11106 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11109 SmallVector<SDValue, 16> Elts;
11110 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11111 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11113 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11116 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11117 /// generation and convert it from being a bunch of shuffles and extracts
11118 /// to a simple store and scalar loads to extract the elements.
11119 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11120 const TargetLowering &TLI) {
11121 SDValue InputVector = N->getOperand(0);
11123 // Only operate on vectors of 4 elements, where the alternative shuffling
11124 // gets to be more expensive.
11125 if (InputVector.getValueType() != MVT::v4i32)
11128 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11129 // single use which is a sign-extend or zero-extend, and all elements are
11131 SmallVector<SDNode *, 4> Uses;
11132 unsigned ExtractedElements = 0;
11133 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11134 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11135 if (UI.getUse().getResNo() != InputVector.getResNo())
11138 SDNode *Extract = *UI;
11139 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11142 if (Extract->getValueType(0) != MVT::i32)
11144 if (!Extract->hasOneUse())
11146 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11147 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11149 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11152 // Record which element was extracted.
11153 ExtractedElements |=
11154 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11156 Uses.push_back(Extract);
11159 // If not all the elements were used, this may not be worthwhile.
11160 if (ExtractedElements != 15)
11163 // Ok, we've now decided to do the transformation.
11164 DebugLoc dl = InputVector.getDebugLoc();
11166 // Store the value to a temporary stack slot.
11167 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11168 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11169 MachinePointerInfo(), false, false, 0);
11171 // Replace each use (extract) with a load of the appropriate element.
11172 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11173 UE = Uses.end(); UI != UE; ++UI) {
11174 SDNode *Extract = *UI;
11176 // cOMpute the element's address.
11177 SDValue Idx = Extract->getOperand(1);
11179 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11180 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11181 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11183 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11184 StackPtr, OffsetVal);
11186 // Load the scalar.
11187 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11188 ScalarAddr, MachinePointerInfo(),
11191 // Replace the exact with the load.
11192 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11195 // The replacement was made in place; don't return anything.
11199 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11200 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11201 const X86Subtarget *Subtarget) {
11202 DebugLoc DL = N->getDebugLoc();
11203 SDValue Cond = N->getOperand(0);
11204 // Get the LHS/RHS of the select.
11205 SDValue LHS = N->getOperand(1);
11206 SDValue RHS = N->getOperand(2);
11208 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11209 // instructions match the semantics of the common C idiom x<y?x:y but not
11210 // x<=y?x:y, because of how they handle negative zero (which can be
11211 // ignored in unsafe-math mode).
11212 if (Subtarget->hasSSE2() &&
11213 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11214 Cond.getOpcode() == ISD::SETCC) {
11215 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11217 unsigned Opcode = 0;
11218 // Check for x CC y ? x : y.
11219 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11220 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11224 // Converting this to a min would handle NaNs incorrectly, and swapping
11225 // the operands would cause it to handle comparisons between positive
11226 // and negative zero incorrectly.
11227 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11228 if (!UnsafeFPMath &&
11229 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11231 std::swap(LHS, RHS);
11233 Opcode = X86ISD::FMIN;
11236 // Converting this to a min would handle comparisons between positive
11237 // and negative zero incorrectly.
11238 if (!UnsafeFPMath &&
11239 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11241 Opcode = X86ISD::FMIN;
11244 // Converting this to a min would handle both negative zeros and NaNs
11245 // incorrectly, but we can swap the operands to fix both.
11246 std::swap(LHS, RHS);
11250 Opcode = X86ISD::FMIN;
11254 // Converting this to a max would handle comparisons between positive
11255 // and negative zero incorrectly.
11256 if (!UnsafeFPMath &&
11257 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11259 Opcode = X86ISD::FMAX;
11262 // Converting this to a max would handle NaNs incorrectly, and swapping
11263 // the operands would cause it to handle comparisons between positive
11264 // and negative zero incorrectly.
11265 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11266 if (!UnsafeFPMath &&
11267 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11269 std::swap(LHS, RHS);
11271 Opcode = X86ISD::FMAX;
11274 // Converting this to a max would handle both negative zeros and NaNs
11275 // incorrectly, but we can swap the operands to fix both.
11276 std::swap(LHS, RHS);
11280 Opcode = X86ISD::FMAX;
11283 // Check for x CC y ? y : x -- a min/max with reversed arms.
11284 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11285 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11289 // Converting this to a min would handle comparisons between positive
11290 // and negative zero incorrectly, and swapping the operands would
11291 // cause it to handle NaNs incorrectly.
11292 if (!UnsafeFPMath &&
11293 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11294 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11296 std::swap(LHS, RHS);
11298 Opcode = X86ISD::FMIN;
11301 // Converting this to a min would handle NaNs incorrectly.
11302 if (!UnsafeFPMath &&
11303 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11305 Opcode = X86ISD::FMIN;
11308 // Converting this to a min would handle both negative zeros and NaNs
11309 // incorrectly, but we can swap the operands to fix both.
11310 std::swap(LHS, RHS);
11314 Opcode = X86ISD::FMIN;
11318 // Converting this to a max would handle NaNs incorrectly.
11319 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11321 Opcode = X86ISD::FMAX;
11324 // Converting this to a max would handle comparisons between positive
11325 // and negative zero incorrectly, and swapping the operands would
11326 // cause it to handle NaNs incorrectly.
11327 if (!UnsafeFPMath &&
11328 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11329 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11331 std::swap(LHS, RHS);
11333 Opcode = X86ISD::FMAX;
11336 // Converting this to a max would handle both negative zeros and NaNs
11337 // incorrectly, but we can swap the operands to fix both.
11338 std::swap(LHS, RHS);
11342 Opcode = X86ISD::FMAX;
11348 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11351 // If this is a select between two integer constants, try to do some
11353 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11354 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11355 // Don't do this for crazy integer types.
11356 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11357 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11358 // so that TrueC (the true value) is larger than FalseC.
11359 bool NeedsCondInvert = false;
11361 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11362 // Efficiently invertible.
11363 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
11364 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
11365 isa<ConstantSDNode>(Cond.getOperand(1))))) {
11366 NeedsCondInvert = true;
11367 std::swap(TrueC, FalseC);
11370 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
11371 if (FalseC->getAPIntValue() == 0 &&
11372 TrueC->getAPIntValue().isPowerOf2()) {
11373 if (NeedsCondInvert) // Invert the condition if needed.
11374 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11375 DAG.getConstant(1, Cond.getValueType()));
11377 // Zero extend the condition if needed.
11378 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11380 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11381 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11382 DAG.getConstant(ShAmt, MVT::i8));
11385 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11386 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11387 if (NeedsCondInvert) // Invert the condition if needed.
11388 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11389 DAG.getConstant(1, Cond.getValueType()));
11391 // Zero extend the condition if needed.
11392 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11393 FalseC->getValueType(0), Cond);
11394 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11395 SDValue(FalseC, 0));
11398 // Optimize cases that will turn into an LEA instruction. This requires
11399 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11400 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11401 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11402 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11404 bool isFastMultiplier = false;
11406 switch ((unsigned char)Diff) {
11408 case 1: // result = add base, cond
11409 case 2: // result = lea base( , cond*2)
11410 case 3: // result = lea base(cond, cond*2)
11411 case 4: // result = lea base( , cond*4)
11412 case 5: // result = lea base(cond, cond*4)
11413 case 8: // result = lea base( , cond*8)
11414 case 9: // result = lea base(cond, cond*8)
11415 isFastMultiplier = true;
11420 if (isFastMultiplier) {
11421 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11422 if (NeedsCondInvert) // Invert the condition if needed.
11423 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11424 DAG.getConstant(1, Cond.getValueType()));
11426 // Zero extend the condition if needed.
11427 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11429 // Scale the condition by the difference.
11431 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11432 DAG.getConstant(Diff, Cond.getValueType()));
11434 // Add the base if non-zero.
11435 if (FalseC->getAPIntValue() != 0)
11436 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11437 SDValue(FalseC, 0));
11447 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11448 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11449 TargetLowering::DAGCombinerInfo &DCI) {
11450 DebugLoc DL = N->getDebugLoc();
11452 // If the flag operand isn't dead, don't touch this CMOV.
11453 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11456 SDValue FalseOp = N->getOperand(0);
11457 SDValue TrueOp = N->getOperand(1);
11458 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11459 SDValue Cond = N->getOperand(3);
11460 if (CC == X86::COND_E || CC == X86::COND_NE) {
11461 switch (Cond.getOpcode()) {
11465 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11466 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11467 return (CC == X86::COND_E) ? FalseOp : TrueOp;
11471 // If this is a select between two integer constants, try to do some
11472 // optimizations. Note that the operands are ordered the opposite of SELECT
11474 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11475 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11476 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11477 // larger than FalseC (the false value).
11478 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11479 CC = X86::GetOppositeBranchCondition(CC);
11480 std::swap(TrueC, FalseC);
11483 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
11484 // This is efficient for any integer data type (including i8/i16) and
11486 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11487 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11488 DAG.getConstant(CC, MVT::i8), Cond);
11490 // Zero extend the condition if needed.
11491 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11493 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11494 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11495 DAG.getConstant(ShAmt, MVT::i8));
11496 if (N->getNumValues() == 2) // Dead flag value?
11497 return DCI.CombineTo(N, Cond, SDValue());
11501 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
11502 // for any integer data type, including i8/i16.
11503 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11504 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11505 DAG.getConstant(CC, MVT::i8), Cond);
11507 // Zero extend the condition if needed.
11508 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11509 FalseC->getValueType(0), Cond);
11510 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11511 SDValue(FalseC, 0));
11513 if (N->getNumValues() == 2) // Dead flag value?
11514 return DCI.CombineTo(N, Cond, SDValue());
11518 // Optimize cases that will turn into an LEA instruction. This requires
11519 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11520 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11521 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11522 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11524 bool isFastMultiplier = false;
11526 switch ((unsigned char)Diff) {
11528 case 1: // result = add base, cond
11529 case 2: // result = lea base( , cond*2)
11530 case 3: // result = lea base(cond, cond*2)
11531 case 4: // result = lea base( , cond*4)
11532 case 5: // result = lea base(cond, cond*4)
11533 case 8: // result = lea base( , cond*8)
11534 case 9: // result = lea base(cond, cond*8)
11535 isFastMultiplier = true;
11540 if (isFastMultiplier) {
11541 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11542 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11543 DAG.getConstant(CC, MVT::i8), Cond);
11544 // Zero extend the condition if needed.
11545 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11547 // Scale the condition by the difference.
11549 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11550 DAG.getConstant(Diff, Cond.getValueType()));
11552 // Add the base if non-zero.
11553 if (FalseC->getAPIntValue() != 0)
11554 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11555 SDValue(FalseC, 0));
11556 if (N->getNumValues() == 2) // Dead flag value?
11557 return DCI.CombineTo(N, Cond, SDValue());
11567 /// PerformMulCombine - Optimize a single multiply with constant into two
11568 /// in order to implement it with two cheaper instructions, e.g.
11569 /// LEA + SHL, LEA + LEA.
11570 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11571 TargetLowering::DAGCombinerInfo &DCI) {
11572 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11575 EVT VT = N->getValueType(0);
11576 if (VT != MVT::i64)
11579 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11582 uint64_t MulAmt = C->getZExtValue();
11583 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11586 uint64_t MulAmt1 = 0;
11587 uint64_t MulAmt2 = 0;
11588 if ((MulAmt % 9) == 0) {
11590 MulAmt2 = MulAmt / 9;
11591 } else if ((MulAmt % 5) == 0) {
11593 MulAmt2 = MulAmt / 5;
11594 } else if ((MulAmt % 3) == 0) {
11596 MulAmt2 = MulAmt / 3;
11599 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11600 DebugLoc DL = N->getDebugLoc();
11602 if (isPowerOf2_64(MulAmt2) &&
11603 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11604 // If second multiplifer is pow2, issue it first. We want the multiply by
11605 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11607 std::swap(MulAmt1, MulAmt2);
11610 if (isPowerOf2_64(MulAmt1))
11611 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11612 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11614 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11615 DAG.getConstant(MulAmt1, VT));
11617 if (isPowerOf2_64(MulAmt2))
11618 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11619 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11621 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11622 DAG.getConstant(MulAmt2, VT));
11624 // Do not add new nodes to DAG combiner worklist.
11625 DCI.CombineTo(N, NewMul, false);
11630 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11631 SDValue N0 = N->getOperand(0);
11632 SDValue N1 = N->getOperand(1);
11633 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11634 EVT VT = N0.getValueType();
11636 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11637 // since the result of setcc_c is all zero's or all ones.
11638 if (N1C && N0.getOpcode() == ISD::AND &&
11639 N0.getOperand(1).getOpcode() == ISD::Constant) {
11640 SDValue N00 = N0.getOperand(0);
11641 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11642 ((N00.getOpcode() == ISD::ANY_EXTEND ||
11643 N00.getOpcode() == ISD::ZERO_EXTEND) &&
11644 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11645 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11646 APInt ShAmt = N1C->getAPIntValue();
11647 Mask = Mask.shl(ShAmt);
11649 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11650 N00, DAG.getConstant(Mask, VT));
11657 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11659 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11660 const X86Subtarget *Subtarget) {
11661 EVT VT = N->getValueType(0);
11662 if (!VT.isVector() && VT.isInteger() &&
11663 N->getOpcode() == ISD::SHL)
11664 return PerformSHLCombine(N, DAG);
11666 // On X86 with SSE2 support, we can transform this to a vector shift if
11667 // all elements are shifted by the same amount. We can't do this in legalize
11668 // because the a constant vector is typically transformed to a constant pool
11669 // so we have no knowledge of the shift amount.
11670 if (!Subtarget->hasSSE2())
11673 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11676 SDValue ShAmtOp = N->getOperand(1);
11677 EVT EltVT = VT.getVectorElementType();
11678 DebugLoc DL = N->getDebugLoc();
11679 SDValue BaseShAmt = SDValue();
11680 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11681 unsigned NumElts = VT.getVectorNumElements();
11683 for (; i != NumElts; ++i) {
11684 SDValue Arg = ShAmtOp.getOperand(i);
11685 if (Arg.getOpcode() == ISD::UNDEF) continue;
11689 for (; i != NumElts; ++i) {
11690 SDValue Arg = ShAmtOp.getOperand(i);
11691 if (Arg.getOpcode() == ISD::UNDEF) continue;
11692 if (Arg != BaseShAmt) {
11696 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11697 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11698 SDValue InVec = ShAmtOp.getOperand(0);
11699 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11700 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11702 for (; i != NumElts; ++i) {
11703 SDValue Arg = InVec.getOperand(i);
11704 if (Arg.getOpcode() == ISD::UNDEF) continue;
11708 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11709 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11710 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11711 if (C->getZExtValue() == SplatIdx)
11712 BaseShAmt = InVec.getOperand(1);
11715 if (BaseShAmt.getNode() == 0)
11716 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11717 DAG.getIntPtrConstant(0));
11721 // The shift amount is an i32.
11722 if (EltVT.bitsGT(MVT::i32))
11723 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11724 else if (EltVT.bitsLT(MVT::i32))
11725 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11727 // The shift amount is identical so we can do a vector shift.
11728 SDValue ValOp = N->getOperand(0);
11729 switch (N->getOpcode()) {
11731 llvm_unreachable("Unknown shift opcode!");
11734 if (VT == MVT::v2i64)
11735 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11736 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11738 if (VT == MVT::v4i32)
11739 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11740 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11742 if (VT == MVT::v8i16)
11743 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11744 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11748 if (VT == MVT::v4i32)
11749 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11750 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11752 if (VT == MVT::v8i16)
11753 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11754 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11758 if (VT == MVT::v2i64)
11759 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11760 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11762 if (VT == MVT::v4i32)
11763 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11764 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11766 if (VT == MVT::v8i16)
11767 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11768 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11776 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
11777 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
11778 // and friends. Likewise for OR -> CMPNEQSS.
11779 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
11780 TargetLowering::DAGCombinerInfo &DCI,
11781 const X86Subtarget *Subtarget) {
11784 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
11785 // we're requiring SSE2 for both.
11786 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
11787 SDValue N0 = N->getOperand(0);
11788 SDValue N1 = N->getOperand(1);
11789 SDValue CMP0 = N0->getOperand(1);
11790 SDValue CMP1 = N1->getOperand(1);
11791 DebugLoc DL = N->getDebugLoc();
11793 // The SETCCs should both refer to the same CMP.
11794 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
11797 SDValue CMP00 = CMP0->getOperand(0);
11798 SDValue CMP01 = CMP0->getOperand(1);
11799 EVT VT = CMP00.getValueType();
11801 if (VT == MVT::f32 || VT == MVT::f64) {
11802 bool ExpectingFlags = false;
11803 // Check for any users that want flags:
11804 for (SDNode::use_iterator UI = N->use_begin(),
11806 !ExpectingFlags && UI != UE; ++UI)
11807 switch (UI->getOpcode()) {
11812 ExpectingFlags = true;
11814 case ISD::CopyToReg:
11815 case ISD::SIGN_EXTEND:
11816 case ISD::ZERO_EXTEND:
11817 case ISD::ANY_EXTEND:
11821 if (!ExpectingFlags) {
11822 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
11823 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
11825 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
11826 X86::CondCode tmp = cc0;
11831 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
11832 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
11833 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
11834 X86ISD::NodeType NTOperator = is64BitFP ?
11835 X86ISD::FSETCCsd : X86ISD::FSETCCss;
11836 // FIXME: need symbolic constants for these magic numbers.
11837 // See X86ATTInstPrinter.cpp:printSSECC().
11838 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
11839 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
11840 DAG.getConstant(x86cc, MVT::i8));
11841 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
11843 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
11844 DAG.getConstant(1, MVT::i32));
11845 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
11846 return OneBitOfTruth;
11854 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11855 TargetLowering::DAGCombinerInfo &DCI,
11856 const X86Subtarget *Subtarget) {
11857 if (DCI.isBeforeLegalizeOps())
11860 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11864 // Want to form ANDNP nodes:
11865 // 1) In the hopes of then easily combining them with OR and AND nodes
11866 // to form PBLEND/PSIGN.
11867 // 2) To match ANDN packed intrinsics
11868 EVT VT = N->getValueType(0);
11869 if (VT != MVT::v2i64 && VT != MVT::v4i64)
11872 SDValue N0 = N->getOperand(0);
11873 SDValue N1 = N->getOperand(1);
11874 DebugLoc DL = N->getDebugLoc();
11876 // Check LHS for vnot
11877 if (N0.getOpcode() == ISD::XOR &&
11878 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11879 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
11881 // Check RHS for vnot
11882 if (N1.getOpcode() == ISD::XOR &&
11883 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11884 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
11889 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11890 TargetLowering::DAGCombinerInfo &DCI,
11891 const X86Subtarget *Subtarget) {
11892 if (DCI.isBeforeLegalizeOps())
11895 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11899 EVT VT = N->getValueType(0);
11900 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11903 SDValue N0 = N->getOperand(0);
11904 SDValue N1 = N->getOperand(1);
11906 // look for psign/blend
11907 if (Subtarget->hasSSSE3()) {
11908 if (VT == MVT::v2i64) {
11909 // Canonicalize pandn to RHS
11910 if (N0.getOpcode() == X86ISD::ANDNP)
11912 // or (and (m, x), (pandn m, y))
11913 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
11914 SDValue Mask = N1.getOperand(0);
11915 SDValue X = N1.getOperand(1);
11917 if (N0.getOperand(0) == Mask)
11918 Y = N0.getOperand(1);
11919 if (N0.getOperand(1) == Mask)
11920 Y = N0.getOperand(0);
11922 // Check to see if the mask appeared in both the AND and ANDNP and
11926 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11927 if (Mask.getOpcode() != ISD::BITCAST ||
11928 X.getOpcode() != ISD::BITCAST ||
11929 Y.getOpcode() != ISD::BITCAST)
11932 // Look through mask bitcast.
11933 Mask = Mask.getOperand(0);
11934 EVT MaskVT = Mask.getValueType();
11936 // Validate that the Mask operand is a vector sra node. The sra node
11937 // will be an intrinsic.
11938 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11941 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11942 // there is no psrai.b
11943 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11944 case Intrinsic::x86_sse2_psrai_w:
11945 case Intrinsic::x86_sse2_psrai_d:
11947 default: return SDValue();
11950 // Check that the SRA is all signbits.
11951 SDValue SraC = Mask.getOperand(2);
11952 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
11953 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11954 if ((SraAmt + 1) != EltBits)
11957 DebugLoc DL = N->getDebugLoc();
11959 // Now we know we at least have a plendvb with the mask val. See if
11960 // we can form a psignb/w/d.
11961 // psign = x.type == y.type == mask.type && y = sub(0, x);
11962 X = X.getOperand(0);
11963 Y = Y.getOperand(0);
11964 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11965 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11966 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11969 case 8: Opc = X86ISD::PSIGNB; break;
11970 case 16: Opc = X86ISD::PSIGNW; break;
11971 case 32: Opc = X86ISD::PSIGND; break;
11975 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11976 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11979 // PBLENDVB only available on SSE 4.1
11980 if (!Subtarget->hasSSE41())
11983 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11984 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11985 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11986 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11987 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11992 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11993 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11995 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11997 if (!N0.hasOneUse() || !N1.hasOneUse())
12000 SDValue ShAmt0 = N0.getOperand(1);
12001 if (ShAmt0.getValueType() != MVT::i8)
12003 SDValue ShAmt1 = N1.getOperand(1);
12004 if (ShAmt1.getValueType() != MVT::i8)
12006 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
12007 ShAmt0 = ShAmt0.getOperand(0);
12008 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
12009 ShAmt1 = ShAmt1.getOperand(0);
12011 DebugLoc DL = N->getDebugLoc();
12012 unsigned Opc = X86ISD::SHLD;
12013 SDValue Op0 = N0.getOperand(0);
12014 SDValue Op1 = N1.getOperand(0);
12015 if (ShAmt0.getOpcode() == ISD::SUB) {
12016 Opc = X86ISD::SHRD;
12017 std::swap(Op0, Op1);
12018 std::swap(ShAmt0, ShAmt1);
12021 unsigned Bits = VT.getSizeInBits();
12022 if (ShAmt1.getOpcode() == ISD::SUB) {
12023 SDValue Sum = ShAmt1.getOperand(0);
12024 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
12025 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
12026 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
12027 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
12028 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
12029 return DAG.getNode(Opc, DL, VT,
12031 DAG.getNode(ISD::TRUNCATE, DL,
12034 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
12035 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
12037 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
12038 return DAG.getNode(Opc, DL, VT,
12039 N0.getOperand(0), N1.getOperand(0),
12040 DAG.getNode(ISD::TRUNCATE, DL,
12047 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
12048 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
12049 const X86Subtarget *Subtarget) {
12050 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
12051 // the FP state in cases where an emms may be missing.
12052 // A preferable solution to the general problem is to figure out the right
12053 // places to insert EMMS. This qualifies as a quick hack.
12055 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
12056 StoreSDNode *St = cast<StoreSDNode>(N);
12057 EVT VT = St->getValue().getValueType();
12058 if (VT.getSizeInBits() != 64)
12061 const Function *F = DAG.getMachineFunction().getFunction();
12062 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
12063 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
12064 && Subtarget->hasSSE2();
12065 if ((VT.isVector() ||
12066 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
12067 isa<LoadSDNode>(St->getValue()) &&
12068 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
12069 St->getChain().hasOneUse() && !St->isVolatile()) {
12070 SDNode* LdVal = St->getValue().getNode();
12071 LoadSDNode *Ld = 0;
12072 int TokenFactorIndex = -1;
12073 SmallVector<SDValue, 8> Ops;
12074 SDNode* ChainVal = St->getChain().getNode();
12075 // Must be a store of a load. We currently handle two cases: the load
12076 // is a direct child, and it's under an intervening TokenFactor. It is
12077 // possible to dig deeper under nested TokenFactors.
12078 if (ChainVal == LdVal)
12079 Ld = cast<LoadSDNode>(St->getChain());
12080 else if (St->getValue().hasOneUse() &&
12081 ChainVal->getOpcode() == ISD::TokenFactor) {
12082 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
12083 if (ChainVal->getOperand(i).getNode() == LdVal) {
12084 TokenFactorIndex = i;
12085 Ld = cast<LoadSDNode>(St->getValue());
12087 Ops.push_back(ChainVal->getOperand(i));
12091 if (!Ld || !ISD::isNormalLoad(Ld))
12094 // If this is not the MMX case, i.e. we are just turning i64 load/store
12095 // into f64 load/store, avoid the transformation if there are multiple
12096 // uses of the loaded value.
12097 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
12100 DebugLoc LdDL = Ld->getDebugLoc();
12101 DebugLoc StDL = N->getDebugLoc();
12102 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
12103 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
12105 if (Subtarget->is64Bit() || F64IsLegal) {
12106 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
12107 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
12108 Ld->getPointerInfo(), Ld->isVolatile(),
12109 Ld->isNonTemporal(), Ld->getAlignment());
12110 SDValue NewChain = NewLd.getValue(1);
12111 if (TokenFactorIndex != -1) {
12112 Ops.push_back(NewChain);
12113 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12116 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
12117 St->getPointerInfo(),
12118 St->isVolatile(), St->isNonTemporal(),
12119 St->getAlignment());
12122 // Otherwise, lower to two pairs of 32-bit loads / stores.
12123 SDValue LoAddr = Ld->getBasePtr();
12124 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
12125 DAG.getConstant(4, MVT::i32));
12127 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
12128 Ld->getPointerInfo(),
12129 Ld->isVolatile(), Ld->isNonTemporal(),
12130 Ld->getAlignment());
12131 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
12132 Ld->getPointerInfo().getWithOffset(4),
12133 Ld->isVolatile(), Ld->isNonTemporal(),
12134 MinAlign(Ld->getAlignment(), 4));
12136 SDValue NewChain = LoLd.getValue(1);
12137 if (TokenFactorIndex != -1) {
12138 Ops.push_back(LoLd);
12139 Ops.push_back(HiLd);
12140 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12144 LoAddr = St->getBasePtr();
12145 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
12146 DAG.getConstant(4, MVT::i32));
12148 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
12149 St->getPointerInfo(),
12150 St->isVolatile(), St->isNonTemporal(),
12151 St->getAlignment());
12152 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12153 St->getPointerInfo().getWithOffset(4),
12155 St->isNonTemporal(),
12156 MinAlign(St->getAlignment(), 4));
12157 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12162 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12163 /// X86ISD::FXOR nodes.
12164 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12165 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12166 // F[X]OR(0.0, x) -> x
12167 // F[X]OR(x, 0.0) -> x
12168 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12169 if (C->getValueAPF().isPosZero())
12170 return N->getOperand(1);
12171 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12172 if (C->getValueAPF().isPosZero())
12173 return N->getOperand(0);
12177 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12178 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12179 // FAND(0.0, x) -> 0.0
12180 // FAND(x, 0.0) -> 0.0
12181 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12182 if (C->getValueAPF().isPosZero())
12183 return N->getOperand(0);
12184 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12185 if (C->getValueAPF().isPosZero())
12186 return N->getOperand(1);
12190 static SDValue PerformBTCombine(SDNode *N,
12192 TargetLowering::DAGCombinerInfo &DCI) {
12193 // BT ignores high bits in the bit index operand.
12194 SDValue Op1 = N->getOperand(1);
12195 if (Op1.hasOneUse()) {
12196 unsigned BitWidth = Op1.getValueSizeInBits();
12197 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12198 APInt KnownZero, KnownOne;
12199 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12200 !DCI.isBeforeLegalizeOps());
12201 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12202 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12203 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12204 DCI.CommitTargetLoweringOpt(TLO);
12209 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12210 SDValue Op = N->getOperand(0);
12211 if (Op.getOpcode() == ISD::BITCAST)
12212 Op = Op.getOperand(0);
12213 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12214 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12215 VT.getVectorElementType().getSizeInBits() ==
12216 OpVT.getVectorElementType().getSizeInBits()) {
12217 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12222 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12223 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
12224 // (and (i32 x86isd::setcc_carry), 1)
12225 // This eliminates the zext. This transformation is necessary because
12226 // ISD::SETCC is always legalized to i8.
12227 DebugLoc dl = N->getDebugLoc();
12228 SDValue N0 = N->getOperand(0);
12229 EVT VT = N->getValueType(0);
12230 if (N0.getOpcode() == ISD::AND &&
12232 N0.getOperand(0).hasOneUse()) {
12233 SDValue N00 = N0.getOperand(0);
12234 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12236 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12237 if (!C || C->getZExtValue() != 1)
12239 return DAG.getNode(ISD::AND, dl, VT,
12240 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12241 N00.getOperand(0), N00.getOperand(1)),
12242 DAG.getConstant(1, VT));
12248 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12249 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12250 unsigned X86CC = N->getConstantOperandVal(0);
12251 SDValue EFLAG = N->getOperand(1);
12252 DebugLoc DL = N->getDebugLoc();
12254 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12255 // a zext and produces an all-ones bit which is more useful than 0/1 in some
12257 if (X86CC == X86::COND_B)
12258 return DAG.getNode(ISD::AND, DL, MVT::i8,
12259 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12260 DAG.getConstant(X86CC, MVT::i8), EFLAG),
12261 DAG.getConstant(1, MVT::i8));
12266 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
12267 const X86TargetLowering *XTLI) {
12268 SDValue Op0 = N->getOperand(0);
12269 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
12270 // a 32-bit target where SSE doesn't support i64->FP operations.
12271 if (Op0.getOpcode() == ISD::LOAD) {
12272 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
12273 EVT VT = Ld->getValueType(0);
12274 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
12275 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
12276 !XTLI->getSubtarget()->is64Bit() &&
12277 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12278 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
12279 Ld->getChain(), Op0, DAG);
12280 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
12287 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12288 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12289 X86TargetLowering::DAGCombinerInfo &DCI) {
12290 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12291 // the result is either zero or one (depending on the input carry bit).
12292 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12293 if (X86::isZeroNode(N->getOperand(0)) &&
12294 X86::isZeroNode(N->getOperand(1)) &&
12295 // We don't have a good way to replace an EFLAGS use, so only do this when
12297 SDValue(N, 1).use_empty()) {
12298 DebugLoc DL = N->getDebugLoc();
12299 EVT VT = N->getValueType(0);
12300 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12301 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12302 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12303 DAG.getConstant(X86::COND_B,MVT::i8),
12305 DAG.getConstant(1, VT));
12306 return DCI.CombineTo(N, Res1, CarryOut);
12312 // fold (add Y, (sete X, 0)) -> adc 0, Y
12313 // (add Y, (setne X, 0)) -> sbb -1, Y
12314 // (sub (sete X, 0), Y) -> sbb 0, Y
12315 // (sub (setne X, 0), Y) -> adc -1, Y
12316 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12317 DebugLoc DL = N->getDebugLoc();
12319 // Look through ZExts.
12320 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12321 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12324 SDValue SetCC = Ext.getOperand(0);
12325 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12328 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12329 if (CC != X86::COND_E && CC != X86::COND_NE)
12332 SDValue Cmp = SetCC.getOperand(1);
12333 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12334 !X86::isZeroNode(Cmp.getOperand(1)) ||
12335 !Cmp.getOperand(0).getValueType().isInteger())
12338 SDValue CmpOp0 = Cmp.getOperand(0);
12339 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12340 DAG.getConstant(1, CmpOp0.getValueType()));
12342 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12343 if (CC == X86::COND_NE)
12344 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12345 DL, OtherVal.getValueType(), OtherVal,
12346 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12347 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12348 DL, OtherVal.getValueType(), OtherVal,
12349 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12352 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12353 DAGCombinerInfo &DCI) const {
12354 SelectionDAG &DAG = DCI.DAG;
12355 switch (N->getOpcode()) {
12357 case ISD::EXTRACT_VECTOR_ELT:
12358 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12359 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
12360 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
12362 case ISD::SUB: return OptimizeConditonalInDecrement(N, DAG);
12363 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
12364 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
12367 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
12368 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
12369 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
12370 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
12371 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
12373 case X86ISD::FOR: return PerformFORCombine(N, DAG);
12374 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
12375 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
12376 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
12377 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
12378 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
12379 case X86ISD::SHUFPS: // Handle all target specific shuffles
12380 case X86ISD::SHUFPD:
12381 case X86ISD::PALIGN:
12382 case X86ISD::PUNPCKHBW:
12383 case X86ISD::PUNPCKHWD:
12384 case X86ISD::PUNPCKHDQ:
12385 case X86ISD::PUNPCKHQDQ:
12386 case X86ISD::UNPCKHPS:
12387 case X86ISD::UNPCKHPD:
12388 case X86ISD::PUNPCKLBW:
12389 case X86ISD::PUNPCKLWD:
12390 case X86ISD::PUNPCKLDQ:
12391 case X86ISD::PUNPCKLQDQ:
12392 case X86ISD::UNPCKLPS:
12393 case X86ISD::UNPCKLPD:
12394 case X86ISD::VUNPCKLPS:
12395 case X86ISD::VUNPCKLPD:
12396 case X86ISD::VUNPCKLPSY:
12397 case X86ISD::VUNPCKLPDY:
12398 case X86ISD::MOVHLPS:
12399 case X86ISD::MOVLHPS:
12400 case X86ISD::PSHUFD:
12401 case X86ISD::PSHUFHW:
12402 case X86ISD::PSHUFLW:
12403 case X86ISD::MOVSS:
12404 case X86ISD::MOVSD:
12405 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12411 /// isTypeDesirableForOp - Return true if the target has native support for
12412 /// the specified value type and it is 'desirable' to use the type for the
12413 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12414 /// instruction encodings are longer and some i16 instructions are slow.
12415 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12416 if (!isTypeLegal(VT))
12418 if (VT != MVT::i16)
12425 case ISD::SIGN_EXTEND:
12426 case ISD::ZERO_EXTEND:
12427 case ISD::ANY_EXTEND:
12440 /// IsDesirableToPromoteOp - This method query the target whether it is
12441 /// beneficial for dag combiner to promote the specified node. If true, it
12442 /// should return the desired promotion type by reference.
12443 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12444 EVT VT = Op.getValueType();
12445 if (VT != MVT::i16)
12448 bool Promote = false;
12449 bool Commute = false;
12450 switch (Op.getOpcode()) {
12453 LoadSDNode *LD = cast<LoadSDNode>(Op);
12454 // If the non-extending load has a single use and it's not live out, then it
12455 // might be folded.
12456 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12457 Op.hasOneUse()*/) {
12458 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12459 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12460 // The only case where we'd want to promote LOAD (rather then it being
12461 // promoted as an operand is when it's only use is liveout.
12462 if (UI->getOpcode() != ISD::CopyToReg)
12469 case ISD::SIGN_EXTEND:
12470 case ISD::ZERO_EXTEND:
12471 case ISD::ANY_EXTEND:
12476 SDValue N0 = Op.getOperand(0);
12477 // Look out for (store (shl (load), x)).
12478 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12491 SDValue N0 = Op.getOperand(0);
12492 SDValue N1 = Op.getOperand(1);
12493 if (!Commute && MayFoldLoad(N1))
12495 // Avoid disabling potential load folding opportunities.
12496 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12498 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12508 //===----------------------------------------------------------------------===//
12509 // X86 Inline Assembly Support
12510 //===----------------------------------------------------------------------===//
12512 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12513 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12515 std::string AsmStr = IA->getAsmString();
12517 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12518 SmallVector<StringRef, 4> AsmPieces;
12519 SplitString(AsmStr, AsmPieces, ";\n");
12521 switch (AsmPieces.size()) {
12522 default: return false;
12524 AsmStr = AsmPieces[0];
12526 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
12528 // FIXME: this should verify that we are targeting a 486 or better. If not,
12529 // we will turn this bswap into something that will be lowered to logical ops
12530 // instead of emitting the bswap asm. For now, we don't support 486 or lower
12531 // so don't worry about this.
12533 if (AsmPieces.size() == 2 &&
12534 (AsmPieces[0] == "bswap" ||
12535 AsmPieces[0] == "bswapq" ||
12536 AsmPieces[0] == "bswapl") &&
12537 (AsmPieces[1] == "$0" ||
12538 AsmPieces[1] == "${0:q}")) {
12539 // No need to check constraints, nothing other than the equivalent of
12540 // "=r,0" would be valid here.
12541 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12542 if (!Ty || Ty->getBitWidth() % 16 != 0)
12544 return IntrinsicLowering::LowerToByteSwap(CI);
12546 // rorw $$8, ${0:w} --> llvm.bswap.i16
12547 if (CI->getType()->isIntegerTy(16) &&
12548 AsmPieces.size() == 3 &&
12549 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12550 AsmPieces[1] == "$$8," &&
12551 AsmPieces[2] == "${0:w}" &&
12552 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12554 const std::string &ConstraintsStr = IA->getConstraintString();
12555 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12556 std::sort(AsmPieces.begin(), AsmPieces.end());
12557 if (AsmPieces.size() == 4 &&
12558 AsmPieces[0] == "~{cc}" &&
12559 AsmPieces[1] == "~{dirflag}" &&
12560 AsmPieces[2] == "~{flags}" &&
12561 AsmPieces[3] == "~{fpsr}") {
12562 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12563 if (!Ty || Ty->getBitWidth() % 16 != 0)
12565 return IntrinsicLowering::LowerToByteSwap(CI);
12570 if (CI->getType()->isIntegerTy(32) &&
12571 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12572 SmallVector<StringRef, 4> Words;
12573 SplitString(AsmPieces[0], Words, " \t,");
12574 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12575 Words[2] == "${0:w}") {
12577 SplitString(AsmPieces[1], Words, " \t,");
12578 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12579 Words[2] == "$0") {
12581 SplitString(AsmPieces[2], Words, " \t,");
12582 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12583 Words[2] == "${0:w}") {
12585 const std::string &ConstraintsStr = IA->getConstraintString();
12586 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12587 std::sort(AsmPieces.begin(), AsmPieces.end());
12588 if (AsmPieces.size() == 4 &&
12589 AsmPieces[0] == "~{cc}" &&
12590 AsmPieces[1] == "~{dirflag}" &&
12591 AsmPieces[2] == "~{flags}" &&
12592 AsmPieces[3] == "~{fpsr}") {
12593 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12594 if (!Ty || Ty->getBitWidth() % 16 != 0)
12596 return IntrinsicLowering::LowerToByteSwap(CI);
12603 if (CI->getType()->isIntegerTy(64)) {
12604 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12605 if (Constraints.size() >= 2 &&
12606 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12607 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12608 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
12609 SmallVector<StringRef, 4> Words;
12610 SplitString(AsmPieces[0], Words, " \t");
12611 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12613 SplitString(AsmPieces[1], Words, " \t");
12614 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12616 SplitString(AsmPieces[2], Words, " \t,");
12617 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12618 Words[2] == "%edx") {
12619 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12620 if (!Ty || Ty->getBitWidth() % 16 != 0)
12622 return IntrinsicLowering::LowerToByteSwap(CI);
12635 /// getConstraintType - Given a constraint letter, return the type of
12636 /// constraint it is for this target.
12637 X86TargetLowering::ConstraintType
12638 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12639 if (Constraint.size() == 1) {
12640 switch (Constraint[0]) {
12651 return C_RegisterClass;
12675 return TargetLowering::getConstraintType(Constraint);
12678 /// Examine constraint type and operand type and determine a weight value.
12679 /// This object must already have been set up with the operand type
12680 /// and the current alternative constraint selected.
12681 TargetLowering::ConstraintWeight
12682 X86TargetLowering::getSingleConstraintMatchWeight(
12683 AsmOperandInfo &info, const char *constraint) const {
12684 ConstraintWeight weight = CW_Invalid;
12685 Value *CallOperandVal = info.CallOperandVal;
12686 // If we don't have a value, we can't do a match,
12687 // but allow it at the lowest weight.
12688 if (CallOperandVal == NULL)
12690 Type *type = CallOperandVal->getType();
12691 // Look at the constraint type.
12692 switch (*constraint) {
12694 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12705 if (CallOperandVal->getType()->isIntegerTy())
12706 weight = CW_SpecificReg;
12711 if (type->isFloatingPointTy())
12712 weight = CW_SpecificReg;
12715 if (type->isX86_MMXTy() && Subtarget->hasMMX())
12716 weight = CW_SpecificReg;
12720 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12721 weight = CW_Register;
12724 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12725 if (C->getZExtValue() <= 31)
12726 weight = CW_Constant;
12730 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12731 if (C->getZExtValue() <= 63)
12732 weight = CW_Constant;
12736 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12737 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12738 weight = CW_Constant;
12742 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12743 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12744 weight = CW_Constant;
12748 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12749 if (C->getZExtValue() <= 3)
12750 weight = CW_Constant;
12754 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12755 if (C->getZExtValue() <= 0xff)
12756 weight = CW_Constant;
12761 if (dyn_cast<ConstantFP>(CallOperandVal)) {
12762 weight = CW_Constant;
12766 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12767 if ((C->getSExtValue() >= -0x80000000LL) &&
12768 (C->getSExtValue() <= 0x7fffffffLL))
12769 weight = CW_Constant;
12773 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12774 if (C->getZExtValue() <= 0xffffffff)
12775 weight = CW_Constant;
12782 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12783 /// with another that has more specific requirements based on the type of the
12784 /// corresponding operand.
12785 const char *X86TargetLowering::
12786 LowerXConstraint(EVT ConstraintVT) const {
12787 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12788 // 'f' like normal targets.
12789 if (ConstraintVT.isFloatingPoint()) {
12790 if (Subtarget->hasXMMInt())
12792 if (Subtarget->hasXMM())
12796 return TargetLowering::LowerXConstraint(ConstraintVT);
12799 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12800 /// vector. If it is invalid, don't add anything to Ops.
12801 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12802 std::string &Constraint,
12803 std::vector<SDValue>&Ops,
12804 SelectionDAG &DAG) const {
12805 SDValue Result(0, 0);
12807 // Only support length 1 constraints for now.
12808 if (Constraint.length() > 1) return;
12810 char ConstraintLetter = Constraint[0];
12811 switch (ConstraintLetter) {
12814 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12815 if (C->getZExtValue() <= 31) {
12816 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12822 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12823 if (C->getZExtValue() <= 63) {
12824 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12830 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12831 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12832 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12838 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12839 if (C->getZExtValue() <= 255) {
12840 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12846 // 32-bit signed value
12847 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12848 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12849 C->getSExtValue())) {
12850 // Widen to 64 bits here to get it sign extended.
12851 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12854 // FIXME gcc accepts some relocatable values here too, but only in certain
12855 // memory models; it's complicated.
12860 // 32-bit unsigned value
12861 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12862 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12863 C->getZExtValue())) {
12864 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12868 // FIXME gcc accepts some relocatable values here too, but only in certain
12869 // memory models; it's complicated.
12873 // Literal immediates are always ok.
12874 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12875 // Widen to 64 bits here to get it sign extended.
12876 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12880 // In any sort of PIC mode addresses need to be computed at runtime by
12881 // adding in a register or some sort of table lookup. These can't
12882 // be used as immediates.
12883 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12886 // If we are in non-pic codegen mode, we allow the address of a global (with
12887 // an optional displacement) to be used with 'i'.
12888 GlobalAddressSDNode *GA = 0;
12889 int64_t Offset = 0;
12891 // Match either (GA), (GA+C), (GA+C1+C2), etc.
12893 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12894 Offset += GA->getOffset();
12896 } else if (Op.getOpcode() == ISD::ADD) {
12897 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12898 Offset += C->getZExtValue();
12899 Op = Op.getOperand(0);
12902 } else if (Op.getOpcode() == ISD::SUB) {
12903 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12904 Offset += -C->getZExtValue();
12905 Op = Op.getOperand(0);
12910 // Otherwise, this isn't something we can handle, reject it.
12914 const GlobalValue *GV = GA->getGlobal();
12915 // If we require an extra load to get this address, as in PIC mode, we
12916 // can't accept it.
12917 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12918 getTargetMachine())))
12921 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12922 GA->getValueType(0), Offset);
12927 if (Result.getNode()) {
12928 Ops.push_back(Result);
12931 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12934 std::pair<unsigned, const TargetRegisterClass*>
12935 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12937 // First, see if this is a constraint that directly corresponds to an LLVM
12939 if (Constraint.size() == 1) {
12940 // GCC Constraint Letters
12941 switch (Constraint[0]) {
12943 // TODO: Slight differences here in allocation order and leaving
12944 // RIP in the class. Do they matter any more here than they do
12945 // in the normal allocation?
12946 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12947 if (Subtarget->is64Bit()) {
12948 if (VT == MVT::i32 || VT == MVT::f32)
12949 return std::make_pair(0U, X86::GR32RegisterClass);
12950 else if (VT == MVT::i16)
12951 return std::make_pair(0U, X86::GR16RegisterClass);
12952 else if (VT == MVT::i8 || VT == MVT::i1)
12953 return std::make_pair(0U, X86::GR8RegisterClass);
12954 else if (VT == MVT::i64 || VT == MVT::f64)
12955 return std::make_pair(0U, X86::GR64RegisterClass);
12958 // 32-bit fallthrough
12959 case 'Q': // Q_REGS
12960 if (VT == MVT::i32 || VT == MVT::f32)
12961 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
12962 else if (VT == MVT::i16)
12963 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
12964 else if (VT == MVT::i8 || VT == MVT::i1)
12965 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
12966 else if (VT == MVT::i64)
12967 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
12969 case 'r': // GENERAL_REGS
12970 case 'l': // INDEX_REGS
12971 if (VT == MVT::i8 || VT == MVT::i1)
12972 return std::make_pair(0U, X86::GR8RegisterClass);
12973 if (VT == MVT::i16)
12974 return std::make_pair(0U, X86::GR16RegisterClass);
12975 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
12976 return std::make_pair(0U, X86::GR32RegisterClass);
12977 return std::make_pair(0U, X86::GR64RegisterClass);
12978 case 'R': // LEGACY_REGS
12979 if (VT == MVT::i8 || VT == MVT::i1)
12980 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12981 if (VT == MVT::i16)
12982 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12983 if (VT == MVT::i32 || !Subtarget->is64Bit())
12984 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12985 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12986 case 'f': // FP Stack registers.
12987 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12988 // value to the correct fpstack register class.
12989 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12990 return std::make_pair(0U, X86::RFP32RegisterClass);
12991 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12992 return std::make_pair(0U, X86::RFP64RegisterClass);
12993 return std::make_pair(0U, X86::RFP80RegisterClass);
12994 case 'y': // MMX_REGS if MMX allowed.
12995 if (!Subtarget->hasMMX()) break;
12996 return std::make_pair(0U, X86::VR64RegisterClass);
12997 case 'Y': // SSE_REGS if SSE2 allowed
12998 if (!Subtarget->hasXMMInt()) break;
13000 case 'x': // SSE_REGS if SSE1 allowed
13001 if (!Subtarget->hasXMM()) break;
13003 switch (VT.getSimpleVT().SimpleTy) {
13005 // Scalar SSE types.
13008 return std::make_pair(0U, X86::FR32RegisterClass);
13011 return std::make_pair(0U, X86::FR64RegisterClass);
13019 return std::make_pair(0U, X86::VR128RegisterClass);
13025 // Use the default implementation in TargetLowering to convert the register
13026 // constraint into a member of a register class.
13027 std::pair<unsigned, const TargetRegisterClass*> Res;
13028 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
13030 // Not found as a standard register?
13031 if (Res.second == 0) {
13032 // Map st(0) -> st(7) -> ST0
13033 if (Constraint.size() == 7 && Constraint[0] == '{' &&
13034 tolower(Constraint[1]) == 's' &&
13035 tolower(Constraint[2]) == 't' &&
13036 Constraint[3] == '(' &&
13037 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
13038 Constraint[5] == ')' &&
13039 Constraint[6] == '}') {
13041 Res.first = X86::ST0+Constraint[4]-'0';
13042 Res.second = X86::RFP80RegisterClass;
13046 // GCC allows "st(0)" to be called just plain "st".
13047 if (StringRef("{st}").equals_lower(Constraint)) {
13048 Res.first = X86::ST0;
13049 Res.second = X86::RFP80RegisterClass;
13054 if (StringRef("{flags}").equals_lower(Constraint)) {
13055 Res.first = X86::EFLAGS;
13056 Res.second = X86::CCRRegisterClass;
13060 // 'A' means EAX + EDX.
13061 if (Constraint == "A") {
13062 Res.first = X86::EAX;
13063 Res.second = X86::GR32_ADRegisterClass;
13069 // Otherwise, check to see if this is a register class of the wrong value
13070 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
13071 // turn into {ax},{dx}.
13072 if (Res.second->hasType(VT))
13073 return Res; // Correct type already, nothing to do.
13075 // All of the single-register GCC register classes map their values onto
13076 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
13077 // really want an 8-bit or 32-bit register, map to the appropriate register
13078 // class and return the appropriate register.
13079 if (Res.second == X86::GR16RegisterClass) {
13080 if (VT == MVT::i8) {
13081 unsigned DestReg = 0;
13082 switch (Res.first) {
13084 case X86::AX: DestReg = X86::AL; break;
13085 case X86::DX: DestReg = X86::DL; break;
13086 case X86::CX: DestReg = X86::CL; break;
13087 case X86::BX: DestReg = X86::BL; break;
13090 Res.first = DestReg;
13091 Res.second = X86::GR8RegisterClass;
13093 } else if (VT == MVT::i32) {
13094 unsigned DestReg = 0;
13095 switch (Res.first) {
13097 case X86::AX: DestReg = X86::EAX; break;
13098 case X86::DX: DestReg = X86::EDX; break;
13099 case X86::CX: DestReg = X86::ECX; break;
13100 case X86::BX: DestReg = X86::EBX; break;
13101 case X86::SI: DestReg = X86::ESI; break;
13102 case X86::DI: DestReg = X86::EDI; break;
13103 case X86::BP: DestReg = X86::EBP; break;
13104 case X86::SP: DestReg = X86::ESP; break;
13107 Res.first = DestReg;
13108 Res.second = X86::GR32RegisterClass;
13110 } else if (VT == MVT::i64) {
13111 unsigned DestReg = 0;
13112 switch (Res.first) {
13114 case X86::AX: DestReg = X86::RAX; break;
13115 case X86::DX: DestReg = X86::RDX; break;
13116 case X86::CX: DestReg = X86::RCX; break;
13117 case X86::BX: DestReg = X86::RBX; break;
13118 case X86::SI: DestReg = X86::RSI; break;
13119 case X86::DI: DestReg = X86::RDI; break;
13120 case X86::BP: DestReg = X86::RBP; break;
13121 case X86::SP: DestReg = X86::RSP; break;
13124 Res.first = DestReg;
13125 Res.second = X86::GR64RegisterClass;
13128 } else if (Res.second == X86::FR32RegisterClass ||
13129 Res.second == X86::FR64RegisterClass ||
13130 Res.second == X86::VR128RegisterClass) {
13131 // Handle references to XMM physical registers that got mapped into the
13132 // wrong class. This can happen with constraints like {xmm0} where the
13133 // target independent register mapper will just pick the first match it can
13134 // find, ignoring the required type.
13135 if (VT == MVT::f32)
13136 Res.second = X86::FR32RegisterClass;
13137 else if (VT == MVT::f64)
13138 Res.second = X86::FR64RegisterClass;
13139 else if (X86::VR128RegisterClass->hasType(VT))
13140 Res.second = X86::VR128RegisterClass;