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::v32i8, X86::VR256RegisterClass);
974 addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
975 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
976 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
977 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
978 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
980 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
981 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
982 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
984 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
985 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
986 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
987 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
988 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
989 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
991 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
992 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
993 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
994 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
995 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
996 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
998 // Custom lower several nodes for 256-bit types.
999 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1000 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1001 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1004 // Extract subvector is special because the value type
1005 // (result) is 128-bit but the source is 256-bit wide.
1006 if (VT.is128BitVector())
1007 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1009 // Do not attempt to custom lower other non-256-bit vectors
1010 if (!VT.is256BitVector())
1013 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1014 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1015 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1016 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1017 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1018 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1021 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1022 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1023 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1026 // Do not attempt to promote non-256-bit vectors
1027 if (!VT.is256BitVector())
1030 setOperationAction(ISD::AND, SVT, Promote);
1031 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1032 setOperationAction(ISD::OR, SVT, Promote);
1033 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1034 setOperationAction(ISD::XOR, SVT, Promote);
1035 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1036 setOperationAction(ISD::LOAD, SVT, Promote);
1037 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1038 setOperationAction(ISD::SELECT, SVT, Promote);
1039 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1043 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1044 // of this type with custom code.
1045 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1046 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1047 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1050 // We want to custom lower some of our intrinsics.
1051 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1054 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1055 // handle type legalization for these operations here.
1057 // FIXME: We really should do custom legalization for addition and
1058 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1059 // than generic legalization for 64-bit multiplication-with-overflow, though.
1060 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1061 // Add/Sub/Mul with overflow operations are custom lowered.
1063 setOperationAction(ISD::SADDO, VT, Custom);
1064 setOperationAction(ISD::UADDO, VT, Custom);
1065 setOperationAction(ISD::SSUBO, VT, Custom);
1066 setOperationAction(ISD::USUBO, VT, Custom);
1067 setOperationAction(ISD::SMULO, VT, Custom);
1068 setOperationAction(ISD::UMULO, VT, Custom);
1071 // There are no 8-bit 3-address imul/mul instructions
1072 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1073 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1075 if (!Subtarget->is64Bit()) {
1076 // These libcalls are not available in 32-bit.
1077 setLibcallName(RTLIB::SHL_I128, 0);
1078 setLibcallName(RTLIB::SRL_I128, 0);
1079 setLibcallName(RTLIB::SRA_I128, 0);
1082 // We have target-specific dag combine patterns for the following nodes:
1083 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1084 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1085 setTargetDAGCombine(ISD::BUILD_VECTOR);
1086 setTargetDAGCombine(ISD::SELECT);
1087 setTargetDAGCombine(ISD::SHL);
1088 setTargetDAGCombine(ISD::SRA);
1089 setTargetDAGCombine(ISD::SRL);
1090 setTargetDAGCombine(ISD::OR);
1091 setTargetDAGCombine(ISD::AND);
1092 setTargetDAGCombine(ISD::ADD);
1093 setTargetDAGCombine(ISD::SUB);
1094 setTargetDAGCombine(ISD::STORE);
1095 setTargetDAGCombine(ISD::ZERO_EXTEND);
1096 setTargetDAGCombine(ISD::SINT_TO_FP);
1097 if (Subtarget->is64Bit())
1098 setTargetDAGCombine(ISD::MUL);
1100 computeRegisterProperties();
1102 // On Darwin, -Os means optimize for size without hurting performance,
1103 // do not reduce the limit.
1104 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1105 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1106 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1107 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1108 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1109 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1110 setPrefLoopAlignment(16);
1111 benefitFromCodePlacementOpt = true;
1113 setPrefFunctionAlignment(4);
1117 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1122 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1123 /// the desired ByVal argument alignment.
1124 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1127 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1128 if (VTy->getBitWidth() == 128)
1130 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1131 unsigned EltAlign = 0;
1132 getMaxByValAlign(ATy->getElementType(), EltAlign);
1133 if (EltAlign > MaxAlign)
1134 MaxAlign = EltAlign;
1135 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1136 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1137 unsigned EltAlign = 0;
1138 getMaxByValAlign(STy->getElementType(i), EltAlign);
1139 if (EltAlign > MaxAlign)
1140 MaxAlign = EltAlign;
1148 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1149 /// function arguments in the caller parameter area. For X86, aggregates
1150 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1151 /// are at 4-byte boundaries.
1152 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1153 if (Subtarget->is64Bit()) {
1154 // Max of 8 and alignment of type.
1155 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1162 if (Subtarget->hasXMM())
1163 getMaxByValAlign(Ty, Align);
1167 /// getOptimalMemOpType - Returns the target specific optimal type for load
1168 /// and store operations as a result of memset, memcpy, and memmove
1169 /// lowering. If DstAlign is zero that means it's safe to destination
1170 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1171 /// means there isn't a need to check it against alignment requirement,
1172 /// probably because the source does not need to be loaded. If
1173 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1174 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1175 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1176 /// constant so it does not need to be loaded.
1177 /// It returns EVT::Other if the type should be determined using generic
1178 /// target-independent logic.
1180 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1181 unsigned DstAlign, unsigned SrcAlign,
1182 bool NonScalarIntSafe,
1184 MachineFunction &MF) const {
1185 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1186 // linux. This is because the stack realignment code can't handle certain
1187 // cases like PR2962. This should be removed when PR2962 is fixed.
1188 const Function *F = MF.getFunction();
1189 if (NonScalarIntSafe &&
1190 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1192 (Subtarget->isUnalignedMemAccessFast() ||
1193 ((DstAlign == 0 || DstAlign >= 16) &&
1194 (SrcAlign == 0 || SrcAlign >= 16))) &&
1195 Subtarget->getStackAlignment() >= 16) {
1196 if (Subtarget->hasSSE2())
1198 if (Subtarget->hasSSE1())
1200 } else if (!MemcpyStrSrc && Size >= 8 &&
1201 !Subtarget->is64Bit() &&
1202 Subtarget->getStackAlignment() >= 8 &&
1203 Subtarget->hasXMMInt()) {
1204 // Do not use f64 to lower memcpy if source is string constant. It's
1205 // better to use i32 to avoid the loads.
1209 if (Subtarget->is64Bit() && Size >= 8)
1214 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1215 /// current function. The returned value is a member of the
1216 /// MachineJumpTableInfo::JTEntryKind enum.
1217 unsigned X86TargetLowering::getJumpTableEncoding() const {
1218 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1220 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1221 Subtarget->isPICStyleGOT())
1222 return MachineJumpTableInfo::EK_Custom32;
1224 // Otherwise, use the normal jump table encoding heuristics.
1225 return TargetLowering::getJumpTableEncoding();
1229 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1230 const MachineBasicBlock *MBB,
1231 unsigned uid,MCContext &Ctx) const{
1232 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1233 Subtarget->isPICStyleGOT());
1234 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1236 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1237 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1240 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1242 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1243 SelectionDAG &DAG) const {
1244 if (!Subtarget->is64Bit())
1245 // This doesn't have DebugLoc associated with it, but is not really the
1246 // same as a Register.
1247 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1251 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1252 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1254 const MCExpr *X86TargetLowering::
1255 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1256 MCContext &Ctx) const {
1257 // X86-64 uses RIP relative addressing based on the jump table label.
1258 if (Subtarget->isPICStyleRIPRel())
1259 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1261 // Otherwise, the reference is relative to the PIC base.
1262 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1265 // FIXME: Why this routine is here? Move to RegInfo!
1266 std::pair<const TargetRegisterClass*, uint8_t>
1267 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1268 const TargetRegisterClass *RRC = 0;
1270 switch (VT.getSimpleVT().SimpleTy) {
1272 return TargetLowering::findRepresentativeClass(VT);
1273 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1274 RRC = (Subtarget->is64Bit()
1275 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1278 RRC = X86::VR64RegisterClass;
1280 case MVT::f32: case MVT::f64:
1281 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1282 case MVT::v4f32: case MVT::v2f64:
1283 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1285 RRC = X86::VR128RegisterClass;
1288 return std::make_pair(RRC, Cost);
1291 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1292 unsigned &Offset) const {
1293 if (!Subtarget->isTargetLinux())
1296 if (Subtarget->is64Bit()) {
1297 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1299 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1312 //===----------------------------------------------------------------------===//
1313 // Return Value Calling Convention Implementation
1314 //===----------------------------------------------------------------------===//
1316 #include "X86GenCallingConv.inc"
1319 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1320 MachineFunction &MF, bool isVarArg,
1321 const SmallVectorImpl<ISD::OutputArg> &Outs,
1322 LLVMContext &Context) const {
1323 SmallVector<CCValAssign, 16> RVLocs;
1324 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1326 return CCInfo.CheckReturn(Outs, RetCC_X86);
1330 X86TargetLowering::LowerReturn(SDValue Chain,
1331 CallingConv::ID CallConv, bool isVarArg,
1332 const SmallVectorImpl<ISD::OutputArg> &Outs,
1333 const SmallVectorImpl<SDValue> &OutVals,
1334 DebugLoc dl, SelectionDAG &DAG) const {
1335 MachineFunction &MF = DAG.getMachineFunction();
1336 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1338 SmallVector<CCValAssign, 16> RVLocs;
1339 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1340 RVLocs, *DAG.getContext());
1341 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1343 // Add the regs to the liveout set for the function.
1344 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1345 for (unsigned i = 0; i != RVLocs.size(); ++i)
1346 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1347 MRI.addLiveOut(RVLocs[i].getLocReg());
1351 SmallVector<SDValue, 6> RetOps;
1352 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1353 // Operand #1 = Bytes To Pop
1354 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1357 // Copy the result values into the output registers.
1358 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1359 CCValAssign &VA = RVLocs[i];
1360 assert(VA.isRegLoc() && "Can only return in registers!");
1361 SDValue ValToCopy = OutVals[i];
1362 EVT ValVT = ValToCopy.getValueType();
1364 // If this is x86-64, and we disabled SSE, we can't return FP values,
1365 // or SSE or MMX vectors.
1366 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1367 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1368 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1369 report_fatal_error("SSE register return with SSE disabled");
1371 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1372 // llvm-gcc has never done it right and no one has noticed, so this
1373 // should be OK for now.
1374 if (ValVT == MVT::f64 &&
1375 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1376 report_fatal_error("SSE2 register return with SSE2 disabled");
1378 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1379 // the RET instruction and handled by the FP Stackifier.
1380 if (VA.getLocReg() == X86::ST0 ||
1381 VA.getLocReg() == X86::ST1) {
1382 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1383 // change the value to the FP stack register class.
1384 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1385 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1386 RetOps.push_back(ValToCopy);
1387 // Don't emit a copytoreg.
1391 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1392 // which is returned in RAX / RDX.
1393 if (Subtarget->is64Bit()) {
1394 if (ValVT == MVT::x86mmx) {
1395 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1396 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1397 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1399 // If we don't have SSE2 available, convert to v4f32 so the generated
1400 // register is legal.
1401 if (!Subtarget->hasSSE2())
1402 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1407 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1408 Flag = Chain.getValue(1);
1411 // The x86-64 ABI for returning structs by value requires that we copy
1412 // the sret argument into %rax for the return. We saved the argument into
1413 // a virtual register in the entry block, so now we copy the value out
1415 if (Subtarget->is64Bit() &&
1416 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1417 MachineFunction &MF = DAG.getMachineFunction();
1418 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1419 unsigned Reg = FuncInfo->getSRetReturnReg();
1421 "SRetReturnReg should have been set in LowerFormalArguments().");
1422 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1424 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1425 Flag = Chain.getValue(1);
1427 // RAX now acts like a return value.
1428 MRI.addLiveOut(X86::RAX);
1431 RetOps[0] = Chain; // Update chain.
1433 // Add the flag if we have it.
1435 RetOps.push_back(Flag);
1437 return DAG.getNode(X86ISD::RET_FLAG, dl,
1438 MVT::Other, &RetOps[0], RetOps.size());
1441 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1442 if (N->getNumValues() != 1)
1444 if (!N->hasNUsesOfValue(1, 0))
1447 SDNode *Copy = *N->use_begin();
1448 if (Copy->getOpcode() != ISD::CopyToReg &&
1449 Copy->getOpcode() != ISD::FP_EXTEND)
1452 bool HasRet = false;
1453 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1455 if (UI->getOpcode() != X86ISD::RET_FLAG)
1464 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1465 ISD::NodeType ExtendKind) const {
1467 // TODO: Is this also valid on 32-bit?
1468 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1469 ReturnMVT = MVT::i8;
1471 ReturnMVT = MVT::i32;
1473 EVT MinVT = getRegisterType(Context, ReturnMVT);
1474 return VT.bitsLT(MinVT) ? MinVT : VT;
1477 /// LowerCallResult - Lower the result values of a call into the
1478 /// appropriate copies out of appropriate physical registers.
1481 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1482 CallingConv::ID CallConv, bool isVarArg,
1483 const SmallVectorImpl<ISD::InputArg> &Ins,
1484 DebugLoc dl, SelectionDAG &DAG,
1485 SmallVectorImpl<SDValue> &InVals) const {
1487 // Assign locations to each value returned by this call.
1488 SmallVector<CCValAssign, 16> RVLocs;
1489 bool Is64Bit = Subtarget->is64Bit();
1490 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1491 getTargetMachine(), RVLocs, *DAG.getContext());
1492 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1494 // Copy all of the result registers out of their specified physreg.
1495 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1496 CCValAssign &VA = RVLocs[i];
1497 EVT CopyVT = VA.getValVT();
1499 // If this is x86-64, and we disabled SSE, we can't return FP values
1500 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1501 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1502 report_fatal_error("SSE register return with SSE disabled");
1507 // If this is a call to a function that returns an fp value on the floating
1508 // point stack, we must guarantee the the value is popped from the stack, so
1509 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1510 // if the return value is not used. We use the FpPOP_RETVAL instruction
1512 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1513 // If we prefer to use the value in xmm registers, copy it out as f80 and
1514 // use a truncate to move it from fp stack reg to xmm reg.
1515 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1516 SDValue Ops[] = { Chain, InFlag };
1517 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1518 MVT::Other, MVT::Glue, Ops, 2), 1);
1519 Val = Chain.getValue(0);
1521 // Round the f80 to the right size, which also moves it to the appropriate
1523 if (CopyVT != VA.getValVT())
1524 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1525 // This truncation won't change the value.
1526 DAG.getIntPtrConstant(1));
1528 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1529 CopyVT, InFlag).getValue(1);
1530 Val = Chain.getValue(0);
1532 InFlag = Chain.getValue(2);
1533 InVals.push_back(Val);
1540 //===----------------------------------------------------------------------===//
1541 // C & StdCall & Fast Calling Convention implementation
1542 //===----------------------------------------------------------------------===//
1543 // StdCall calling convention seems to be standard for many Windows' API
1544 // routines and around. It differs from C calling convention just a little:
1545 // callee should clean up the stack, not caller. Symbols should be also
1546 // decorated in some fancy way :) It doesn't support any vector arguments.
1547 // For info on fast calling convention see Fast Calling Convention (tail call)
1548 // implementation LowerX86_32FastCCCallTo.
1550 /// CallIsStructReturn - Determines whether a call uses struct return
1552 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1556 return Outs[0].Flags.isSRet();
1559 /// ArgsAreStructReturn - Determines whether a function uses struct
1560 /// return semantics.
1562 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1566 return Ins[0].Flags.isSRet();
1569 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1570 /// by "Src" to address "Dst" with size and alignment information specified by
1571 /// the specific parameter attribute. The copy will be passed as a byval
1572 /// function parameter.
1574 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1575 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1577 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1579 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1580 /*isVolatile*/false, /*AlwaysInline=*/true,
1581 MachinePointerInfo(), MachinePointerInfo());
1584 /// IsTailCallConvention - Return true if the calling convention is one that
1585 /// supports tail call optimization.
1586 static bool IsTailCallConvention(CallingConv::ID CC) {
1587 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1590 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1591 if (!CI->isTailCall())
1595 CallingConv::ID CalleeCC = CS.getCallingConv();
1596 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1602 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1603 /// a tailcall target by changing its ABI.
1604 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1605 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1609 X86TargetLowering::LowerMemArgument(SDValue Chain,
1610 CallingConv::ID CallConv,
1611 const SmallVectorImpl<ISD::InputArg> &Ins,
1612 DebugLoc dl, SelectionDAG &DAG,
1613 const CCValAssign &VA,
1614 MachineFrameInfo *MFI,
1616 // Create the nodes corresponding to a load from this parameter slot.
1617 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1618 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1619 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1622 // If value is passed by pointer we have address passed instead of the value
1624 if (VA.getLocInfo() == CCValAssign::Indirect)
1625 ValVT = VA.getLocVT();
1627 ValVT = VA.getValVT();
1629 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1630 // changed with more analysis.
1631 // In case of tail call optimization mark all arguments mutable. Since they
1632 // could be overwritten by lowering of arguments in case of a tail call.
1633 if (Flags.isByVal()) {
1634 unsigned Bytes = Flags.getByValSize();
1635 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1636 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1637 return DAG.getFrameIndex(FI, getPointerTy());
1639 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1640 VA.getLocMemOffset(), isImmutable);
1641 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1642 return DAG.getLoad(ValVT, dl, Chain, FIN,
1643 MachinePointerInfo::getFixedStack(FI),
1649 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1650 CallingConv::ID CallConv,
1652 const SmallVectorImpl<ISD::InputArg> &Ins,
1655 SmallVectorImpl<SDValue> &InVals)
1657 MachineFunction &MF = DAG.getMachineFunction();
1658 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1660 const Function* Fn = MF.getFunction();
1661 if (Fn->hasExternalLinkage() &&
1662 Subtarget->isTargetCygMing() &&
1663 Fn->getName() == "main")
1664 FuncInfo->setForceFramePointer(true);
1666 MachineFrameInfo *MFI = MF.getFrameInfo();
1667 bool Is64Bit = Subtarget->is64Bit();
1668 bool IsWin64 = Subtarget->isTargetWin64();
1670 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1671 "Var args not supported with calling convention fastcc or ghc");
1673 // Assign locations to all of the incoming arguments.
1674 SmallVector<CCValAssign, 16> ArgLocs;
1675 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1676 ArgLocs, *DAG.getContext());
1678 // Allocate shadow area for Win64
1680 CCInfo.AllocateStack(32, 8);
1683 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1685 unsigned LastVal = ~0U;
1687 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1688 CCValAssign &VA = ArgLocs[i];
1689 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1691 assert(VA.getValNo() != LastVal &&
1692 "Don't support value assigned to multiple locs yet");
1693 LastVal = VA.getValNo();
1695 if (VA.isRegLoc()) {
1696 EVT RegVT = VA.getLocVT();
1697 TargetRegisterClass *RC = NULL;
1698 if (RegVT == MVT::i32)
1699 RC = X86::GR32RegisterClass;
1700 else if (Is64Bit && RegVT == MVT::i64)
1701 RC = X86::GR64RegisterClass;
1702 else if (RegVT == MVT::f32)
1703 RC = X86::FR32RegisterClass;
1704 else if (RegVT == MVT::f64)
1705 RC = X86::FR64RegisterClass;
1706 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1707 RC = X86::VR256RegisterClass;
1708 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1709 RC = X86::VR128RegisterClass;
1710 else if (RegVT == MVT::x86mmx)
1711 RC = X86::VR64RegisterClass;
1713 llvm_unreachable("Unknown argument type!");
1715 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1716 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1718 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1719 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1721 if (VA.getLocInfo() == CCValAssign::SExt)
1722 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1723 DAG.getValueType(VA.getValVT()));
1724 else if (VA.getLocInfo() == CCValAssign::ZExt)
1725 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1726 DAG.getValueType(VA.getValVT()));
1727 else if (VA.getLocInfo() == CCValAssign::BCvt)
1728 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1730 if (VA.isExtInLoc()) {
1731 // Handle MMX values passed in XMM regs.
1732 if (RegVT.isVector()) {
1733 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1736 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1739 assert(VA.isMemLoc());
1740 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1743 // If value is passed via pointer - do a load.
1744 if (VA.getLocInfo() == CCValAssign::Indirect)
1745 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1746 MachinePointerInfo(), false, false, 0);
1748 InVals.push_back(ArgValue);
1751 // The x86-64 ABI for returning structs by value requires that we copy
1752 // the sret argument into %rax for the return. Save the argument into
1753 // a virtual register so that we can access it from the return points.
1754 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1755 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1756 unsigned Reg = FuncInfo->getSRetReturnReg();
1758 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1759 FuncInfo->setSRetReturnReg(Reg);
1761 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1762 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1765 unsigned StackSize = CCInfo.getNextStackOffset();
1766 // Align stack specially for tail calls.
1767 if (FuncIsMadeTailCallSafe(CallConv))
1768 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1770 // If the function takes variable number of arguments, make a frame index for
1771 // the start of the first vararg value... for expansion of llvm.va_start.
1773 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1774 CallConv != CallingConv::X86_ThisCall)) {
1775 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1778 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1780 // FIXME: We should really autogenerate these arrays
1781 static const unsigned GPR64ArgRegsWin64[] = {
1782 X86::RCX, X86::RDX, X86::R8, X86::R9
1784 static const unsigned GPR64ArgRegs64Bit[] = {
1785 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1787 static const unsigned XMMArgRegs64Bit[] = {
1788 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1789 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1791 const unsigned *GPR64ArgRegs;
1792 unsigned NumXMMRegs = 0;
1795 // The XMM registers which might contain var arg parameters are shadowed
1796 // in their paired GPR. So we only need to save the GPR to their home
1798 TotalNumIntRegs = 4;
1799 GPR64ArgRegs = GPR64ArgRegsWin64;
1801 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1802 GPR64ArgRegs = GPR64ArgRegs64Bit;
1804 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1806 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1809 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1810 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1811 "SSE register cannot be used when SSE is disabled!");
1812 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1813 "SSE register cannot be used when SSE is disabled!");
1814 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1815 // Kernel mode asks for SSE to be disabled, so don't push them
1817 TotalNumXMMRegs = 0;
1820 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1821 // Get to the caller-allocated home save location. Add 8 to account
1822 // for the return address.
1823 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1824 FuncInfo->setRegSaveFrameIndex(
1825 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1826 // Fixup to set vararg frame on shadow area (4 x i64).
1828 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1830 // For X86-64, if there are vararg parameters that are passed via
1831 // registers, then we must store them to their spots on the stack so they
1832 // may be loaded by deferencing the result of va_next.
1833 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1834 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1835 FuncInfo->setRegSaveFrameIndex(
1836 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1840 // Store the integer parameter registers.
1841 SmallVector<SDValue, 8> MemOps;
1842 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1844 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1845 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1846 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1847 DAG.getIntPtrConstant(Offset));
1848 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1849 X86::GR64RegisterClass);
1850 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1852 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1853 MachinePointerInfo::getFixedStack(
1854 FuncInfo->getRegSaveFrameIndex(), Offset),
1856 MemOps.push_back(Store);
1860 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1861 // Now store the XMM (fp + vector) parameter registers.
1862 SmallVector<SDValue, 11> SaveXMMOps;
1863 SaveXMMOps.push_back(Chain);
1865 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1866 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1867 SaveXMMOps.push_back(ALVal);
1869 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1870 FuncInfo->getRegSaveFrameIndex()));
1871 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1872 FuncInfo->getVarArgsFPOffset()));
1874 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1875 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1876 X86::VR128RegisterClass);
1877 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1878 SaveXMMOps.push_back(Val);
1880 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1882 &SaveXMMOps[0], SaveXMMOps.size()));
1885 if (!MemOps.empty())
1886 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1887 &MemOps[0], MemOps.size());
1891 // Some CCs need callee pop.
1892 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1893 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1895 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1896 // If this is an sret function, the return should pop the hidden pointer.
1897 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1898 FuncInfo->setBytesToPopOnReturn(4);
1902 // RegSaveFrameIndex is X86-64 only.
1903 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1904 if (CallConv == CallingConv::X86_FastCall ||
1905 CallConv == CallingConv::X86_ThisCall)
1906 // fastcc functions can't have varargs.
1907 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1914 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1915 SDValue StackPtr, SDValue Arg,
1916 DebugLoc dl, SelectionDAG &DAG,
1917 const CCValAssign &VA,
1918 ISD::ArgFlagsTy Flags) const {
1919 unsigned LocMemOffset = VA.getLocMemOffset();
1920 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1921 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1922 if (Flags.isByVal())
1923 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1925 return DAG.getStore(Chain, dl, Arg, PtrOff,
1926 MachinePointerInfo::getStack(LocMemOffset),
1930 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1931 /// optimization is performed and it is required.
1933 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1934 SDValue &OutRetAddr, SDValue Chain,
1935 bool IsTailCall, bool Is64Bit,
1936 int FPDiff, DebugLoc dl) const {
1937 // Adjust the Return address stack slot.
1938 EVT VT = getPointerTy();
1939 OutRetAddr = getReturnAddressFrameIndex(DAG);
1941 // Load the "old" Return address.
1942 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1944 return SDValue(OutRetAddr.getNode(), 1);
1947 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1948 /// optimization is performed and it is required (FPDiff!=0).
1950 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1951 SDValue Chain, SDValue RetAddrFrIdx,
1952 bool Is64Bit, int FPDiff, DebugLoc dl) {
1953 // Store the return address to the appropriate stack slot.
1954 if (!FPDiff) return Chain;
1955 // Calculate the new stack slot for the return address.
1956 int SlotSize = Is64Bit ? 8 : 4;
1957 int NewReturnAddrFI =
1958 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1959 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1960 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1961 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1962 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1968 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1969 CallingConv::ID CallConv, bool isVarArg,
1971 const SmallVectorImpl<ISD::OutputArg> &Outs,
1972 const SmallVectorImpl<SDValue> &OutVals,
1973 const SmallVectorImpl<ISD::InputArg> &Ins,
1974 DebugLoc dl, SelectionDAG &DAG,
1975 SmallVectorImpl<SDValue> &InVals) const {
1976 MachineFunction &MF = DAG.getMachineFunction();
1977 bool Is64Bit = Subtarget->is64Bit();
1978 bool IsWin64 = Subtarget->isTargetWin64();
1979 bool IsStructRet = CallIsStructReturn(Outs);
1980 bool IsSibcall = false;
1983 // Check if it's really possible to do a tail call.
1984 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1985 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1986 Outs, OutVals, Ins, DAG);
1988 // Sibcalls are automatically detected tailcalls which do not require
1990 if (!GuaranteedTailCallOpt && isTailCall)
1997 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1998 "Var args not supported with calling convention fastcc or ghc");
2000 // Analyze operands of the call, assigning locations to each operand.
2001 SmallVector<CCValAssign, 16> ArgLocs;
2002 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2003 ArgLocs, *DAG.getContext());
2005 // Allocate shadow area for Win64
2007 CCInfo.AllocateStack(32, 8);
2010 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2012 // Get a count of how many bytes are to be pushed on the stack.
2013 unsigned NumBytes = CCInfo.getNextStackOffset();
2015 // This is a sibcall. The memory operands are available in caller's
2016 // own caller's stack.
2018 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2019 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2022 if (isTailCall && !IsSibcall) {
2023 // Lower arguments at fp - stackoffset + fpdiff.
2024 unsigned NumBytesCallerPushed =
2025 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2026 FPDiff = NumBytesCallerPushed - NumBytes;
2028 // Set the delta of movement of the returnaddr stackslot.
2029 // But only set if delta is greater than previous delta.
2030 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2031 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2035 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2037 SDValue RetAddrFrIdx;
2038 // Load return address for tail calls.
2039 if (isTailCall && FPDiff)
2040 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2041 Is64Bit, FPDiff, dl);
2043 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2044 SmallVector<SDValue, 8> MemOpChains;
2047 // Walk the register/memloc assignments, inserting copies/loads. In the case
2048 // of tail call optimization arguments are handle later.
2049 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2050 CCValAssign &VA = ArgLocs[i];
2051 EVT RegVT = VA.getLocVT();
2052 SDValue Arg = OutVals[i];
2053 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2054 bool isByVal = Flags.isByVal();
2056 // Promote the value if needed.
2057 switch (VA.getLocInfo()) {
2058 default: llvm_unreachable("Unknown loc info!");
2059 case CCValAssign::Full: break;
2060 case CCValAssign::SExt:
2061 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2063 case CCValAssign::ZExt:
2064 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2066 case CCValAssign::AExt:
2067 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2068 // Special case: passing MMX values in XMM registers.
2069 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2070 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2071 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2073 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2075 case CCValAssign::BCvt:
2076 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2078 case CCValAssign::Indirect: {
2079 // Store the argument.
2080 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2081 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2082 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2083 MachinePointerInfo::getFixedStack(FI),
2090 if (VA.isRegLoc()) {
2091 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2092 if (isVarArg && IsWin64) {
2093 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2094 // shadow reg if callee is a varargs function.
2095 unsigned ShadowReg = 0;
2096 switch (VA.getLocReg()) {
2097 case X86::XMM0: ShadowReg = X86::RCX; break;
2098 case X86::XMM1: ShadowReg = X86::RDX; break;
2099 case X86::XMM2: ShadowReg = X86::R8; break;
2100 case X86::XMM3: ShadowReg = X86::R9; break;
2103 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2105 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2106 assert(VA.isMemLoc());
2107 if (StackPtr.getNode() == 0)
2108 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2109 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2110 dl, DAG, VA, Flags));
2114 if (!MemOpChains.empty())
2115 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2116 &MemOpChains[0], MemOpChains.size());
2118 // Build a sequence of copy-to-reg nodes chained together with token chain
2119 // and flag operands which copy the outgoing args into registers.
2121 // Tail call byval lowering might overwrite argument registers so in case of
2122 // tail call optimization the copies to registers are lowered later.
2124 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2125 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2126 RegsToPass[i].second, InFlag);
2127 InFlag = Chain.getValue(1);
2130 if (Subtarget->isPICStyleGOT()) {
2131 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2134 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2135 DAG.getNode(X86ISD::GlobalBaseReg,
2136 DebugLoc(), getPointerTy()),
2138 InFlag = Chain.getValue(1);
2140 // If we are tail calling and generating PIC/GOT style code load the
2141 // address of the callee into ECX. The value in ecx is used as target of
2142 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2143 // for tail calls on PIC/GOT architectures. Normally we would just put the
2144 // address of GOT into ebx and then call target@PLT. But for tail calls
2145 // ebx would be restored (since ebx is callee saved) before jumping to the
2148 // Note: The actual moving to ECX is done further down.
2149 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2150 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2151 !G->getGlobal()->hasProtectedVisibility())
2152 Callee = LowerGlobalAddress(Callee, DAG);
2153 else if (isa<ExternalSymbolSDNode>(Callee))
2154 Callee = LowerExternalSymbol(Callee, DAG);
2158 if (Is64Bit && isVarArg && !IsWin64) {
2159 // From AMD64 ABI document:
2160 // For calls that may call functions that use varargs or stdargs
2161 // (prototype-less calls or calls to functions containing ellipsis (...) in
2162 // the declaration) %al is used as hidden argument to specify the number
2163 // of SSE registers used. The contents of %al do not need to match exactly
2164 // the number of registers, but must be an ubound on the number of SSE
2165 // registers used and is in the range 0 - 8 inclusive.
2167 // Count the number of XMM registers allocated.
2168 static const unsigned XMMArgRegs[] = {
2169 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2170 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2172 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2173 assert((Subtarget->hasXMM() || !NumXMMRegs)
2174 && "SSE registers cannot be used when SSE is disabled");
2176 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2177 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2178 InFlag = Chain.getValue(1);
2182 // For tail calls lower the arguments to the 'real' stack slot.
2184 // Force all the incoming stack arguments to be loaded from the stack
2185 // before any new outgoing arguments are stored to the stack, because the
2186 // outgoing stack slots may alias the incoming argument stack slots, and
2187 // the alias isn't otherwise explicit. This is slightly more conservative
2188 // than necessary, because it means that each store effectively depends
2189 // on every argument instead of just those arguments it would clobber.
2190 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2192 SmallVector<SDValue, 8> MemOpChains2;
2195 // Do not flag preceding copytoreg stuff together with the following stuff.
2197 if (GuaranteedTailCallOpt) {
2198 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2199 CCValAssign &VA = ArgLocs[i];
2202 assert(VA.isMemLoc());
2203 SDValue Arg = OutVals[i];
2204 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2205 // Create frame index.
2206 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2207 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2208 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2209 FIN = DAG.getFrameIndex(FI, getPointerTy());
2211 if (Flags.isByVal()) {
2212 // Copy relative to framepointer.
2213 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2214 if (StackPtr.getNode() == 0)
2215 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2217 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2219 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2223 // Store relative to framepointer.
2224 MemOpChains2.push_back(
2225 DAG.getStore(ArgChain, dl, Arg, FIN,
2226 MachinePointerInfo::getFixedStack(FI),
2232 if (!MemOpChains2.empty())
2233 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2234 &MemOpChains2[0], MemOpChains2.size());
2236 // Copy arguments to their registers.
2237 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2238 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2239 RegsToPass[i].second, InFlag);
2240 InFlag = Chain.getValue(1);
2244 // Store the return address to the appropriate stack slot.
2245 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2249 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2250 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2251 // In the 64-bit large code model, we have to make all calls
2252 // through a register, since the call instruction's 32-bit
2253 // pc-relative offset may not be large enough to hold the whole
2255 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2256 // If the callee is a GlobalAddress node (quite common, every direct call
2257 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2260 // We should use extra load for direct calls to dllimported functions in
2262 const GlobalValue *GV = G->getGlobal();
2263 if (!GV->hasDLLImportLinkage()) {
2264 unsigned char OpFlags = 0;
2265 bool ExtraLoad = false;
2266 unsigned WrapperKind = ISD::DELETED_NODE;
2268 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2269 // external symbols most go through the PLT in PIC mode. If the symbol
2270 // has hidden or protected visibility, or if it is static or local, then
2271 // we don't need to use the PLT - we can directly call it.
2272 if (Subtarget->isTargetELF() &&
2273 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2274 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2275 OpFlags = X86II::MO_PLT;
2276 } else if (Subtarget->isPICStyleStubAny() &&
2277 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2278 (!Subtarget->getTargetTriple().isMacOSX() ||
2279 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2280 // PC-relative references to external symbols should go through $stub,
2281 // unless we're building with the leopard linker or later, which
2282 // automatically synthesizes these stubs.
2283 OpFlags = X86II::MO_DARWIN_STUB;
2284 } else if (Subtarget->isPICStyleRIPRel() &&
2285 isa<Function>(GV) &&
2286 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2287 // If the function is marked as non-lazy, generate an indirect call
2288 // which loads from the GOT directly. This avoids runtime overhead
2289 // at the cost of eager binding (and one extra byte of encoding).
2290 OpFlags = X86II::MO_GOTPCREL;
2291 WrapperKind = X86ISD::WrapperRIP;
2295 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2296 G->getOffset(), OpFlags);
2298 // Add a wrapper if needed.
2299 if (WrapperKind != ISD::DELETED_NODE)
2300 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2301 // Add extra indirection if needed.
2303 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2304 MachinePointerInfo::getGOT(),
2307 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2308 unsigned char OpFlags = 0;
2310 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2311 // external symbols should go through the PLT.
2312 if (Subtarget->isTargetELF() &&
2313 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2314 OpFlags = X86II::MO_PLT;
2315 } else if (Subtarget->isPICStyleStubAny() &&
2316 (!Subtarget->getTargetTriple().isMacOSX() ||
2317 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2318 // PC-relative references to external symbols should go through $stub,
2319 // unless we're building with the leopard linker or later, which
2320 // automatically synthesizes these stubs.
2321 OpFlags = X86II::MO_DARWIN_STUB;
2324 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2328 // Returns a chain & a flag for retval copy to use.
2329 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2330 SmallVector<SDValue, 8> Ops;
2332 if (!IsSibcall && isTailCall) {
2333 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2334 DAG.getIntPtrConstant(0, true), InFlag);
2335 InFlag = Chain.getValue(1);
2338 Ops.push_back(Chain);
2339 Ops.push_back(Callee);
2342 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2344 // Add argument registers to the end of the list so that they are known live
2346 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2347 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2348 RegsToPass[i].second.getValueType()));
2350 // Add an implicit use GOT pointer in EBX.
2351 if (!isTailCall && Subtarget->isPICStyleGOT())
2352 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2354 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2355 if (Is64Bit && isVarArg && !IsWin64)
2356 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2358 if (InFlag.getNode())
2359 Ops.push_back(InFlag);
2363 //// If this is the first return lowered for this function, add the regs
2364 //// to the liveout set for the function.
2365 // This isn't right, although it's probably harmless on x86; liveouts
2366 // should be computed from returns not tail calls. Consider a void
2367 // function making a tail call to a function returning int.
2368 return DAG.getNode(X86ISD::TC_RETURN, dl,
2369 NodeTys, &Ops[0], Ops.size());
2372 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2373 InFlag = Chain.getValue(1);
2375 // Create the CALLSEQ_END node.
2376 unsigned NumBytesForCalleeToPush;
2377 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2378 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2379 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2380 // If this is a call to a struct-return function, the callee
2381 // pops the hidden struct pointer, so we have to push it back.
2382 // This is common for Darwin/X86, Linux & Mingw32 targets.
2383 NumBytesForCalleeToPush = 4;
2385 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2387 // Returns a flag for retval copy to use.
2389 Chain = DAG.getCALLSEQ_END(Chain,
2390 DAG.getIntPtrConstant(NumBytes, true),
2391 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2394 InFlag = Chain.getValue(1);
2397 // Handle result values, copying them out of physregs into vregs that we
2399 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2400 Ins, dl, DAG, InVals);
2404 //===----------------------------------------------------------------------===//
2405 // Fast Calling Convention (tail call) implementation
2406 //===----------------------------------------------------------------------===//
2408 // Like std call, callee cleans arguments, convention except that ECX is
2409 // reserved for storing the tail called function address. Only 2 registers are
2410 // free for argument passing (inreg). Tail call optimization is performed
2412 // * tailcallopt is enabled
2413 // * caller/callee are fastcc
2414 // On X86_64 architecture with GOT-style position independent code only local
2415 // (within module) calls are supported at the moment.
2416 // To keep the stack aligned according to platform abi the function
2417 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2418 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2419 // If a tail called function callee has more arguments than the caller the
2420 // caller needs to make sure that there is room to move the RETADDR to. This is
2421 // achieved by reserving an area the size of the argument delta right after the
2422 // original REtADDR, but before the saved framepointer or the spilled registers
2423 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2435 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2436 /// for a 16 byte align requirement.
2438 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2439 SelectionDAG& DAG) const {
2440 MachineFunction &MF = DAG.getMachineFunction();
2441 const TargetMachine &TM = MF.getTarget();
2442 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2443 unsigned StackAlignment = TFI.getStackAlignment();
2444 uint64_t AlignMask = StackAlignment - 1;
2445 int64_t Offset = StackSize;
2446 uint64_t SlotSize = TD->getPointerSize();
2447 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2448 // Number smaller than 12 so just add the difference.
2449 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2451 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2452 Offset = ((~AlignMask) & Offset) + StackAlignment +
2453 (StackAlignment-SlotSize);
2458 /// MatchingStackOffset - Return true if the given stack call argument is
2459 /// already available in the same position (relatively) of the caller's
2460 /// incoming argument stack.
2462 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2463 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2464 const X86InstrInfo *TII) {
2465 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2467 if (Arg.getOpcode() == ISD::CopyFromReg) {
2468 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2469 if (!TargetRegisterInfo::isVirtualRegister(VR))
2471 MachineInstr *Def = MRI->getVRegDef(VR);
2474 if (!Flags.isByVal()) {
2475 if (!TII->isLoadFromStackSlot(Def, FI))
2478 unsigned Opcode = Def->getOpcode();
2479 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2480 Def->getOperand(1).isFI()) {
2481 FI = Def->getOperand(1).getIndex();
2482 Bytes = Flags.getByValSize();
2486 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2487 if (Flags.isByVal())
2488 // ByVal argument is passed in as a pointer but it's now being
2489 // dereferenced. e.g.
2490 // define @foo(%struct.X* %A) {
2491 // tail call @bar(%struct.X* byval %A)
2494 SDValue Ptr = Ld->getBasePtr();
2495 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2498 FI = FINode->getIndex();
2499 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2500 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2501 FI = FINode->getIndex();
2502 Bytes = Flags.getByValSize();
2506 assert(FI != INT_MAX);
2507 if (!MFI->isFixedObjectIndex(FI))
2509 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2512 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2513 /// for tail call optimization. Targets which want to do tail call
2514 /// optimization should implement this function.
2516 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2517 CallingConv::ID CalleeCC,
2519 bool isCalleeStructRet,
2520 bool isCallerStructRet,
2521 const SmallVectorImpl<ISD::OutputArg> &Outs,
2522 const SmallVectorImpl<SDValue> &OutVals,
2523 const SmallVectorImpl<ISD::InputArg> &Ins,
2524 SelectionDAG& DAG) const {
2525 if (!IsTailCallConvention(CalleeCC) &&
2526 CalleeCC != CallingConv::C)
2529 // If -tailcallopt is specified, make fastcc functions tail-callable.
2530 const MachineFunction &MF = DAG.getMachineFunction();
2531 const Function *CallerF = DAG.getMachineFunction().getFunction();
2532 CallingConv::ID CallerCC = CallerF->getCallingConv();
2533 bool CCMatch = CallerCC == CalleeCC;
2535 if (GuaranteedTailCallOpt) {
2536 if (IsTailCallConvention(CalleeCC) && CCMatch)
2541 // Look for obvious safe cases to perform tail call optimization that do not
2542 // require ABI changes. This is what gcc calls sibcall.
2544 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2545 // emit a special epilogue.
2546 if (RegInfo->needsStackRealignment(MF))
2549 // Also avoid sibcall optimization if either caller or callee uses struct
2550 // return semantics.
2551 if (isCalleeStructRet || isCallerStructRet)
2554 // An stdcall caller is expected to clean up its arguments; the callee
2555 // isn't going to do that.
2556 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2559 // Do not sibcall optimize vararg calls unless all arguments are passed via
2561 if (isVarArg && !Outs.empty()) {
2563 // Optimizing for varargs on Win64 is unlikely to be safe without
2564 // additional testing.
2565 if (Subtarget->isTargetWin64())
2568 SmallVector<CCValAssign, 16> ArgLocs;
2569 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2570 getTargetMachine(), ArgLocs, *DAG.getContext());
2572 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2573 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2574 if (!ArgLocs[i].isRegLoc())
2578 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2579 // Therefore if it's not used by the call it is not safe to optimize this into
2581 bool Unused = false;
2582 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2589 SmallVector<CCValAssign, 16> RVLocs;
2590 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2591 getTargetMachine(), RVLocs, *DAG.getContext());
2592 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2593 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2594 CCValAssign &VA = RVLocs[i];
2595 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2600 // If the calling conventions do not match, then we'd better make sure the
2601 // results are returned in the same way as what the caller expects.
2603 SmallVector<CCValAssign, 16> RVLocs1;
2604 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2605 getTargetMachine(), RVLocs1, *DAG.getContext());
2606 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2608 SmallVector<CCValAssign, 16> RVLocs2;
2609 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2610 getTargetMachine(), RVLocs2, *DAG.getContext());
2611 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2613 if (RVLocs1.size() != RVLocs2.size())
2615 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2616 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2618 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2620 if (RVLocs1[i].isRegLoc()) {
2621 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2624 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2630 // If the callee takes no arguments then go on to check the results of the
2632 if (!Outs.empty()) {
2633 // Check if stack adjustment is needed. For now, do not do this if any
2634 // argument is passed on the stack.
2635 SmallVector<CCValAssign, 16> ArgLocs;
2636 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2637 getTargetMachine(), ArgLocs, *DAG.getContext());
2639 // Allocate shadow area for Win64
2640 if (Subtarget->isTargetWin64()) {
2641 CCInfo.AllocateStack(32, 8);
2644 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2645 if (CCInfo.getNextStackOffset()) {
2646 MachineFunction &MF = DAG.getMachineFunction();
2647 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2650 // Check if the arguments are already laid out in the right way as
2651 // the caller's fixed stack objects.
2652 MachineFrameInfo *MFI = MF.getFrameInfo();
2653 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2654 const X86InstrInfo *TII =
2655 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2656 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2657 CCValAssign &VA = ArgLocs[i];
2658 SDValue Arg = OutVals[i];
2659 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2660 if (VA.getLocInfo() == CCValAssign::Indirect)
2662 if (!VA.isRegLoc()) {
2663 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2670 // If the tailcall address may be in a register, then make sure it's
2671 // possible to register allocate for it. In 32-bit, the call address can
2672 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2673 // callee-saved registers are restored. These happen to be the same
2674 // registers used to pass 'inreg' arguments so watch out for those.
2675 if (!Subtarget->is64Bit() &&
2676 !isa<GlobalAddressSDNode>(Callee) &&
2677 !isa<ExternalSymbolSDNode>(Callee)) {
2678 unsigned NumInRegs = 0;
2679 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2680 CCValAssign &VA = ArgLocs[i];
2683 unsigned Reg = VA.getLocReg();
2686 case X86::EAX: case X86::EDX: case X86::ECX:
2687 if (++NumInRegs == 3)
2699 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2700 return X86::createFastISel(funcInfo);
2704 //===----------------------------------------------------------------------===//
2705 // Other Lowering Hooks
2706 //===----------------------------------------------------------------------===//
2708 static bool MayFoldLoad(SDValue Op) {
2709 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2712 static bool MayFoldIntoStore(SDValue Op) {
2713 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2716 static bool isTargetShuffle(unsigned Opcode) {
2718 default: return false;
2719 case X86ISD::PSHUFD:
2720 case X86ISD::PSHUFHW:
2721 case X86ISD::PSHUFLW:
2722 case X86ISD::SHUFPD:
2723 case X86ISD::PALIGN:
2724 case X86ISD::SHUFPS:
2725 case X86ISD::MOVLHPS:
2726 case X86ISD::MOVLHPD:
2727 case X86ISD::MOVHLPS:
2728 case X86ISD::MOVLPS:
2729 case X86ISD::MOVLPD:
2730 case X86ISD::MOVSHDUP:
2731 case X86ISD::MOVSLDUP:
2732 case X86ISD::MOVDDUP:
2735 case X86ISD::UNPCKLPS:
2736 case X86ISD::UNPCKLPD:
2737 case X86ISD::VUNPCKLPS:
2738 case X86ISD::VUNPCKLPD:
2739 case X86ISD::VUNPCKLPSY:
2740 case X86ISD::VUNPCKLPDY:
2741 case X86ISD::PUNPCKLWD:
2742 case X86ISD::PUNPCKLBW:
2743 case X86ISD::PUNPCKLDQ:
2744 case X86ISD::PUNPCKLQDQ:
2745 case X86ISD::UNPCKHPS:
2746 case X86ISD::UNPCKHPD:
2747 case X86ISD::PUNPCKHWD:
2748 case X86ISD::PUNPCKHBW:
2749 case X86ISD::PUNPCKHDQ:
2750 case X86ISD::PUNPCKHQDQ:
2751 case X86ISD::VPERMIL:
2757 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2758 SDValue V1, SelectionDAG &DAG) {
2760 default: llvm_unreachable("Unknown x86 shuffle node");
2761 case X86ISD::MOVSHDUP:
2762 case X86ISD::MOVSLDUP:
2763 case X86ISD::MOVDDUP:
2764 return DAG.getNode(Opc, dl, VT, V1);
2770 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2771 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2773 default: llvm_unreachable("Unknown x86 shuffle node");
2774 case X86ISD::PSHUFD:
2775 case X86ISD::PSHUFHW:
2776 case X86ISD::PSHUFLW:
2777 case X86ISD::VPERMIL:
2778 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2784 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2785 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2787 default: llvm_unreachable("Unknown x86 shuffle node");
2788 case X86ISD::PALIGN:
2789 case X86ISD::SHUFPD:
2790 case X86ISD::SHUFPS:
2791 return DAG.getNode(Opc, dl, VT, V1, V2,
2792 DAG.getConstant(TargetMask, MVT::i8));
2797 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2798 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2800 default: llvm_unreachable("Unknown x86 shuffle node");
2801 case X86ISD::MOVLHPS:
2802 case X86ISD::MOVLHPD:
2803 case X86ISD::MOVHLPS:
2804 case X86ISD::MOVLPS:
2805 case X86ISD::MOVLPD:
2808 case X86ISD::UNPCKLPS:
2809 case X86ISD::UNPCKLPD:
2810 case X86ISD::VUNPCKLPS:
2811 case X86ISD::VUNPCKLPD:
2812 case X86ISD::VUNPCKLPSY:
2813 case X86ISD::VUNPCKLPDY:
2814 case X86ISD::PUNPCKLWD:
2815 case X86ISD::PUNPCKLBW:
2816 case X86ISD::PUNPCKLDQ:
2817 case X86ISD::PUNPCKLQDQ:
2818 case X86ISD::UNPCKHPS:
2819 case X86ISD::UNPCKHPD:
2820 case X86ISD::PUNPCKHWD:
2821 case X86ISD::PUNPCKHBW:
2822 case X86ISD::PUNPCKHDQ:
2823 case X86ISD::PUNPCKHQDQ:
2824 return DAG.getNode(Opc, dl, VT, V1, V2);
2829 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2830 MachineFunction &MF = DAG.getMachineFunction();
2831 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2832 int ReturnAddrIndex = FuncInfo->getRAIndex();
2834 if (ReturnAddrIndex == 0) {
2835 // Set up a frame object for the return address.
2836 uint64_t SlotSize = TD->getPointerSize();
2837 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2839 FuncInfo->setRAIndex(ReturnAddrIndex);
2842 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2846 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2847 bool hasSymbolicDisplacement) {
2848 // Offset should fit into 32 bit immediate field.
2849 if (!isInt<32>(Offset))
2852 // If we don't have a symbolic displacement - we don't have any extra
2854 if (!hasSymbolicDisplacement)
2857 // FIXME: Some tweaks might be needed for medium code model.
2858 if (M != CodeModel::Small && M != CodeModel::Kernel)
2861 // For small code model we assume that latest object is 16MB before end of 31
2862 // bits boundary. We may also accept pretty large negative constants knowing
2863 // that all objects are in the positive half of address space.
2864 if (M == CodeModel::Small && Offset < 16*1024*1024)
2867 // For kernel code model we know that all object resist in the negative half
2868 // of 32bits address space. We may not accept negative offsets, since they may
2869 // be just off and we may accept pretty large positive ones.
2870 if (M == CodeModel::Kernel && Offset > 0)
2876 /// isCalleePop - Determines whether the callee is required to pop its
2877 /// own arguments. Callee pop is necessary to support tail calls.
2878 bool X86::isCalleePop(CallingConv::ID CallingConv,
2879 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2883 switch (CallingConv) {
2886 case CallingConv::X86_StdCall:
2888 case CallingConv::X86_FastCall:
2890 case CallingConv::X86_ThisCall:
2892 case CallingConv::Fast:
2894 case CallingConv::GHC:
2899 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2900 /// specific condition code, returning the condition code and the LHS/RHS of the
2901 /// comparison to make.
2902 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2903 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2905 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2906 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2907 // X > -1 -> X == 0, jump !sign.
2908 RHS = DAG.getConstant(0, RHS.getValueType());
2909 return X86::COND_NS;
2910 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2911 // X < 0 -> X == 0, jump on sign.
2913 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2915 RHS = DAG.getConstant(0, RHS.getValueType());
2916 return X86::COND_LE;
2920 switch (SetCCOpcode) {
2921 default: llvm_unreachable("Invalid integer condition!");
2922 case ISD::SETEQ: return X86::COND_E;
2923 case ISD::SETGT: return X86::COND_G;
2924 case ISD::SETGE: return X86::COND_GE;
2925 case ISD::SETLT: return X86::COND_L;
2926 case ISD::SETLE: return X86::COND_LE;
2927 case ISD::SETNE: return X86::COND_NE;
2928 case ISD::SETULT: return X86::COND_B;
2929 case ISD::SETUGT: return X86::COND_A;
2930 case ISD::SETULE: return X86::COND_BE;
2931 case ISD::SETUGE: return X86::COND_AE;
2935 // First determine if it is required or is profitable to flip the operands.
2937 // If LHS is a foldable load, but RHS is not, flip the condition.
2938 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2939 !ISD::isNON_EXTLoad(RHS.getNode())) {
2940 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2941 std::swap(LHS, RHS);
2944 switch (SetCCOpcode) {
2950 std::swap(LHS, RHS);
2954 // On a floating point condition, the flags are set as follows:
2956 // 0 | 0 | 0 | X > Y
2957 // 0 | 0 | 1 | X < Y
2958 // 1 | 0 | 0 | X == Y
2959 // 1 | 1 | 1 | unordered
2960 switch (SetCCOpcode) {
2961 default: llvm_unreachable("Condcode should be pre-legalized away");
2963 case ISD::SETEQ: return X86::COND_E;
2964 case ISD::SETOLT: // flipped
2966 case ISD::SETGT: return X86::COND_A;
2967 case ISD::SETOLE: // flipped
2969 case ISD::SETGE: return X86::COND_AE;
2970 case ISD::SETUGT: // flipped
2972 case ISD::SETLT: return X86::COND_B;
2973 case ISD::SETUGE: // flipped
2975 case ISD::SETLE: return X86::COND_BE;
2977 case ISD::SETNE: return X86::COND_NE;
2978 case ISD::SETUO: return X86::COND_P;
2979 case ISD::SETO: return X86::COND_NP;
2981 case ISD::SETUNE: return X86::COND_INVALID;
2985 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2986 /// code. Current x86 isa includes the following FP cmov instructions:
2987 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2988 static bool hasFPCMov(unsigned X86CC) {
3004 /// isFPImmLegal - Returns true if the target can instruction select the
3005 /// specified FP immediate natively. If false, the legalizer will
3006 /// materialize the FP immediate as a load from a constant pool.
3007 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3008 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3009 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3015 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3016 /// the specified range (L, H].
3017 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3018 return (Val < 0) || (Val >= Low && Val < Hi);
3021 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3022 /// specified value.
3023 static bool isUndefOrEqual(int Val, int CmpVal) {
3024 if (Val < 0 || Val == CmpVal)
3029 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3030 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3031 /// the second operand.
3032 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3033 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3034 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3035 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3036 return (Mask[0] < 2 && Mask[1] < 2);
3040 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3041 SmallVector<int, 8> M;
3043 return ::isPSHUFDMask(M, N->getValueType(0));
3046 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3047 /// is suitable for input to PSHUFHW.
3048 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3049 if (VT != MVT::v8i16)
3052 // Lower quadword copied in order or undef.
3053 for (int i = 0; i != 4; ++i)
3054 if (Mask[i] >= 0 && Mask[i] != i)
3057 // Upper quadword shuffled.
3058 for (int i = 4; i != 8; ++i)
3059 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3065 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3066 SmallVector<int, 8> M;
3068 return ::isPSHUFHWMask(M, N->getValueType(0));
3071 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3072 /// is suitable for input to PSHUFLW.
3073 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3074 if (VT != MVT::v8i16)
3077 // Upper quadword copied in order.
3078 for (int i = 4; i != 8; ++i)
3079 if (Mask[i] >= 0 && Mask[i] != i)
3082 // Lower quadword shuffled.
3083 for (int i = 0; i != 4; ++i)
3090 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3091 SmallVector<int, 8> M;
3093 return ::isPSHUFLWMask(M, N->getValueType(0));
3096 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3097 /// is suitable for input to PALIGNR.
3098 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3100 int i, e = VT.getVectorNumElements();
3102 // Do not handle v2i64 / v2f64 shuffles with palignr.
3103 if (e < 4 || !hasSSSE3)
3106 for (i = 0; i != e; ++i)
3110 // All undef, not a palignr.
3114 // Determine if it's ok to perform a palignr with only the LHS, since we
3115 // don't have access to the actual shuffle elements to see if RHS is undef.
3116 bool Unary = Mask[i] < (int)e;
3117 bool NeedsUnary = false;
3119 int s = Mask[i] - i;
3121 // Check the rest of the elements to see if they are consecutive.
3122 for (++i; i != e; ++i) {
3127 Unary = Unary && (m < (int)e);
3128 NeedsUnary = NeedsUnary || (m < s);
3130 if (NeedsUnary && !Unary)
3132 if (Unary && m != ((s+i) & (e-1)))
3134 if (!Unary && m != (s+i))
3140 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3141 SmallVector<int, 8> M;
3143 return ::isPALIGNRMask(M, N->getValueType(0), true);
3146 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3147 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3148 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3149 int NumElems = VT.getVectorNumElements();
3150 if (NumElems != 2 && NumElems != 4)
3153 int Half = NumElems / 2;
3154 for (int i = 0; i < Half; ++i)
3155 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3157 for (int i = Half; i < NumElems; ++i)
3158 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3164 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3165 SmallVector<int, 8> M;
3167 return ::isSHUFPMask(M, N->getValueType(0));
3170 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3171 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3172 /// half elements to come from vector 1 (which would equal the dest.) and
3173 /// the upper half to come from vector 2.
3174 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3175 int NumElems = VT.getVectorNumElements();
3177 if (NumElems != 2 && NumElems != 4)
3180 int Half = NumElems / 2;
3181 for (int i = 0; i < Half; ++i)
3182 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3184 for (int i = Half; i < NumElems; ++i)
3185 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3190 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3191 SmallVector<int, 8> M;
3193 return isCommutedSHUFPMask(M, N->getValueType(0));
3196 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3197 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3198 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3199 if (N->getValueType(0).getVectorNumElements() != 4)
3202 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3203 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3204 isUndefOrEqual(N->getMaskElt(1), 7) &&
3205 isUndefOrEqual(N->getMaskElt(2), 2) &&
3206 isUndefOrEqual(N->getMaskElt(3), 3);
3209 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3210 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3212 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3213 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3218 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3219 isUndefOrEqual(N->getMaskElt(1), 3) &&
3220 isUndefOrEqual(N->getMaskElt(2), 2) &&
3221 isUndefOrEqual(N->getMaskElt(3), 3);
3224 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3225 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3226 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3227 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3229 if (NumElems != 2 && NumElems != 4)
3232 for (unsigned i = 0; i < NumElems/2; ++i)
3233 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3236 for (unsigned i = NumElems/2; i < NumElems; ++i)
3237 if (!isUndefOrEqual(N->getMaskElt(i), i))
3243 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3244 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3245 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3246 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3248 if ((NumElems != 2 && NumElems != 4)
3249 || N->getValueType(0).getSizeInBits() > 128)
3252 for (unsigned i = 0; i < NumElems/2; ++i)
3253 if (!isUndefOrEqual(N->getMaskElt(i), i))
3256 for (unsigned i = 0; i < NumElems/2; ++i)
3257 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3263 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3264 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3265 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3266 bool V2IsSplat = false) {
3267 int NumElts = VT.getVectorNumElements();
3268 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3271 // Handle vector lengths > 128 bits. Define a "section" as a set of
3272 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3274 unsigned NumSections = VT.getSizeInBits() / 128;
3275 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3276 unsigned NumSectionElts = NumElts / NumSections;
3279 unsigned End = NumSectionElts;
3280 for (unsigned s = 0; s < NumSections; ++s) {
3281 for (unsigned i = Start, j = s * NumSectionElts;
3285 int BitI1 = Mask[i+1];
3286 if (!isUndefOrEqual(BitI, j))
3289 if (!isUndefOrEqual(BitI1, NumElts))
3292 if (!isUndefOrEqual(BitI1, j + NumElts))
3296 // Process the next 128 bits.
3297 Start += NumSectionElts;
3298 End += NumSectionElts;
3304 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3305 SmallVector<int, 8> M;
3307 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3310 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3311 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3312 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3313 bool V2IsSplat = false) {
3314 int NumElts = VT.getVectorNumElements();
3315 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3318 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3320 int BitI1 = Mask[i+1];
3321 if (!isUndefOrEqual(BitI, j + NumElts/2))
3324 if (isUndefOrEqual(BitI1, NumElts))
3327 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3334 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3335 SmallVector<int, 8> M;
3337 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3340 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3341 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3343 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3344 int NumElems = VT.getVectorNumElements();
3345 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3348 // Handle vector lengths > 128 bits. Define a "section" as a set of
3349 // 128 bits. AVX defines UNPCK* to operate independently on 128-bit
3351 unsigned NumSections = VT.getSizeInBits() / 128;
3352 if (NumSections == 0 ) NumSections = 1; // Handle MMX
3353 unsigned NumSectionElts = NumElems / NumSections;
3355 for (unsigned s = 0; s < NumSections; ++s) {
3356 for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3357 i != NumSectionElts * (s + 1);
3360 int BitI1 = Mask[i+1];
3362 if (!isUndefOrEqual(BitI, j))
3364 if (!isUndefOrEqual(BitI1, j))
3372 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3373 SmallVector<int, 8> M;
3375 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3378 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3379 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3381 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3382 int NumElems = VT.getVectorNumElements();
3383 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3386 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3388 int BitI1 = Mask[i+1];
3389 if (!isUndefOrEqual(BitI, j))
3391 if (!isUndefOrEqual(BitI1, j))
3397 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3398 SmallVector<int, 8> M;
3400 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3403 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3404 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3405 /// MOVSD, and MOVD, i.e. setting the lowest element.
3406 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3407 if (VT.getVectorElementType().getSizeInBits() < 32)
3410 int NumElts = VT.getVectorNumElements();
3412 if (!isUndefOrEqual(Mask[0], NumElts))
3415 for (int i = 1; i < NumElts; ++i)
3416 if (!isUndefOrEqual(Mask[i], i))
3422 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3423 SmallVector<int, 8> M;
3425 return ::isMOVLMask(M, N->getValueType(0));
3428 /// isVPERMILMask - Return true if the specified VECTOR_SHUFFLE operand
3429 /// specifies a shuffle of elements that is suitable for input to VPERMIL*.
3430 static bool isVPERMILMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3431 unsigned NumElts = VT.getVectorNumElements();
3432 unsigned NumLanes = VT.getSizeInBits()/128;
3434 // Match any permutation of 128-bit vector with 32/64-bit types
3435 if (NumLanes == 1) {
3436 if (NumElts == 4 || NumElts == 2)
3441 // Only match 256-bit with 32/64-bit types
3442 if (NumElts != 8 && NumElts != 4)
3445 // The mask on the high lane should be the same as the low. Actually,
3446 // they can differ if any of the corresponding index in a lane is undef.
3447 int LaneSize = NumElts/NumLanes;
3448 for (int i = 0; i < LaneSize; ++i) {
3449 int HighElt = i+LaneSize;
3450 if (Mask[i] < 0 || Mask[HighElt] < 0)
3453 if (Mask[HighElt]-Mask[i] != LaneSize)
3460 /// getShuffleVPERMILImmediateediate - Return the appropriate immediate to shuffle
3461 /// the specified VECTOR_MASK mask with VPERMIL* instructions.
3462 static unsigned getShuffleVPERMILImmediate(SDNode *N) {
3463 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3464 EVT VT = SVOp->getValueType(0);
3466 int NumElts = VT.getVectorNumElements();
3467 int NumLanes = VT.getSizeInBits()/128;
3470 for (int i = 0; i < NumElts/NumLanes /* lane size */; ++i)
3471 Mask |= SVOp->getMaskElt(i) << (i*2);
3476 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3477 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3478 /// element of vector 2 and the other elements to come from vector 1 in order.
3479 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3480 bool V2IsSplat = false, bool V2IsUndef = false) {
3481 int NumOps = VT.getVectorNumElements();
3482 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3485 if (!isUndefOrEqual(Mask[0], 0))
3488 for (int i = 1; i < NumOps; ++i)
3489 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3490 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3491 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3497 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3498 bool V2IsUndef = false) {
3499 SmallVector<int, 8> M;
3501 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3504 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3505 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3506 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3507 if (N->getValueType(0).getVectorNumElements() != 4)
3510 // Expect 1, 1, 3, 3
3511 for (unsigned i = 0; i < 2; ++i) {
3512 int Elt = N->getMaskElt(i);
3513 if (Elt >= 0 && Elt != 1)
3518 for (unsigned i = 2; i < 4; ++i) {
3519 int Elt = N->getMaskElt(i);
3520 if (Elt >= 0 && Elt != 3)
3525 // Don't use movshdup if it can be done with a shufps.
3526 // FIXME: verify that matching u, u, 3, 3 is what we want.
3530 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3531 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3532 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3533 if (N->getValueType(0).getVectorNumElements() != 4)
3536 // Expect 0, 0, 2, 2
3537 for (unsigned i = 0; i < 2; ++i)
3538 if (N->getMaskElt(i) > 0)
3542 for (unsigned i = 2; i < 4; ++i) {
3543 int Elt = N->getMaskElt(i);
3544 if (Elt >= 0 && Elt != 2)
3549 // Don't use movsldup if it can be done with a shufps.
3553 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3554 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3555 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3556 int e = N->getValueType(0).getVectorNumElements() / 2;
3558 for (int i = 0; i < e; ++i)
3559 if (!isUndefOrEqual(N->getMaskElt(i), i))
3561 for (int i = 0; i < e; ++i)
3562 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3567 /// isVEXTRACTF128Index - Return true if the specified
3568 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3569 /// suitable for input to VEXTRACTF128.
3570 bool X86::isVEXTRACTF128Index(SDNode *N) {
3571 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3574 // The index should be aligned on a 128-bit boundary.
3576 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3578 unsigned VL = N->getValueType(0).getVectorNumElements();
3579 unsigned VBits = N->getValueType(0).getSizeInBits();
3580 unsigned ElSize = VBits / VL;
3581 bool Result = (Index * ElSize) % 128 == 0;
3586 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3587 /// operand specifies a subvector insert that is suitable for input to
3589 bool X86::isVINSERTF128Index(SDNode *N) {
3590 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3593 // The index should be aligned on a 128-bit boundary.
3595 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3597 unsigned VL = N->getValueType(0).getVectorNumElements();
3598 unsigned VBits = N->getValueType(0).getSizeInBits();
3599 unsigned ElSize = VBits / VL;
3600 bool Result = (Index * ElSize) % 128 == 0;
3605 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3606 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3607 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3608 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3609 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3611 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3613 for (int i = 0; i < NumOperands; ++i) {
3614 int Val = SVOp->getMaskElt(NumOperands-i-1);
3615 if (Val < 0) Val = 0;
3616 if (Val >= NumOperands) Val -= NumOperands;
3618 if (i != NumOperands - 1)
3624 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3625 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3626 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3627 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3629 // 8 nodes, but we only care about the last 4.
3630 for (unsigned i = 7; i >= 4; --i) {
3631 int Val = SVOp->getMaskElt(i);
3640 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3641 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3642 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3643 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3645 // 8 nodes, but we only care about the first 4.
3646 for (int i = 3; i >= 0; --i) {
3647 int Val = SVOp->getMaskElt(i);
3656 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3657 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3658 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3659 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3660 EVT VVT = N->getValueType(0);
3661 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3665 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3666 Val = SVOp->getMaskElt(i);
3670 return (Val - i) * EltSize;
3673 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3674 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3676 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3677 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3678 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3681 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3683 EVT VecVT = N->getOperand(0).getValueType();
3684 EVT ElVT = VecVT.getVectorElementType();
3686 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3687 return Index / NumElemsPerChunk;
3690 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3691 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3693 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3694 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3695 llvm_unreachable("Illegal insert subvector for VINSERTF128");
3698 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3700 EVT VecVT = N->getValueType(0);
3701 EVT ElVT = VecVT.getVectorElementType();
3703 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3704 return Index / NumElemsPerChunk;
3707 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3709 bool X86::isZeroNode(SDValue Elt) {
3710 return ((isa<ConstantSDNode>(Elt) &&
3711 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3712 (isa<ConstantFPSDNode>(Elt) &&
3713 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3716 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3717 /// their permute mask.
3718 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3719 SelectionDAG &DAG) {
3720 EVT VT = SVOp->getValueType(0);
3721 unsigned NumElems = VT.getVectorNumElements();
3722 SmallVector<int, 8> MaskVec;
3724 for (unsigned i = 0; i != NumElems; ++i) {
3725 int idx = SVOp->getMaskElt(i);
3727 MaskVec.push_back(idx);
3728 else if (idx < (int)NumElems)
3729 MaskVec.push_back(idx + NumElems);
3731 MaskVec.push_back(idx - NumElems);
3733 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3734 SVOp->getOperand(0), &MaskVec[0]);
3737 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3738 /// the two vector operands have swapped position.
3739 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3740 unsigned NumElems = VT.getVectorNumElements();
3741 for (unsigned i = 0; i != NumElems; ++i) {
3745 else if (idx < (int)NumElems)
3746 Mask[i] = idx + NumElems;
3748 Mask[i] = idx - NumElems;
3752 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3753 /// match movhlps. The lower half elements should come from upper half of
3754 /// V1 (and in order), and the upper half elements should come from the upper
3755 /// half of V2 (and in order).
3756 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3757 if (Op->getValueType(0).getVectorNumElements() != 4)
3759 for (unsigned i = 0, e = 2; i != e; ++i)
3760 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3762 for (unsigned i = 2; i != 4; ++i)
3763 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3768 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3769 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3771 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3772 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3774 N = N->getOperand(0).getNode();
3775 if (!ISD::isNON_EXTLoad(N))
3778 *LD = cast<LoadSDNode>(N);
3782 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3783 /// match movlp{s|d}. The lower half elements should come from lower half of
3784 /// V1 (and in order), and the upper half elements should come from the upper
3785 /// half of V2 (and in order). And since V1 will become the source of the
3786 /// MOVLP, it must be either a vector load or a scalar load to vector.
3787 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3788 ShuffleVectorSDNode *Op) {
3789 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3791 // Is V2 is a vector load, don't do this transformation. We will try to use
3792 // load folding shufps op.
3793 if (ISD::isNON_EXTLoad(V2))
3796 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3798 if (NumElems != 2 && NumElems != 4)
3800 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3801 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3803 for (unsigned i = NumElems/2; i != NumElems; ++i)
3804 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3809 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3811 static bool isSplatVector(SDNode *N) {
3812 if (N->getOpcode() != ISD::BUILD_VECTOR)
3815 SDValue SplatValue = N->getOperand(0);
3816 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3817 if (N->getOperand(i) != SplatValue)
3822 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3823 /// to an zero vector.
3824 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3825 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3826 SDValue V1 = N->getOperand(0);
3827 SDValue V2 = N->getOperand(1);
3828 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3829 for (unsigned i = 0; i != NumElems; ++i) {
3830 int Idx = N->getMaskElt(i);
3831 if (Idx >= (int)NumElems) {
3832 unsigned Opc = V2.getOpcode();
3833 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3835 if (Opc != ISD::BUILD_VECTOR ||
3836 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3838 } else if (Idx >= 0) {
3839 unsigned Opc = V1.getOpcode();
3840 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3842 if (Opc != ISD::BUILD_VECTOR ||
3843 !X86::isZeroNode(V1.getOperand(Idx)))
3850 /// getZeroVector - Returns a vector of specified type with all zero elements.
3852 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3854 assert(VT.isVector() && "Expected a vector type");
3856 // Always build SSE zero vectors as <4 x i32> bitcasted
3857 // to their dest type. This ensures they get CSE'd.
3859 if (VT.getSizeInBits() == 128) { // SSE
3860 if (HasSSE2) { // SSE2
3861 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3862 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3864 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3865 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3867 } else if (VT.getSizeInBits() == 256) { // AVX
3868 // 256-bit logic and arithmetic instructions in AVX are
3869 // all floating-point, no support for integer ops. Default
3870 // to emitting fp zeroed vectors then.
3871 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3872 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3873 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3875 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3878 /// getOnesVector - Returns a vector of specified type with all bits set.
3879 /// Always build ones vectors as <4 x i32> or <8 x i32> bitcasted to
3880 /// their original type, ensuring they get CSE'd.
3881 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3882 assert(VT.isVector() && "Expected a vector type");
3883 assert((VT.is128BitVector() || VT.is256BitVector())
3884 && "Expected a 128-bit or 256-bit vector type");
3886 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3889 if (VT.is256BitVector()) {
3890 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3891 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
3893 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3894 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3897 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3898 /// that point to V2 points to its first element.
3899 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3900 EVT VT = SVOp->getValueType(0);
3901 unsigned NumElems = VT.getVectorNumElements();
3903 bool Changed = false;
3904 SmallVector<int, 8> MaskVec;
3905 SVOp->getMask(MaskVec);
3907 for (unsigned i = 0; i != NumElems; ++i) {
3908 if (MaskVec[i] > (int)NumElems) {
3909 MaskVec[i] = NumElems;
3914 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3915 SVOp->getOperand(1), &MaskVec[0]);
3916 return SDValue(SVOp, 0);
3919 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3920 /// operation of specified width.
3921 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3923 unsigned NumElems = VT.getVectorNumElements();
3924 SmallVector<int, 8> Mask;
3925 Mask.push_back(NumElems);
3926 for (unsigned i = 1; i != NumElems; ++i)
3928 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3931 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3932 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3934 unsigned NumElems = VT.getVectorNumElements();
3935 SmallVector<int, 8> Mask;
3936 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3938 Mask.push_back(i + NumElems);
3940 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3943 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
3944 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3946 unsigned NumElems = VT.getVectorNumElements();
3947 unsigned Half = NumElems/2;
3948 SmallVector<int, 8> Mask;
3949 for (unsigned i = 0; i != Half; ++i) {
3950 Mask.push_back(i + Half);
3951 Mask.push_back(i + NumElems + Half);
3953 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3956 // PromoteSplatv8v16 - All i16 and i8 vector types can't be used directly by
3957 // a generic shuffle instruction because the target has no such instructions.
3958 // Generate shuffles which repeat i16 and i8 several times until they can be
3959 // represented by v4f32 and then be manipulated by target suported shuffles.
3960 static SDValue PromoteSplatv8v16(SDValue V, SelectionDAG &DAG, int &EltNo) {
3961 EVT VT = V.getValueType();
3962 int NumElems = VT.getVectorNumElements();
3963 DebugLoc dl = V.getDebugLoc();
3965 while (NumElems > 4) {
3966 if (EltNo < NumElems/2) {
3967 V = getUnpackl(DAG, dl, VT, V, V);
3969 V = getUnpackh(DAG, dl, VT, V, V);
3970 EltNo -= NumElems/2;
3977 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
3978 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
3979 EVT VT = V.getValueType();
3980 DebugLoc dl = V.getDebugLoc();
3981 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
3982 && "Vector size not supported");
3984 bool Is128 = VT.getSizeInBits() == 128;
3985 EVT NVT = Is128 ? MVT::v4f32 : MVT::v8f32;
3986 V = DAG.getNode(ISD::BITCAST, dl, NVT, V);
3989 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3990 V = DAG.getVectorShuffle(NVT, dl, V, DAG.getUNDEF(NVT), &SplatMask[0]);
3992 // The second half of indicies refer to the higher part, which is a
3993 // duplication of the lower one. This makes this shuffle a perfect match
3994 // for the VPERM instruction.
3995 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
3996 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
3997 V = DAG.getVectorShuffle(NVT, dl, V, DAG.getUNDEF(NVT), &SplatMask[0]);
4000 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4003 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32 and
4004 /// v8i32, v16i16 or v32i8 to v8f32.
4005 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4006 EVT SrcVT = SV->getValueType(0);
4007 SDValue V1 = SV->getOperand(0);
4008 DebugLoc dl = SV->getDebugLoc();
4010 int EltNo = SV->getSplatIndex();
4011 int NumElems = SrcVT.getVectorNumElements();
4012 unsigned Size = SrcVT.getSizeInBits();
4014 // Extract the 128-bit part containing the splat element and update
4015 // the splat element index when it refers to the higher register.
4017 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4018 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4020 EltNo -= NumElems/2;
4023 // Make this 128-bit vector duplicate i8 and i16 elements
4025 V1 = PromoteSplatv8v16(V1, DAG, EltNo);
4027 // Recreate the 256-bit vector and place the same 128-bit vector
4028 // into the low and high part. This is necessary because we want
4029 // to use VPERM to shuffle the v8f32 vector, and VPERM only shuffles
4030 // inside each separate v4f32 lane.
4032 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4033 DAG.getConstant(0, MVT::i32), DAG, dl);
4034 V1 = Insert128BitVector(InsV, V1,
4035 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4038 return getLegalSplat(DAG, V1, EltNo);
4041 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4042 /// vector of zero or undef vector. This produces a shuffle where the low
4043 /// element of V2 is swizzled into the zero/undef vector, landing at element
4044 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4045 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4046 bool isZero, bool HasSSE2,
4047 SelectionDAG &DAG) {
4048 EVT VT = V2.getValueType();
4050 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4051 unsigned NumElems = VT.getVectorNumElements();
4052 SmallVector<int, 16> MaskVec;
4053 for (unsigned i = 0; i != NumElems; ++i)
4054 // If this is the insertion idx, put the low elt of V2 here.
4055 MaskVec.push_back(i == Idx ? NumElems : i);
4056 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4059 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4060 /// element of the result of the vector shuffle.
4061 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4064 return SDValue(); // Limit search depth.
4066 SDValue V = SDValue(N, 0);
4067 EVT VT = V.getValueType();
4068 unsigned Opcode = V.getOpcode();
4070 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4071 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4072 Index = SV->getMaskElt(Index);
4075 return DAG.getUNDEF(VT.getVectorElementType());
4077 int NumElems = VT.getVectorNumElements();
4078 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4079 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4082 // Recurse into target specific vector shuffles to find scalars.
4083 if (isTargetShuffle(Opcode)) {
4084 int NumElems = VT.getVectorNumElements();
4085 SmallVector<unsigned, 16> ShuffleMask;
4089 case X86ISD::SHUFPS:
4090 case X86ISD::SHUFPD:
4091 ImmN = N->getOperand(N->getNumOperands()-1);
4092 DecodeSHUFPSMask(NumElems,
4093 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4096 case X86ISD::PUNPCKHBW:
4097 case X86ISD::PUNPCKHWD:
4098 case X86ISD::PUNPCKHDQ:
4099 case X86ISD::PUNPCKHQDQ:
4100 DecodePUNPCKHMask(NumElems, ShuffleMask);
4102 case X86ISD::UNPCKHPS:
4103 case X86ISD::UNPCKHPD:
4104 DecodeUNPCKHPMask(NumElems, ShuffleMask);
4106 case X86ISD::PUNPCKLBW:
4107 case X86ISD::PUNPCKLWD:
4108 case X86ISD::PUNPCKLDQ:
4109 case X86ISD::PUNPCKLQDQ:
4110 DecodePUNPCKLMask(VT, ShuffleMask);
4112 case X86ISD::UNPCKLPS:
4113 case X86ISD::UNPCKLPD:
4114 case X86ISD::VUNPCKLPS:
4115 case X86ISD::VUNPCKLPD:
4116 case X86ISD::VUNPCKLPSY:
4117 case X86ISD::VUNPCKLPDY:
4118 DecodeUNPCKLPMask(VT, ShuffleMask);
4120 case X86ISD::MOVHLPS:
4121 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4123 case X86ISD::MOVLHPS:
4124 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4126 case X86ISD::PSHUFD:
4127 ImmN = N->getOperand(N->getNumOperands()-1);
4128 DecodePSHUFMask(NumElems,
4129 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4132 case X86ISD::PSHUFHW:
4133 ImmN = N->getOperand(N->getNumOperands()-1);
4134 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4137 case X86ISD::PSHUFLW:
4138 ImmN = N->getOperand(N->getNumOperands()-1);
4139 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4143 case X86ISD::MOVSD: {
4144 // The index 0 always comes from the first element of the second source,
4145 // this is why MOVSS and MOVSD are used in the first place. The other
4146 // elements come from the other positions of the first source vector.
4147 unsigned OpNum = (Index == 0) ? 1 : 0;
4148 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4151 case X86ISD::VPERMIL:
4152 ImmN = N->getOperand(N->getNumOperands()-1);
4153 DecodeVPERMILMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4156 assert("not implemented for target shuffle node");
4160 Index = ShuffleMask[Index];
4162 return DAG.getUNDEF(VT.getVectorElementType());
4164 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4165 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4169 // Actual nodes that may contain scalar elements
4170 if (Opcode == ISD::BITCAST) {
4171 V = V.getOperand(0);
4172 EVT SrcVT = V.getValueType();
4173 unsigned NumElems = VT.getVectorNumElements();
4175 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4179 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4180 return (Index == 0) ? V.getOperand(0)
4181 : DAG.getUNDEF(VT.getVectorElementType());
4183 if (V.getOpcode() == ISD::BUILD_VECTOR)
4184 return V.getOperand(Index);
4189 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4190 /// shuffle operation which come from a consecutively from a zero. The
4191 /// search can start in two different directions, from left or right.
4193 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4194 bool ZerosFromLeft, SelectionDAG &DAG) {
4197 while (i < NumElems) {
4198 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4199 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4200 if (!(Elt.getNode() &&
4201 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4209 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4210 /// MaskE correspond consecutively to elements from one of the vector operands,
4211 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4213 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4214 int OpIdx, int NumElems, unsigned &OpNum) {
4215 bool SeenV1 = false;
4216 bool SeenV2 = false;
4218 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4219 int Idx = SVOp->getMaskElt(i);
4220 // Ignore undef indicies
4229 // Only accept consecutive elements from the same vector
4230 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4234 OpNum = SeenV1 ? 0 : 1;
4238 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4239 /// logical left shift of a vector.
4240 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4241 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4242 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4243 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4244 false /* check zeros from right */, DAG);
4250 // Considering the elements in the mask that are not consecutive zeros,
4251 // check if they consecutively come from only one of the source vectors.
4253 // V1 = {X, A, B, C} 0
4255 // vector_shuffle V1, V2 <1, 2, 3, X>
4257 if (!isShuffleMaskConsecutive(SVOp,
4258 0, // Mask Start Index
4259 NumElems-NumZeros-1, // Mask End Index
4260 NumZeros, // Where to start looking in the src vector
4261 NumElems, // Number of elements in vector
4262 OpSrc)) // Which source operand ?
4267 ShVal = SVOp->getOperand(OpSrc);
4271 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4272 /// logical left shift of a vector.
4273 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4274 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4275 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4276 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4277 true /* check zeros from left */, DAG);
4283 // Considering the elements in the mask that are not consecutive zeros,
4284 // check if they consecutively come from only one of the source vectors.
4286 // 0 { A, B, X, X } = V2
4288 // vector_shuffle V1, V2 <X, X, 4, 5>
4290 if (!isShuffleMaskConsecutive(SVOp,
4291 NumZeros, // Mask Start Index
4292 NumElems-1, // Mask End Index
4293 0, // Where to start looking in the src vector
4294 NumElems, // Number of elements in vector
4295 OpSrc)) // Which source operand ?
4300 ShVal = SVOp->getOperand(OpSrc);
4304 /// isVectorShift - Returns true if the shuffle can be implemented as a
4305 /// logical left or right shift of a vector.
4306 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4307 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4308 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4309 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4315 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4317 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4318 unsigned NumNonZero, unsigned NumZero,
4320 const TargetLowering &TLI) {
4324 DebugLoc dl = Op.getDebugLoc();
4327 for (unsigned i = 0; i < 16; ++i) {
4328 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4329 if (ThisIsNonZero && First) {
4331 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4333 V = DAG.getUNDEF(MVT::v8i16);
4338 SDValue ThisElt(0, 0), LastElt(0, 0);
4339 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4340 if (LastIsNonZero) {
4341 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4342 MVT::i16, Op.getOperand(i-1));
4344 if (ThisIsNonZero) {
4345 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4346 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4347 ThisElt, DAG.getConstant(8, MVT::i8));
4349 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4353 if (ThisElt.getNode())
4354 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4355 DAG.getIntPtrConstant(i/2));
4359 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4362 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4364 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4365 unsigned NumNonZero, unsigned NumZero,
4367 const TargetLowering &TLI) {
4371 DebugLoc dl = Op.getDebugLoc();
4374 for (unsigned i = 0; i < 8; ++i) {
4375 bool isNonZero = (NonZeros & (1 << i)) != 0;
4379 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4381 V = DAG.getUNDEF(MVT::v8i16);
4384 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4385 MVT::v8i16, V, Op.getOperand(i),
4386 DAG.getIntPtrConstant(i));
4393 /// getVShift - Return a vector logical shift node.
4395 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4396 unsigned NumBits, SelectionDAG &DAG,
4397 const TargetLowering &TLI, DebugLoc dl) {
4398 EVT ShVT = MVT::v2i64;
4399 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4400 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4401 return DAG.getNode(ISD::BITCAST, dl, VT,
4402 DAG.getNode(Opc, dl, ShVT, SrcOp,
4403 DAG.getConstant(NumBits,
4404 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4408 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4409 SelectionDAG &DAG) const {
4411 // Check if the scalar load can be widened into a vector load. And if
4412 // the address is "base + cst" see if the cst can be "absorbed" into
4413 // the shuffle mask.
4414 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4415 SDValue Ptr = LD->getBasePtr();
4416 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4418 EVT PVT = LD->getValueType(0);
4419 if (PVT != MVT::i32 && PVT != MVT::f32)
4424 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4425 FI = FINode->getIndex();
4427 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4428 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4429 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4430 Offset = Ptr.getConstantOperandVal(1);
4431 Ptr = Ptr.getOperand(0);
4436 SDValue Chain = LD->getChain();
4437 // Make sure the stack object alignment is at least 16.
4438 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4439 if (DAG.InferPtrAlignment(Ptr) < 16) {
4440 if (MFI->isFixedObjectIndex(FI)) {
4441 // Can't change the alignment. FIXME: It's possible to compute
4442 // the exact stack offset and reference FI + adjust offset instead.
4443 // If someone *really* cares about this. That's the way to implement it.
4446 MFI->setObjectAlignment(FI, 16);
4450 // (Offset % 16) must be multiple of 4. Then address is then
4451 // Ptr + (Offset & ~15).
4454 if ((Offset % 16) & 3)
4456 int64_t StartOffset = Offset & ~15;
4458 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4459 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4461 int EltNo = (Offset - StartOffset) >> 2;
4462 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4463 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4464 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4465 LD->getPointerInfo().getWithOffset(StartOffset),
4467 // Canonicalize it to a v4i32 shuffle.
4468 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4469 return DAG.getNode(ISD::BITCAST, dl, VT,
4470 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4471 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4477 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4478 /// vector of type 'VT', see if the elements can be replaced by a single large
4479 /// load which has the same value as a build_vector whose operands are 'elts'.
4481 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4483 /// FIXME: we'd also like to handle the case where the last elements are zero
4484 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4485 /// There's even a handy isZeroNode for that purpose.
4486 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4487 DebugLoc &DL, SelectionDAG &DAG) {
4488 EVT EltVT = VT.getVectorElementType();
4489 unsigned NumElems = Elts.size();
4491 LoadSDNode *LDBase = NULL;
4492 unsigned LastLoadedElt = -1U;
4494 // For each element in the initializer, see if we've found a load or an undef.
4495 // If we don't find an initial load element, or later load elements are
4496 // non-consecutive, bail out.
4497 for (unsigned i = 0; i < NumElems; ++i) {
4498 SDValue Elt = Elts[i];
4500 if (!Elt.getNode() ||
4501 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4504 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4506 LDBase = cast<LoadSDNode>(Elt.getNode());
4510 if (Elt.getOpcode() == ISD::UNDEF)
4513 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4514 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4519 // If we have found an entire vector of loads and undefs, then return a large
4520 // load of the entire vector width starting at the base pointer. If we found
4521 // consecutive loads for the low half, generate a vzext_load node.
4522 if (LastLoadedElt == NumElems - 1) {
4523 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4524 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4525 LDBase->getPointerInfo(),
4526 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4527 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4528 LDBase->getPointerInfo(),
4529 LDBase->isVolatile(), LDBase->isNonTemporal(),
4530 LDBase->getAlignment());
4531 } else if (NumElems == 4 && LastLoadedElt == 1) {
4532 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4533 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4534 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4536 LDBase->getMemOperand());
4537 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4543 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4544 DebugLoc dl = Op.getDebugLoc();
4546 EVT VT = Op.getValueType();
4547 EVT ExtVT = VT.getVectorElementType();
4549 unsigned NumElems = Op.getNumOperands();
4551 // For AVX-length vectors, build the individual 128-bit pieces and
4552 // use shuffles to put them in place.
4553 if (VT.getSizeInBits() > 256 &&
4554 Subtarget->hasAVX() &&
4555 !ISD::isBuildVectorAllZeros(Op.getNode())) {
4556 SmallVector<SDValue, 8> V;
4558 for (unsigned i = 0; i < NumElems; ++i) {
4559 V[i] = Op.getOperand(i);
4562 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4564 // Build the lower subvector.
4565 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4566 // Build the upper subvector.
4567 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4570 return ConcatVectors(Lower, Upper, DAG);
4574 // - pxor (SSE2), xorps (SSE1), vpxor (128 AVX), xorp[s|d] (256 AVX)
4576 // - pcmpeqd (SSE2 and 128 AVX), fallback to constant pools (256 AVX)
4577 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4578 ISD::isBuildVectorAllOnes(Op.getNode())) {
4579 // Canonicalize this to <4 x i32> or <8 x 32> (SSE) to
4580 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4581 // eliminated on x86-32 hosts.
4582 if (Op.getValueType() == MVT::v4i32 ||
4583 Op.getValueType() == MVT::v8i32)
4586 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4587 return getOnesVector(Op.getValueType(), DAG, dl);
4588 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4591 unsigned EVTBits = ExtVT.getSizeInBits();
4593 unsigned NumZero = 0;
4594 unsigned NumNonZero = 0;
4595 unsigned NonZeros = 0;
4596 bool IsAllConstants = true;
4597 SmallSet<SDValue, 8> Values;
4598 for (unsigned i = 0; i < NumElems; ++i) {
4599 SDValue Elt = Op.getOperand(i);
4600 if (Elt.getOpcode() == ISD::UNDEF)
4603 if (Elt.getOpcode() != ISD::Constant &&
4604 Elt.getOpcode() != ISD::ConstantFP)
4605 IsAllConstants = false;
4606 if (X86::isZeroNode(Elt))
4609 NonZeros |= (1 << i);
4614 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4615 if (NumNonZero == 0)
4616 return DAG.getUNDEF(VT);
4618 // Special case for single non-zero, non-undef, element.
4619 if (NumNonZero == 1) {
4620 unsigned Idx = CountTrailingZeros_32(NonZeros);
4621 SDValue Item = Op.getOperand(Idx);
4623 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4624 // the value are obviously zero, truncate the value to i32 and do the
4625 // insertion that way. Only do this if the value is non-constant or if the
4626 // value is a constant being inserted into element 0. It is cheaper to do
4627 // a constant pool load than it is to do a movd + shuffle.
4628 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4629 (!IsAllConstants || Idx == 0)) {
4630 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4632 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4633 EVT VecVT = MVT::v4i32;
4634 unsigned VecElts = 4;
4636 // Truncate the value (which may itself be a constant) to i32, and
4637 // convert it to a vector with movd (S2V+shuffle to zero extend).
4638 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4639 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4640 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4641 Subtarget->hasSSE2(), DAG);
4643 // Now we have our 32-bit value zero extended in the low element of
4644 // a vector. If Idx != 0, swizzle it into place.
4646 SmallVector<int, 4> Mask;
4647 Mask.push_back(Idx);
4648 for (unsigned i = 1; i != VecElts; ++i)
4650 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4651 DAG.getUNDEF(Item.getValueType()),
4654 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4658 // If we have a constant or non-constant insertion into the low element of
4659 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4660 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4661 // depending on what the source datatype is.
4664 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4665 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4666 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4667 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4668 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4669 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4671 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4672 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4673 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4674 EVT MiddleVT = MVT::v4i32;
4675 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4676 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4677 Subtarget->hasSSE2(), DAG);
4678 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4682 // Is it a vector logical left shift?
4683 if (NumElems == 2 && Idx == 1 &&
4684 X86::isZeroNode(Op.getOperand(0)) &&
4685 !X86::isZeroNode(Op.getOperand(1))) {
4686 unsigned NumBits = VT.getSizeInBits();
4687 return getVShift(true, VT,
4688 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4689 VT, Op.getOperand(1)),
4690 NumBits/2, DAG, *this, dl);
4693 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4696 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4697 // is a non-constant being inserted into an element other than the low one,
4698 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4699 // movd/movss) to move this into the low element, then shuffle it into
4701 if (EVTBits == 32) {
4702 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4704 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4705 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4706 Subtarget->hasSSE2(), DAG);
4707 SmallVector<int, 8> MaskVec;
4708 for (unsigned i = 0; i < NumElems; i++)
4709 MaskVec.push_back(i == Idx ? 0 : 1);
4710 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4714 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4715 if (Values.size() == 1) {
4716 if (EVTBits == 32) {
4717 // Instead of a shuffle like this:
4718 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4719 // Check if it's possible to issue this instead.
4720 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4721 unsigned Idx = CountTrailingZeros_32(NonZeros);
4722 SDValue Item = Op.getOperand(Idx);
4723 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4724 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4729 // A vector full of immediates; various special cases are already
4730 // handled, so this is best done with a single constant-pool load.
4734 // Let legalizer expand 2-wide build_vectors.
4735 if (EVTBits == 64) {
4736 if (NumNonZero == 1) {
4737 // One half is zero or undef.
4738 unsigned Idx = CountTrailingZeros_32(NonZeros);
4739 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4740 Op.getOperand(Idx));
4741 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4742 Subtarget->hasSSE2(), DAG);
4747 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4748 if (EVTBits == 8 && NumElems == 16) {
4749 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4751 if (V.getNode()) return V;
4754 if (EVTBits == 16 && NumElems == 8) {
4755 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4757 if (V.getNode()) return V;
4760 // If element VT is == 32 bits, turn it into a number of shuffles.
4761 SmallVector<SDValue, 8> V;
4763 if (NumElems == 4 && NumZero > 0) {
4764 for (unsigned i = 0; i < 4; ++i) {
4765 bool isZero = !(NonZeros & (1 << i));
4767 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4769 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4772 for (unsigned i = 0; i < 2; ++i) {
4773 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4776 V[i] = V[i*2]; // Must be a zero vector.
4779 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4782 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4785 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4790 SmallVector<int, 8> MaskVec;
4791 bool Reverse = (NonZeros & 0x3) == 2;
4792 for (unsigned i = 0; i < 2; ++i)
4793 MaskVec.push_back(Reverse ? 1-i : i);
4794 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4795 for (unsigned i = 0; i < 2; ++i)
4796 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4797 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4800 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4801 // Check for a build vector of consecutive loads.
4802 for (unsigned i = 0; i < NumElems; ++i)
4803 V[i] = Op.getOperand(i);
4805 // Check for elements which are consecutive loads.
4806 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4810 // For SSE 4.1, use insertps to put the high elements into the low element.
4811 if (getSubtarget()->hasSSE41()) {
4813 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4814 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4816 Result = DAG.getUNDEF(VT);
4818 for (unsigned i = 1; i < NumElems; ++i) {
4819 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4820 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4821 Op.getOperand(i), DAG.getIntPtrConstant(i));
4826 // Otherwise, expand into a number of unpckl*, start by extending each of
4827 // our (non-undef) elements to the full vector width with the element in the
4828 // bottom slot of the vector (which generates no code for SSE).
4829 for (unsigned i = 0; i < NumElems; ++i) {
4830 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4831 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4833 V[i] = DAG.getUNDEF(VT);
4836 // Next, we iteratively mix elements, e.g. for v4f32:
4837 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4838 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4839 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4840 unsigned EltStride = NumElems >> 1;
4841 while (EltStride != 0) {
4842 for (unsigned i = 0; i < EltStride; ++i) {
4843 // If V[i+EltStride] is undef and this is the first round of mixing,
4844 // then it is safe to just drop this shuffle: V[i] is already in the
4845 // right place, the one element (since it's the first round) being
4846 // inserted as undef can be dropped. This isn't safe for successive
4847 // rounds because they will permute elements within both vectors.
4848 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4849 EltStride == NumElems/2)
4852 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4862 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4863 // We support concatenate two MMX registers and place them in a MMX
4864 // register. This is better than doing a stack convert.
4865 DebugLoc dl = Op.getDebugLoc();
4866 EVT ResVT = Op.getValueType();
4867 assert(Op.getNumOperands() == 2);
4868 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4869 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4871 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4872 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4873 InVec = Op.getOperand(1);
4874 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4875 unsigned NumElts = ResVT.getVectorNumElements();
4876 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4877 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4878 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4880 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4881 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4882 Mask[0] = 0; Mask[1] = 2;
4883 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4885 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4888 // v8i16 shuffles - Prefer shuffles in the following order:
4889 // 1. [all] pshuflw, pshufhw, optional move
4890 // 2. [ssse3] 1 x pshufb
4891 // 3. [ssse3] 2 x pshufb + 1 x por
4892 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4894 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4895 SelectionDAG &DAG) const {
4896 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4897 SDValue V1 = SVOp->getOperand(0);
4898 SDValue V2 = SVOp->getOperand(1);
4899 DebugLoc dl = SVOp->getDebugLoc();
4900 SmallVector<int, 8> MaskVals;
4902 // Determine if more than 1 of the words in each of the low and high quadwords
4903 // of the result come from the same quadword of one of the two inputs. Undef
4904 // mask values count as coming from any quadword, for better codegen.
4905 SmallVector<unsigned, 4> LoQuad(4);
4906 SmallVector<unsigned, 4> HiQuad(4);
4907 BitVector InputQuads(4);
4908 for (unsigned i = 0; i < 8; ++i) {
4909 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4910 int EltIdx = SVOp->getMaskElt(i);
4911 MaskVals.push_back(EltIdx);
4920 InputQuads.set(EltIdx / 4);
4923 int BestLoQuad = -1;
4924 unsigned MaxQuad = 1;
4925 for (unsigned i = 0; i < 4; ++i) {
4926 if (LoQuad[i] > MaxQuad) {
4928 MaxQuad = LoQuad[i];
4932 int BestHiQuad = -1;
4934 for (unsigned i = 0; i < 4; ++i) {
4935 if (HiQuad[i] > MaxQuad) {
4937 MaxQuad = HiQuad[i];
4941 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4942 // of the two input vectors, shuffle them into one input vector so only a
4943 // single pshufb instruction is necessary. If There are more than 2 input
4944 // quads, disable the next transformation since it does not help SSSE3.
4945 bool V1Used = InputQuads[0] || InputQuads[1];
4946 bool V2Used = InputQuads[2] || InputQuads[3];
4947 if (Subtarget->hasSSSE3()) {
4948 if (InputQuads.count() == 2 && V1Used && V2Used) {
4949 BestLoQuad = InputQuads.find_first();
4950 BestHiQuad = InputQuads.find_next(BestLoQuad);
4952 if (InputQuads.count() > 2) {
4958 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4959 // the shuffle mask. If a quad is scored as -1, that means that it contains
4960 // words from all 4 input quadwords.
4962 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4963 SmallVector<int, 8> MaskV;
4964 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4965 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4966 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4967 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4968 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4969 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4971 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4972 // source words for the shuffle, to aid later transformations.
4973 bool AllWordsInNewV = true;
4974 bool InOrder[2] = { true, true };
4975 for (unsigned i = 0; i != 8; ++i) {
4976 int idx = MaskVals[i];
4978 InOrder[i/4] = false;
4979 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4981 AllWordsInNewV = false;
4985 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4986 if (AllWordsInNewV) {
4987 for (int i = 0; i != 8; ++i) {
4988 int idx = MaskVals[i];
4991 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4992 if ((idx != i) && idx < 4)
4994 if ((idx != i) && idx > 3)
5003 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5004 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5005 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5006 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5007 unsigned TargetMask = 0;
5008 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5009 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5010 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5011 X86::getShufflePSHUFLWImmediate(NewV.getNode());
5012 V1 = NewV.getOperand(0);
5013 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5017 // If we have SSSE3, and all words of the result are from 1 input vector,
5018 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5019 // is present, fall back to case 4.
5020 if (Subtarget->hasSSSE3()) {
5021 SmallVector<SDValue,16> pshufbMask;
5023 // If we have elements from both input vectors, set the high bit of the
5024 // shuffle mask element to zero out elements that come from V2 in the V1
5025 // mask, and elements that come from V1 in the V2 mask, so that the two
5026 // results can be OR'd together.
5027 bool TwoInputs = V1Used && V2Used;
5028 for (unsigned i = 0; i != 8; ++i) {
5029 int EltIdx = MaskVals[i] * 2;
5030 if (TwoInputs && (EltIdx >= 16)) {
5031 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5032 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5035 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5036 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5038 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5039 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5040 DAG.getNode(ISD::BUILD_VECTOR, dl,
5041 MVT::v16i8, &pshufbMask[0], 16));
5043 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5045 // Calculate the shuffle mask for the second input, shuffle it, and
5046 // OR it with the first shuffled input.
5048 for (unsigned i = 0; i != 8; ++i) {
5049 int EltIdx = MaskVals[i] * 2;
5051 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5052 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5055 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5056 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5058 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5059 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5060 DAG.getNode(ISD::BUILD_VECTOR, dl,
5061 MVT::v16i8, &pshufbMask[0], 16));
5062 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5063 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5066 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5067 // and update MaskVals with new element order.
5068 BitVector InOrder(8);
5069 if (BestLoQuad >= 0) {
5070 SmallVector<int, 8> MaskV;
5071 for (int i = 0; i != 4; ++i) {
5072 int idx = MaskVals[i];
5074 MaskV.push_back(-1);
5076 } else if ((idx / 4) == BestLoQuad) {
5077 MaskV.push_back(idx & 3);
5080 MaskV.push_back(-1);
5083 for (unsigned i = 4; i != 8; ++i)
5085 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5088 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5089 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5091 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5095 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5096 // and update MaskVals with the new element order.
5097 if (BestHiQuad >= 0) {
5098 SmallVector<int, 8> MaskV;
5099 for (unsigned i = 0; i != 4; ++i)
5101 for (unsigned i = 4; i != 8; ++i) {
5102 int idx = MaskVals[i];
5104 MaskV.push_back(-1);
5106 } else if ((idx / 4) == BestHiQuad) {
5107 MaskV.push_back((idx & 3) + 4);
5110 MaskV.push_back(-1);
5113 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5116 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5117 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5119 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5123 // In case BestHi & BestLo were both -1, which means each quadword has a word
5124 // from each of the four input quadwords, calculate the InOrder bitvector now
5125 // before falling through to the insert/extract cleanup.
5126 if (BestLoQuad == -1 && BestHiQuad == -1) {
5128 for (int i = 0; i != 8; ++i)
5129 if (MaskVals[i] < 0 || MaskVals[i] == i)
5133 // The other elements are put in the right place using pextrw and pinsrw.
5134 for (unsigned i = 0; i != 8; ++i) {
5137 int EltIdx = MaskVals[i];
5140 SDValue ExtOp = (EltIdx < 8)
5141 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5142 DAG.getIntPtrConstant(EltIdx))
5143 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5144 DAG.getIntPtrConstant(EltIdx - 8));
5145 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5146 DAG.getIntPtrConstant(i));
5151 // v16i8 shuffles - Prefer shuffles in the following order:
5152 // 1. [ssse3] 1 x pshufb
5153 // 2. [ssse3] 2 x pshufb + 1 x por
5154 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5156 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5158 const X86TargetLowering &TLI) {
5159 SDValue V1 = SVOp->getOperand(0);
5160 SDValue V2 = SVOp->getOperand(1);
5161 DebugLoc dl = SVOp->getDebugLoc();
5162 SmallVector<int, 16> MaskVals;
5163 SVOp->getMask(MaskVals);
5165 // If we have SSSE3, case 1 is generated when all result bytes come from
5166 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5167 // present, fall back to case 3.
5168 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5171 for (unsigned i = 0; i < 16; ++i) {
5172 int EltIdx = MaskVals[i];
5181 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5182 if (TLI.getSubtarget()->hasSSSE3()) {
5183 SmallVector<SDValue,16> pshufbMask;
5185 // If all result elements are from one input vector, then only translate
5186 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5188 // Otherwise, we have elements from both input vectors, and must zero out
5189 // elements that come from V2 in the first mask, and V1 in the second mask
5190 // so that we can OR them together.
5191 bool TwoInputs = !(V1Only || V2Only);
5192 for (unsigned i = 0; i != 16; ++i) {
5193 int EltIdx = MaskVals[i];
5194 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5195 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5198 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5200 // If all the elements are from V2, assign it to V1 and return after
5201 // building the first pshufb.
5204 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5205 DAG.getNode(ISD::BUILD_VECTOR, dl,
5206 MVT::v16i8, &pshufbMask[0], 16));
5210 // Calculate the shuffle mask for the second input, shuffle it, and
5211 // OR it with the first shuffled input.
5213 for (unsigned i = 0; i != 16; ++i) {
5214 int EltIdx = MaskVals[i];
5216 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5219 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5221 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5222 DAG.getNode(ISD::BUILD_VECTOR, dl,
5223 MVT::v16i8, &pshufbMask[0], 16));
5224 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5227 // No SSSE3 - Calculate in place words and then fix all out of place words
5228 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5229 // the 16 different words that comprise the two doublequadword input vectors.
5230 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5231 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5232 SDValue NewV = V2Only ? V2 : V1;
5233 for (int i = 0; i != 8; ++i) {
5234 int Elt0 = MaskVals[i*2];
5235 int Elt1 = MaskVals[i*2+1];
5237 // This word of the result is all undef, skip it.
5238 if (Elt0 < 0 && Elt1 < 0)
5241 // This word of the result is already in the correct place, skip it.
5242 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5244 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5247 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5248 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5251 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5252 // using a single extract together, load it and store it.
5253 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5254 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5255 DAG.getIntPtrConstant(Elt1 / 2));
5256 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5257 DAG.getIntPtrConstant(i));
5261 // If Elt1 is defined, extract it from the appropriate source. If the
5262 // source byte is not also odd, shift the extracted word left 8 bits
5263 // otherwise clear the bottom 8 bits if we need to do an or.
5265 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5266 DAG.getIntPtrConstant(Elt1 / 2));
5267 if ((Elt1 & 1) == 0)
5268 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5270 TLI.getShiftAmountTy(InsElt.getValueType())));
5272 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5273 DAG.getConstant(0xFF00, MVT::i16));
5275 // If Elt0 is defined, extract it from the appropriate source. If the
5276 // source byte is not also even, shift the extracted word right 8 bits. If
5277 // Elt1 was also defined, OR the extracted values together before
5278 // inserting them in the result.
5280 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5281 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5282 if ((Elt0 & 1) != 0)
5283 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5285 TLI.getShiftAmountTy(InsElt0.getValueType())));
5287 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5288 DAG.getConstant(0x00FF, MVT::i16));
5289 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5292 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5293 DAG.getIntPtrConstant(i));
5295 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5298 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5299 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5300 /// done when every pair / quad of shuffle mask elements point to elements in
5301 /// the right sequence. e.g.
5302 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5304 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5305 SelectionDAG &DAG, DebugLoc dl) {
5306 EVT VT = SVOp->getValueType(0);
5307 SDValue V1 = SVOp->getOperand(0);
5308 SDValue V2 = SVOp->getOperand(1);
5309 unsigned NumElems = VT.getVectorNumElements();
5310 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5312 switch (VT.getSimpleVT().SimpleTy) {
5313 default: assert(false && "Unexpected!");
5314 case MVT::v4f32: NewVT = MVT::v2f64; break;
5315 case MVT::v4i32: NewVT = MVT::v2i64; break;
5316 case MVT::v8i16: NewVT = MVT::v4i32; break;
5317 case MVT::v16i8: NewVT = MVT::v4i32; break;
5320 int Scale = NumElems / NewWidth;
5321 SmallVector<int, 8> MaskVec;
5322 for (unsigned i = 0; i < NumElems; i += Scale) {
5324 for (int j = 0; j < Scale; ++j) {
5325 int EltIdx = SVOp->getMaskElt(i+j);
5329 StartIdx = EltIdx - (EltIdx % Scale);
5330 if (EltIdx != StartIdx + j)
5334 MaskVec.push_back(-1);
5336 MaskVec.push_back(StartIdx / Scale);
5339 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5340 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5341 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5344 /// getVZextMovL - Return a zero-extending vector move low node.
5346 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5347 SDValue SrcOp, SelectionDAG &DAG,
5348 const X86Subtarget *Subtarget, DebugLoc dl) {
5349 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5350 LoadSDNode *LD = NULL;
5351 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5352 LD = dyn_cast<LoadSDNode>(SrcOp);
5354 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5356 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5357 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5358 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5359 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5360 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5362 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5363 return DAG.getNode(ISD::BITCAST, dl, VT,
5364 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5365 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5373 return DAG.getNode(ISD::BITCAST, dl, VT,
5374 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5375 DAG.getNode(ISD::BITCAST, dl,
5379 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
5380 /// 4 elements, and match them with several different shuffle types.
5382 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5383 SDValue V1 = SVOp->getOperand(0);
5384 SDValue V2 = SVOp->getOperand(1);
5385 DebugLoc dl = SVOp->getDebugLoc();
5386 EVT VT = SVOp->getValueType(0);
5388 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
5390 SmallVector<std::pair<int, int>, 8> Locs;
5392 SmallVector<int, 8> Mask1(4U, -1);
5393 SmallVector<int, 8> PermMask;
5394 SVOp->getMask(PermMask);
5398 for (unsigned i = 0; i != 4; ++i) {
5399 int Idx = PermMask[i];
5401 Locs[i] = std::make_pair(-1, -1);
5403 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5405 Locs[i] = std::make_pair(0, NumLo);
5409 Locs[i] = std::make_pair(1, NumHi);
5411 Mask1[2+NumHi] = Idx;
5417 if (NumLo <= 2 && NumHi <= 2) {
5418 // If no more than two elements come from either vector. This can be
5419 // implemented with two shuffles. First shuffle gather the elements.
5420 // The second shuffle, which takes the first shuffle as both of its
5421 // vector operands, put the elements into the right order.
5422 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5424 SmallVector<int, 8> Mask2(4U, -1);
5426 for (unsigned i = 0; i != 4; ++i) {
5427 if (Locs[i].first == -1)
5430 unsigned Idx = (i < 2) ? 0 : 4;
5431 Idx += Locs[i].first * 2 + Locs[i].second;
5436 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5437 } else if (NumLo == 3 || NumHi == 3) {
5438 // Otherwise, we must have three elements from one vector, call it X, and
5439 // one element from the other, call it Y. First, use a shufps to build an
5440 // intermediate vector with the one element from Y and the element from X
5441 // that will be in the same half in the final destination (the indexes don't
5442 // matter). Then, use a shufps to build the final vector, taking the half
5443 // containing the element from Y from the intermediate, and the other half
5446 // Normalize it so the 3 elements come from V1.
5447 CommuteVectorShuffleMask(PermMask, VT);
5451 // Find the element from V2.
5453 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5454 int Val = PermMask[HiIndex];
5461 Mask1[0] = PermMask[HiIndex];
5463 Mask1[2] = PermMask[HiIndex^1];
5465 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5468 Mask1[0] = PermMask[0];
5469 Mask1[1] = PermMask[1];
5470 Mask1[2] = HiIndex & 1 ? 6 : 4;
5471 Mask1[3] = HiIndex & 1 ? 4 : 6;
5472 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5474 Mask1[0] = HiIndex & 1 ? 2 : 0;
5475 Mask1[1] = HiIndex & 1 ? 0 : 2;
5476 Mask1[2] = PermMask[2];
5477 Mask1[3] = PermMask[3];
5482 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5486 // Break it into (shuffle shuffle_hi, shuffle_lo).
5489 SmallVector<int,8> LoMask(4U, -1);
5490 SmallVector<int,8> HiMask(4U, -1);
5492 SmallVector<int,8> *MaskPtr = &LoMask;
5493 unsigned MaskIdx = 0;
5496 for (unsigned i = 0; i != 4; ++i) {
5503 int Idx = PermMask[i];
5505 Locs[i] = std::make_pair(-1, -1);
5506 } else if (Idx < 4) {
5507 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5508 (*MaskPtr)[LoIdx] = Idx;
5511 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5512 (*MaskPtr)[HiIdx] = Idx;
5517 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5518 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5519 SmallVector<int, 8> MaskOps;
5520 for (unsigned i = 0; i != 4; ++i) {
5521 if (Locs[i].first == -1) {
5522 MaskOps.push_back(-1);
5524 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5525 MaskOps.push_back(Idx);
5528 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5531 static bool MayFoldVectorLoad(SDValue V) {
5532 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5533 V = V.getOperand(0);
5534 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5535 V = V.getOperand(0);
5541 // FIXME: the version above should always be used. Since there's
5542 // a bug where several vector shuffles can't be folded because the
5543 // DAG is not updated during lowering and a node claims to have two
5544 // uses while it only has one, use this version, and let isel match
5545 // another instruction if the load really happens to have more than
5546 // one use. Remove this version after this bug get fixed.
5547 // rdar://8434668, PR8156
5548 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5549 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5550 V = V.getOperand(0);
5551 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5552 V = V.getOperand(0);
5553 if (ISD::isNormalLoad(V.getNode()))
5558 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5559 /// a vector extract, and if both can be later optimized into a single load.
5560 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5561 /// here because otherwise a target specific shuffle node is going to be
5562 /// emitted for this shuffle, and the optimization not done.
5563 /// FIXME: This is probably not the best approach, but fix the problem
5564 /// until the right path is decided.
5566 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5567 const TargetLowering &TLI) {
5568 EVT VT = V.getValueType();
5569 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5571 // Be sure that the vector shuffle is present in a pattern like this:
5572 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5576 SDNode *N = *V.getNode()->use_begin();
5577 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5580 SDValue EltNo = N->getOperand(1);
5581 if (!isa<ConstantSDNode>(EltNo))
5584 // If the bit convert changed the number of elements, it is unsafe
5585 // to examine the mask.
5586 bool HasShuffleIntoBitcast = false;
5587 if (V.getOpcode() == ISD::BITCAST) {
5588 EVT SrcVT = V.getOperand(0).getValueType();
5589 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5591 V = V.getOperand(0);
5592 HasShuffleIntoBitcast = true;
5595 // Select the input vector, guarding against out of range extract vector.
5596 unsigned NumElems = VT.getVectorNumElements();
5597 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5598 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5599 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5601 // Skip one more bit_convert if necessary
5602 if (V.getOpcode() == ISD::BITCAST)
5603 V = V.getOperand(0);
5605 if (ISD::isNormalLoad(V.getNode())) {
5606 // Is the original load suitable?
5607 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5609 // FIXME: avoid the multi-use bug that is preventing lots of
5610 // of foldings to be detected, this is still wrong of course, but
5611 // give the temporary desired behavior, and if it happens that
5612 // the load has real more uses, during isel it will not fold, and
5613 // will generate poor code.
5614 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5617 if (!HasShuffleIntoBitcast)
5620 // If there's a bitcast before the shuffle, check if the load type and
5621 // alignment is valid.
5622 unsigned Align = LN0->getAlignment();
5624 TLI.getTargetData()->getABITypeAlignment(
5625 VT.getTypeForEVT(*DAG.getContext()));
5627 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5635 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5636 EVT VT = Op.getValueType();
5638 // Canonizalize to v2f64.
5639 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5640 return DAG.getNode(ISD::BITCAST, dl, VT,
5641 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5646 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5648 SDValue V1 = Op.getOperand(0);
5649 SDValue V2 = Op.getOperand(1);
5650 EVT VT = Op.getValueType();
5652 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5654 if (HasSSE2 && VT == MVT::v2f64)
5655 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5658 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5662 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5663 SDValue V1 = Op.getOperand(0);
5664 SDValue V2 = Op.getOperand(1);
5665 EVT VT = Op.getValueType();
5667 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5668 "unsupported shuffle type");
5670 if (V2.getOpcode() == ISD::UNDEF)
5674 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5678 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5679 SDValue V1 = Op.getOperand(0);
5680 SDValue V2 = Op.getOperand(1);
5681 EVT VT = Op.getValueType();
5682 unsigned NumElems = VT.getVectorNumElements();
5684 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5685 // operand of these instructions is only memory, so check if there's a
5686 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5688 bool CanFoldLoad = false;
5690 // Trivial case, when V2 comes from a load.
5691 if (MayFoldVectorLoad(V2))
5694 // When V1 is a load, it can be folded later into a store in isel, example:
5695 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5697 // (MOVLPSmr addr:$src1, VR128:$src2)
5698 // So, recognize this potential and also use MOVLPS or MOVLPD
5699 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5702 // Both of them can't be memory operations though.
5703 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5704 CanFoldLoad = false;
5707 if (HasSSE2 && NumElems == 2)
5708 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5711 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5714 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5715 // movl and movlp will both match v2i64, but v2i64 is never matched by
5716 // movl earlier because we make it strict to avoid messing with the movlp load
5717 // folding logic (see the code above getMOVLP call). Match it here then,
5718 // this is horrible, but will stay like this until we move all shuffle
5719 // matching to x86 specific nodes. Note that for the 1st condition all
5720 // types are matched with movsd.
5721 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5722 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5724 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5727 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5729 // Invert the operand order and use SHUFPS to match it.
5730 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5731 X86::getShuffleSHUFImmediate(SVOp), DAG);
5734 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5735 switch(VT.getSimpleVT().SimpleTy) {
5736 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5737 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5739 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5741 return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5742 case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5743 case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5744 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5745 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5747 llvm_unreachable("Unknown type for unpckl");
5752 static inline unsigned getUNPCKHOpcode(EVT VT) {
5753 switch(VT.getSimpleVT().SimpleTy) {
5754 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5755 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5756 case MVT::v4f32: return X86ISD::UNPCKHPS;
5757 case MVT::v2f64: return X86ISD::UNPCKHPD;
5758 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5759 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5761 llvm_unreachable("Unknown type for unpckh");
5767 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5768 const TargetLowering &TLI,
5769 const X86Subtarget *Subtarget) {
5770 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5771 EVT VT = Op.getValueType();
5772 DebugLoc dl = Op.getDebugLoc();
5773 SDValue V1 = Op.getOperand(0);
5774 SDValue V2 = Op.getOperand(1);
5776 if (isZeroShuffle(SVOp))
5777 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5779 // Handle splat operations
5780 if (SVOp->isSplat()) {
5781 unsigned NumElem = VT.getVectorNumElements();
5782 // Special case, this is the only place now where it's allowed to return
5783 // a vector_shuffle operation without using a target specific node, because
5784 // *hopefully* it will be optimized away by the dag combiner. FIXME: should
5785 // this be moved to DAGCombine instead?
5786 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5789 // Handle splats by matching through known masks
5790 if ((VT.is128BitVector() && NumElem <= 4) ||
5791 (VT.is256BitVector() && NumElem <= 8))
5794 // All i16 and i8 vector types can't be used directly by a generic shuffle
5795 // instruction because the target has no such instruction. Generate shuffles
5796 // which repeat i16 and i8 several times until they fit in i32, and then can
5797 // be manipulated by target suported shuffles. After the insertion of the
5798 // necessary shuffles, the result is bitcasted back to v4f32 or v8f32.
5799 return PromoteSplat(SVOp, DAG);
5802 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5804 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5805 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5806 if (NewOp.getNode())
5807 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5808 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5809 // FIXME: Figure out a cleaner way to do this.
5810 // Try to make use of movq to zero out the top part.
5811 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5812 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5813 if (NewOp.getNode()) {
5814 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5815 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5816 DAG, Subtarget, dl);
5818 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5819 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5820 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5821 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5822 DAG, Subtarget, dl);
5829 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5830 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5831 SDValue V1 = Op.getOperand(0);
5832 SDValue V2 = Op.getOperand(1);
5833 EVT VT = Op.getValueType();
5834 DebugLoc dl = Op.getDebugLoc();
5835 unsigned NumElems = VT.getVectorNumElements();
5836 bool isMMX = VT.getSizeInBits() == 64;
5837 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5838 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5839 bool V1IsSplat = false;
5840 bool V2IsSplat = false;
5841 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5842 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5843 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5844 MachineFunction &MF = DAG.getMachineFunction();
5845 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5847 // Shuffle operations on MMX not supported.
5851 // Vector shuffle lowering takes 3 steps:
5853 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5854 // narrowing and commutation of operands should be handled.
5855 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5857 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5858 // so the shuffle can be broken into other shuffles and the legalizer can
5859 // try the lowering again.
5861 // The general ideia is that no vector_shuffle operation should be left to
5862 // be matched during isel, all of them must be converted to a target specific
5865 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5866 // narrowing and commutation of operands should be handled. The actual code
5867 // doesn't include all of those, work in progress...
5868 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5869 if (NewOp.getNode())
5872 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5873 // unpckh_undef). Only use pshufd if speed is more important than size.
5874 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5875 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5876 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5877 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5878 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5879 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5881 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5882 RelaxedMayFoldVectorLoad(V1))
5883 return getMOVDDup(Op, dl, V1, DAG);
5885 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5886 return getMOVHighToLow(Op, dl, DAG);
5888 // Use to match splats
5889 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5890 (VT == MVT::v2f64 || VT == MVT::v2i64))
5891 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5893 if (X86::isPSHUFDMask(SVOp)) {
5894 // The actual implementation will match the mask in the if above and then
5895 // during isel it can match several different instructions, not only pshufd
5896 // as its name says, sad but true, emulate the behavior for now...
5897 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5898 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5900 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5902 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5903 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5905 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5906 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5909 if (VT == MVT::v4f32)
5910 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5914 // Check if this can be converted into a logical shift.
5915 bool isLeft = false;
5918 bool isShift = getSubtarget()->hasSSE2() &&
5919 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5920 if (isShift && ShVal.hasOneUse()) {
5921 // If the shifted value has multiple uses, it may be cheaper to use
5922 // v_set0 + movlhps or movhlps, etc.
5923 EVT EltVT = VT.getVectorElementType();
5924 ShAmt *= EltVT.getSizeInBits();
5925 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5928 if (X86::isMOVLMask(SVOp)) {
5931 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5932 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5933 if (!X86::isMOVLPMask(SVOp)) {
5934 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5935 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5937 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5938 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5942 // FIXME: fold these into legal mask.
5943 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5944 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5946 if (X86::isMOVHLPSMask(SVOp))
5947 return getMOVHighToLow(Op, dl, DAG);
5949 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5950 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5952 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5953 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5955 if (X86::isMOVLPMask(SVOp))
5956 return getMOVLP(Op, dl, DAG, HasSSE2);
5958 if (ShouldXformToMOVHLPS(SVOp) ||
5959 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5960 return CommuteVectorShuffle(SVOp, DAG);
5963 // No better options. Use a vshl / vsrl.
5964 EVT EltVT = VT.getVectorElementType();
5965 ShAmt *= EltVT.getSizeInBits();
5966 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5969 bool Commuted = false;
5970 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5971 // 1,1,1,1 -> v8i16 though.
5972 V1IsSplat = isSplatVector(V1.getNode());
5973 V2IsSplat = isSplatVector(V2.getNode());
5975 // Canonicalize the splat or undef, if present, to be on the RHS.
5976 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5977 Op = CommuteVectorShuffle(SVOp, DAG);
5978 SVOp = cast<ShuffleVectorSDNode>(Op);
5979 V1 = SVOp->getOperand(0);
5980 V2 = SVOp->getOperand(1);
5981 std::swap(V1IsSplat, V2IsSplat);
5982 std::swap(V1IsUndef, V2IsUndef);
5986 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5987 // Shuffling low element of v1 into undef, just return v1.
5990 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5991 // the instruction selector will not match, so get a canonical MOVL with
5992 // swapped operands to undo the commute.
5993 return getMOVL(DAG, dl, VT, V2, V1);
5996 if (X86::isUNPCKLMask(SVOp))
5997 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5998 dl, VT, V1, V2, DAG);
6000 if (X86::isUNPCKHMask(SVOp))
6001 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6004 // Normalize mask so all entries that point to V2 points to its first
6005 // element then try to match unpck{h|l} again. If match, return a
6006 // new vector_shuffle with the corrected mask.
6007 SDValue NewMask = NormalizeMask(SVOp, DAG);
6008 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6009 if (NSVOp != SVOp) {
6010 if (X86::isUNPCKLMask(NSVOp, true)) {
6012 } else if (X86::isUNPCKHMask(NSVOp, true)) {
6019 // Commute is back and try unpck* again.
6020 // FIXME: this seems wrong.
6021 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6022 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6024 if (X86::isUNPCKLMask(NewSVOp))
6025 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
6026 dl, VT, V2, V1, DAG);
6028 if (X86::isUNPCKHMask(NewSVOp))
6029 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6032 // Normalize the node to match x86 shuffle ops if needed
6033 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6034 return CommuteVectorShuffle(SVOp, DAG);
6036 // The checks below are all present in isShuffleMaskLegal, but they are
6037 // inlined here right now to enable us to directly emit target specific
6038 // nodes, and remove one by one until they don't return Op anymore.
6039 SmallVector<int, 16> M;
6042 if (isPALIGNRMask(M, VT, HasSSSE3))
6043 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6044 X86::getShufflePALIGNRImmediate(SVOp),
6047 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6048 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6049 if (VT == MVT::v2f64) {
6050 X86ISD::NodeType Opcode =
6051 getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
6052 return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
6054 if (VT == MVT::v2i64)
6055 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6058 if (isPSHUFHWMask(M, VT))
6059 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6060 X86::getShufflePSHUFHWImmediate(SVOp),
6063 if (isPSHUFLWMask(M, VT))
6064 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6065 X86::getShufflePSHUFLWImmediate(SVOp),
6068 if (isSHUFPMask(M, VT)) {
6069 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6070 if (VT == MVT::v4f32 || VT == MVT::v4i32)
6071 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
6073 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6074 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
6078 if (X86::isUNPCKL_v_undef_Mask(SVOp))
6079 if (VT != MVT::v2i64 && VT != MVT::v2f64)
6080 return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
6081 dl, VT, V1, V1, DAG);
6082 if (X86::isUNPCKH_v_undef_Mask(SVOp))
6083 if (VT != MVT::v2i64 && VT != MVT::v2f64)
6084 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6086 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6087 if (VT == MVT::v8i16) {
6088 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6089 if (NewOp.getNode())
6093 if (VT == MVT::v16i8) {
6094 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6095 if (NewOp.getNode())
6099 // Handle all 128-bit wide vectors with 4 elements, and match them with
6100 // several different shuffle types.
6101 if (NumElems == 4 && VT.getSizeInBits() == 128)
6102 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6104 // Handle VPERMIL permutations
6105 if (isVPERMILMask(M, VT)) {
6106 unsigned TargetMask = getShuffleVPERMILImmediate(SVOp);
6107 if (VT == MVT::v8f32)
6108 return getTargetShuffleNode(X86ISD::VPERMIL, dl, VT, V1, TargetMask, DAG);
6115 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6116 SelectionDAG &DAG) const {
6117 EVT VT = Op.getValueType();
6118 DebugLoc dl = Op.getDebugLoc();
6119 if (VT.getSizeInBits() == 8) {
6120 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6121 Op.getOperand(0), Op.getOperand(1));
6122 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6123 DAG.getValueType(VT));
6124 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6125 } else if (VT.getSizeInBits() == 16) {
6126 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6127 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6129 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6130 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6131 DAG.getNode(ISD::BITCAST, dl,
6135 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6136 Op.getOperand(0), Op.getOperand(1));
6137 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6138 DAG.getValueType(VT));
6139 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6140 } else if (VT == MVT::f32) {
6141 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6142 // the result back to FR32 register. It's only worth matching if the
6143 // result has a single use which is a store or a bitcast to i32. And in
6144 // the case of a store, it's not worth it if the index is a constant 0,
6145 // because a MOVSSmr can be used instead, which is smaller and faster.
6146 if (!Op.hasOneUse())
6148 SDNode *User = *Op.getNode()->use_begin();
6149 if ((User->getOpcode() != ISD::STORE ||
6150 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6151 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6152 (User->getOpcode() != ISD::BITCAST ||
6153 User->getValueType(0) != MVT::i32))
6155 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6156 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6159 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6160 } else if (VT == MVT::i32) {
6161 // ExtractPS works with constant index.
6162 if (isa<ConstantSDNode>(Op.getOperand(1)))
6170 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6171 SelectionDAG &DAG) const {
6172 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6175 SDValue Vec = Op.getOperand(0);
6176 EVT VecVT = Vec.getValueType();
6178 // If this is a 256-bit vector result, first extract the 128-bit
6179 // vector and then extract from the 128-bit vector.
6180 if (VecVT.getSizeInBits() > 128) {
6181 DebugLoc dl = Op.getNode()->getDebugLoc();
6182 unsigned NumElems = VecVT.getVectorNumElements();
6183 SDValue Idx = Op.getOperand(1);
6185 if (!isa<ConstantSDNode>(Idx))
6188 unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6189 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6191 // Get the 128-bit vector.
6192 bool Upper = IdxVal >= ExtractNumElems;
6193 Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6196 SDValue ScaledIdx = Idx;
6198 ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6199 DAG.getConstant(ExtractNumElems,
6200 Idx.getValueType()));
6201 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6205 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6207 if (Subtarget->hasSSE41()) {
6208 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6213 EVT VT = Op.getValueType();
6214 DebugLoc dl = Op.getDebugLoc();
6215 // TODO: handle v16i8.
6216 if (VT.getSizeInBits() == 16) {
6217 SDValue Vec = Op.getOperand(0);
6218 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6220 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6221 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6222 DAG.getNode(ISD::BITCAST, dl,
6225 // Transform it so it match pextrw which produces a 32-bit result.
6226 EVT EltVT = MVT::i32;
6227 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6228 Op.getOperand(0), Op.getOperand(1));
6229 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6230 DAG.getValueType(VT));
6231 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6232 } else if (VT.getSizeInBits() == 32) {
6233 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6237 // SHUFPS the element to the lowest double word, then movss.
6238 int Mask[4] = { Idx, -1, -1, -1 };
6239 EVT VVT = Op.getOperand(0).getValueType();
6240 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6241 DAG.getUNDEF(VVT), Mask);
6242 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6243 DAG.getIntPtrConstant(0));
6244 } else if (VT.getSizeInBits() == 64) {
6245 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6246 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6247 // to match extract_elt for f64.
6248 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6252 // UNPCKHPD the element to the lowest double word, then movsd.
6253 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6254 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6255 int Mask[2] = { 1, -1 };
6256 EVT VVT = Op.getOperand(0).getValueType();
6257 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6258 DAG.getUNDEF(VVT), Mask);
6259 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6260 DAG.getIntPtrConstant(0));
6267 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6268 SelectionDAG &DAG) const {
6269 EVT VT = Op.getValueType();
6270 EVT EltVT = VT.getVectorElementType();
6271 DebugLoc dl = Op.getDebugLoc();
6273 SDValue N0 = Op.getOperand(0);
6274 SDValue N1 = Op.getOperand(1);
6275 SDValue N2 = Op.getOperand(2);
6277 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6278 isa<ConstantSDNode>(N2)) {
6280 if (VT == MVT::v8i16)
6281 Opc = X86ISD::PINSRW;
6282 else if (VT == MVT::v16i8)
6283 Opc = X86ISD::PINSRB;
6285 Opc = X86ISD::PINSRB;
6287 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6289 if (N1.getValueType() != MVT::i32)
6290 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6291 if (N2.getValueType() != MVT::i32)
6292 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6293 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6294 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6295 // Bits [7:6] of the constant are the source select. This will always be
6296 // zero here. The DAG Combiner may combine an extract_elt index into these
6297 // bits. For example (insert (extract, 3), 2) could be matched by putting
6298 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6299 // Bits [5:4] of the constant are the destination select. This is the
6300 // value of the incoming immediate.
6301 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6302 // combine either bitwise AND or insert of float 0.0 to set these bits.
6303 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6304 // Create this as a scalar to vector..
6305 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6306 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6307 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6308 // PINSR* works with constant index.
6315 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6316 EVT VT = Op.getValueType();
6317 EVT EltVT = VT.getVectorElementType();
6319 DebugLoc dl = Op.getDebugLoc();
6320 SDValue N0 = Op.getOperand(0);
6321 SDValue N1 = Op.getOperand(1);
6322 SDValue N2 = Op.getOperand(2);
6324 // If this is a 256-bit vector result, first insert into a 128-bit
6325 // vector and then insert into the 256-bit vector.
6326 if (VT.getSizeInBits() > 128) {
6327 if (!isa<ConstantSDNode>(N2))
6330 // Get the 128-bit vector.
6331 unsigned NumElems = VT.getVectorNumElements();
6332 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6333 bool Upper = IdxVal >= NumElems / 2;
6335 SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6338 SDValue ScaledN2 = N2;
6340 ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6341 DAG.getConstant(NumElems /
6342 (VT.getSizeInBits() / 128),
6343 N2.getValueType()));
6344 Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6347 // Insert the 128-bit vector
6348 // FIXME: Why UNDEF?
6349 return Insert128BitVector(N0, Op, N2, DAG, dl);
6352 if (Subtarget->hasSSE41())
6353 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6355 if (EltVT == MVT::i8)
6358 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6359 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6360 // as its second argument.
6361 if (N1.getValueType() != MVT::i32)
6362 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6363 if (N2.getValueType() != MVT::i32)
6364 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6365 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6371 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6372 LLVMContext *Context = DAG.getContext();
6373 DebugLoc dl = Op.getDebugLoc();
6374 EVT OpVT = Op.getValueType();
6376 // If this is a 256-bit vector result, first insert into a 128-bit
6377 // vector and then insert into the 256-bit vector.
6378 if (OpVT.getSizeInBits() > 128) {
6379 // Insert into a 128-bit vector.
6380 EVT VT128 = EVT::getVectorVT(*Context,
6381 OpVT.getVectorElementType(),
6382 OpVT.getVectorNumElements() / 2);
6384 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6386 // Insert the 128-bit vector.
6387 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6388 DAG.getConstant(0, MVT::i32),
6392 if (Op.getValueType() == MVT::v1i64 &&
6393 Op.getOperand(0).getValueType() == MVT::i64)
6394 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6396 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6397 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6398 "Expected an SSE type!");
6399 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6400 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6403 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
6404 // a simple subregister reference or explicit instructions to grab
6405 // upper bits of a vector.
6407 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6408 if (Subtarget->hasAVX()) {
6409 DebugLoc dl = Op.getNode()->getDebugLoc();
6410 SDValue Vec = Op.getNode()->getOperand(0);
6411 SDValue Idx = Op.getNode()->getOperand(1);
6413 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6414 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6415 return Extract128BitVector(Vec, Idx, DAG, dl);
6421 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
6422 // simple superregister reference or explicit instructions to insert
6423 // the upper bits of a vector.
6425 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6426 if (Subtarget->hasAVX()) {
6427 DebugLoc dl = Op.getNode()->getDebugLoc();
6428 SDValue Vec = Op.getNode()->getOperand(0);
6429 SDValue SubVec = Op.getNode()->getOperand(1);
6430 SDValue Idx = Op.getNode()->getOperand(2);
6432 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6433 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6434 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6440 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6441 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6442 // one of the above mentioned nodes. It has to be wrapped because otherwise
6443 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6444 // be used to form addressing mode. These wrapped nodes will be selected
6447 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6448 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6450 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6452 unsigned char OpFlag = 0;
6453 unsigned WrapperKind = X86ISD::Wrapper;
6454 CodeModel::Model M = getTargetMachine().getCodeModel();
6456 if (Subtarget->isPICStyleRIPRel() &&
6457 (M == CodeModel::Small || M == CodeModel::Kernel))
6458 WrapperKind = X86ISD::WrapperRIP;
6459 else if (Subtarget->isPICStyleGOT())
6460 OpFlag = X86II::MO_GOTOFF;
6461 else if (Subtarget->isPICStyleStubPIC())
6462 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6464 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6466 CP->getOffset(), OpFlag);
6467 DebugLoc DL = CP->getDebugLoc();
6468 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6469 // With PIC, the address is actually $g + Offset.
6471 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6472 DAG.getNode(X86ISD::GlobalBaseReg,
6473 DebugLoc(), getPointerTy()),
6480 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6481 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6483 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6485 unsigned char OpFlag = 0;
6486 unsigned WrapperKind = X86ISD::Wrapper;
6487 CodeModel::Model M = getTargetMachine().getCodeModel();
6489 if (Subtarget->isPICStyleRIPRel() &&
6490 (M == CodeModel::Small || M == CodeModel::Kernel))
6491 WrapperKind = X86ISD::WrapperRIP;
6492 else if (Subtarget->isPICStyleGOT())
6493 OpFlag = X86II::MO_GOTOFF;
6494 else if (Subtarget->isPICStyleStubPIC())
6495 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6497 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6499 DebugLoc DL = JT->getDebugLoc();
6500 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6502 // With PIC, the address is actually $g + Offset.
6504 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6505 DAG.getNode(X86ISD::GlobalBaseReg,
6506 DebugLoc(), getPointerTy()),
6513 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6514 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6516 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6518 unsigned char OpFlag = 0;
6519 unsigned WrapperKind = X86ISD::Wrapper;
6520 CodeModel::Model M = getTargetMachine().getCodeModel();
6522 if (Subtarget->isPICStyleRIPRel() &&
6523 (M == CodeModel::Small || M == CodeModel::Kernel))
6524 WrapperKind = X86ISD::WrapperRIP;
6525 else if (Subtarget->isPICStyleGOT())
6526 OpFlag = X86II::MO_GOTOFF;
6527 else if (Subtarget->isPICStyleStubPIC())
6528 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6530 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6532 DebugLoc DL = Op.getDebugLoc();
6533 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6536 // With PIC, the address is actually $g + Offset.
6537 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6538 !Subtarget->is64Bit()) {
6539 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6540 DAG.getNode(X86ISD::GlobalBaseReg,
6541 DebugLoc(), getPointerTy()),
6549 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6550 // Create the TargetBlockAddressAddress node.
6551 unsigned char OpFlags =
6552 Subtarget->ClassifyBlockAddressReference();
6553 CodeModel::Model M = getTargetMachine().getCodeModel();
6554 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6555 DebugLoc dl = Op.getDebugLoc();
6556 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6557 /*isTarget=*/true, OpFlags);
6559 if (Subtarget->isPICStyleRIPRel() &&
6560 (M == CodeModel::Small || M == CodeModel::Kernel))
6561 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6563 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6565 // With PIC, the address is actually $g + Offset.
6566 if (isGlobalRelativeToPICBase(OpFlags)) {
6567 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6568 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6576 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6578 SelectionDAG &DAG) const {
6579 // Create the TargetGlobalAddress node, folding in the constant
6580 // offset if it is legal.
6581 unsigned char OpFlags =
6582 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6583 CodeModel::Model M = getTargetMachine().getCodeModel();
6585 if (OpFlags == X86II::MO_NO_FLAG &&
6586 X86::isOffsetSuitableForCodeModel(Offset, M)) {
6587 // A direct static reference to a global.
6588 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6591 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6594 if (Subtarget->isPICStyleRIPRel() &&
6595 (M == CodeModel::Small || M == CodeModel::Kernel))
6596 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6598 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6600 // With PIC, the address is actually $g + Offset.
6601 if (isGlobalRelativeToPICBase(OpFlags)) {
6602 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6603 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6607 // For globals that require a load from a stub to get the address, emit the
6609 if (isGlobalStubReference(OpFlags))
6610 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6611 MachinePointerInfo::getGOT(), false, false, 0);
6613 // If there was a non-zero offset that we didn't fold, create an explicit
6616 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6617 DAG.getConstant(Offset, getPointerTy()));
6623 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6624 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6625 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6626 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6630 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6631 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6632 unsigned char OperandFlags) {
6633 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6634 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6635 DebugLoc dl = GA->getDebugLoc();
6636 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6637 GA->getValueType(0),
6641 SDValue Ops[] = { Chain, TGA, *InFlag };
6642 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6644 SDValue Ops[] = { Chain, TGA };
6645 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6648 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6649 MFI->setAdjustsStack(true);
6651 SDValue Flag = Chain.getValue(1);
6652 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6655 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6657 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6660 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6661 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6662 DAG.getNode(X86ISD::GlobalBaseReg,
6663 DebugLoc(), PtrVT), InFlag);
6664 InFlag = Chain.getValue(1);
6666 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6669 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6671 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6673 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6674 X86::RAX, X86II::MO_TLSGD);
6677 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6678 // "local exec" model.
6679 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6680 const EVT PtrVT, TLSModel::Model model,
6682 DebugLoc dl = GA->getDebugLoc();
6684 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6685 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6686 is64Bit ? 257 : 256));
6688 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6689 DAG.getIntPtrConstant(0),
6690 MachinePointerInfo(Ptr), false, false, 0);
6692 unsigned char OperandFlags = 0;
6693 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6695 unsigned WrapperKind = X86ISD::Wrapper;
6696 if (model == TLSModel::LocalExec) {
6697 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6698 } else if (is64Bit) {
6699 assert(model == TLSModel::InitialExec);
6700 OperandFlags = X86II::MO_GOTTPOFF;
6701 WrapperKind = X86ISD::WrapperRIP;
6703 assert(model == TLSModel::InitialExec);
6704 OperandFlags = X86II::MO_INDNTPOFF;
6707 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6709 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6710 GA->getValueType(0),
6711 GA->getOffset(), OperandFlags);
6712 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6714 if (model == TLSModel::InitialExec)
6715 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6716 MachinePointerInfo::getGOT(), false, false, 0);
6718 // The address of the thread local variable is the add of the thread
6719 // pointer with the offset of the variable.
6720 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6724 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6726 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6727 const GlobalValue *GV = GA->getGlobal();
6729 if (Subtarget->isTargetELF()) {
6730 // TODO: implement the "local dynamic" model
6731 // TODO: implement the "initial exec"model for pic executables
6733 // If GV is an alias then use the aliasee for determining
6734 // thread-localness.
6735 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6736 GV = GA->resolveAliasedGlobal(false);
6738 TLSModel::Model model
6739 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6742 case TLSModel::GeneralDynamic:
6743 case TLSModel::LocalDynamic: // not implemented
6744 if (Subtarget->is64Bit())
6745 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6746 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6748 case TLSModel::InitialExec:
6749 case TLSModel::LocalExec:
6750 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6751 Subtarget->is64Bit());
6753 } else if (Subtarget->isTargetDarwin()) {
6754 // Darwin only has one model of TLS. Lower to that.
6755 unsigned char OpFlag = 0;
6756 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6757 X86ISD::WrapperRIP : X86ISD::Wrapper;
6759 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6761 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6762 !Subtarget->is64Bit();
6764 OpFlag = X86II::MO_TLVP_PIC_BASE;
6766 OpFlag = X86II::MO_TLVP;
6767 DebugLoc DL = Op.getDebugLoc();
6768 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6769 GA->getValueType(0),
6770 GA->getOffset(), OpFlag);
6771 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6773 // With PIC32, the address is actually $g + Offset.
6775 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6776 DAG.getNode(X86ISD::GlobalBaseReg,
6777 DebugLoc(), getPointerTy()),
6780 // Lowering the machine isd will make sure everything is in the right
6782 SDValue Chain = DAG.getEntryNode();
6783 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6784 SDValue Args[] = { Chain, Offset };
6785 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6787 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6788 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6789 MFI->setAdjustsStack(true);
6791 // And our return value (tls address) is in the standard call return value
6793 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6794 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6798 "TLS not implemented for this target.");
6800 llvm_unreachable("Unreachable");
6805 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6806 /// take a 2 x i32 value to shift plus a shift amount.
6807 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6808 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6809 EVT VT = Op.getValueType();
6810 unsigned VTBits = VT.getSizeInBits();
6811 DebugLoc dl = Op.getDebugLoc();
6812 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6813 SDValue ShOpLo = Op.getOperand(0);
6814 SDValue ShOpHi = Op.getOperand(1);
6815 SDValue ShAmt = Op.getOperand(2);
6816 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6817 DAG.getConstant(VTBits - 1, MVT::i8))
6818 : DAG.getConstant(0, VT);
6821 if (Op.getOpcode() == ISD::SHL_PARTS) {
6822 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6823 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6825 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6826 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6829 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6830 DAG.getConstant(VTBits, MVT::i8));
6831 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6832 AndNode, DAG.getConstant(0, MVT::i8));
6835 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6836 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6837 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6839 if (Op.getOpcode() == ISD::SHL_PARTS) {
6840 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6841 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6843 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6844 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6847 SDValue Ops[2] = { Lo, Hi };
6848 return DAG.getMergeValues(Ops, 2, dl);
6851 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6852 SelectionDAG &DAG) const {
6853 EVT SrcVT = Op.getOperand(0).getValueType();
6855 if (SrcVT.isVector())
6858 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6859 "Unknown SINT_TO_FP to lower!");
6861 // These are really Legal; return the operand so the caller accepts it as
6863 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6865 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6866 Subtarget->is64Bit()) {
6870 DebugLoc dl = Op.getDebugLoc();
6871 unsigned Size = SrcVT.getSizeInBits()/8;
6872 MachineFunction &MF = DAG.getMachineFunction();
6873 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6874 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6875 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6877 MachinePointerInfo::getFixedStack(SSFI),
6879 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6882 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6884 SelectionDAG &DAG) const {
6886 DebugLoc DL = Op.getDebugLoc();
6888 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6890 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6892 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6894 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6896 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
6897 MachineMemOperand *MMO;
6899 int SSFI = FI->getIndex();
6901 DAG.getMachineFunction()
6902 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6903 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6905 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
6906 StackSlot = StackSlot.getOperand(1);
6908 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6909 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6911 Tys, Ops, array_lengthof(Ops),
6915 Chain = Result.getValue(1);
6916 SDValue InFlag = Result.getValue(2);
6918 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6919 // shouldn't be necessary except that RFP cannot be live across
6920 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6921 MachineFunction &MF = DAG.getMachineFunction();
6922 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6923 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6924 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6925 Tys = DAG.getVTList(MVT::Other);
6927 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6929 MachineMemOperand *MMO =
6930 DAG.getMachineFunction()
6931 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6932 MachineMemOperand::MOStore, SSFISize, SSFISize);
6934 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6935 Ops, array_lengthof(Ops),
6936 Op.getValueType(), MMO);
6937 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6938 MachinePointerInfo::getFixedStack(SSFI),
6945 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6946 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6947 SelectionDAG &DAG) const {
6948 // This algorithm is not obvious. Here it is in C code, more or less:
6950 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6951 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6952 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6954 // Copy ints to xmm registers.
6955 __m128i xh = _mm_cvtsi32_si128( hi );
6956 __m128i xl = _mm_cvtsi32_si128( lo );
6958 // Combine into low half of a single xmm register.
6959 __m128i x = _mm_unpacklo_epi32( xh, xl );
6963 // Merge in appropriate exponents to give the integer bits the right
6965 x = _mm_unpacklo_epi32( x, exp );
6967 // Subtract away the biases to deal with the IEEE-754 double precision
6969 d = _mm_sub_pd( (__m128d) x, bias );
6971 // All conversions up to here are exact. The correctly rounded result is
6972 // calculated using the current rounding mode using the following
6974 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6975 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6976 // store doesn't really need to be here (except
6977 // maybe to zero the other double)
6982 DebugLoc dl = Op.getDebugLoc();
6983 LLVMContext *Context = DAG.getContext();
6985 // Build some magic constants.
6986 std::vector<Constant*> CV0;
6987 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6988 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6989 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6990 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6991 Constant *C0 = ConstantVector::get(CV0);
6992 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6994 std::vector<Constant*> CV1;
6996 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6998 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6999 Constant *C1 = ConstantVector::get(CV1);
7000 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7002 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7003 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7005 DAG.getIntPtrConstant(1)));
7006 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7007 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7009 DAG.getIntPtrConstant(0)));
7010 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7011 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7012 MachinePointerInfo::getConstantPool(),
7014 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7015 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7016 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7017 MachinePointerInfo::getConstantPool(),
7019 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7021 // Add the halves; easiest way is to swap them into another reg first.
7022 int ShufMask[2] = { 1, -1 };
7023 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7024 DAG.getUNDEF(MVT::v2f64), ShufMask);
7025 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7026 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7027 DAG.getIntPtrConstant(0));
7030 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7031 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7032 SelectionDAG &DAG) const {
7033 DebugLoc dl = Op.getDebugLoc();
7034 // FP constant to bias correct the final result.
7035 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7038 // Load the 32-bit value into an XMM register.
7039 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7040 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7042 DAG.getIntPtrConstant(0)));
7044 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7045 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7046 DAG.getIntPtrConstant(0));
7048 // Or the load with the bias.
7049 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7050 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7051 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7053 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7054 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7055 MVT::v2f64, Bias)));
7056 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7057 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7058 DAG.getIntPtrConstant(0));
7060 // Subtract the bias.
7061 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7063 // Handle final rounding.
7064 EVT DestVT = Op.getValueType();
7066 if (DestVT.bitsLT(MVT::f64)) {
7067 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7068 DAG.getIntPtrConstant(0));
7069 } else if (DestVT.bitsGT(MVT::f64)) {
7070 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7073 // Handle final rounding.
7077 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7078 SelectionDAG &DAG) const {
7079 SDValue N0 = Op.getOperand(0);
7080 DebugLoc dl = Op.getDebugLoc();
7082 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7083 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7084 // the optimization here.
7085 if (DAG.SignBitIsZero(N0))
7086 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7088 EVT SrcVT = N0.getValueType();
7089 EVT DstVT = Op.getValueType();
7090 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7091 return LowerUINT_TO_FP_i64(Op, DAG);
7092 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7093 return LowerUINT_TO_FP_i32(Op, DAG);
7095 // Make a 64-bit buffer, and use it to build an FILD.
7096 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7097 if (SrcVT == MVT::i32) {
7098 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7099 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7100 getPointerTy(), StackSlot, WordOff);
7101 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7102 StackSlot, MachinePointerInfo(),
7104 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7105 OffsetSlot, MachinePointerInfo(),
7107 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7111 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7112 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7113 StackSlot, MachinePointerInfo(),
7115 // For i64 source, we need to add the appropriate power of 2 if the input
7116 // was negative. This is the same as the optimization in
7117 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7118 // we must be careful to do the computation in x87 extended precision, not
7119 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7120 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7121 MachineMemOperand *MMO =
7122 DAG.getMachineFunction()
7123 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7124 MachineMemOperand::MOLoad, 8, 8);
7126 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7127 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7128 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7131 APInt FF(32, 0x5F800000ULL);
7133 // Check whether the sign bit is set.
7134 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7135 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7138 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7139 SDValue FudgePtr = DAG.getConstantPool(
7140 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7143 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7144 SDValue Zero = DAG.getIntPtrConstant(0);
7145 SDValue Four = DAG.getIntPtrConstant(4);
7146 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7148 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7150 // Load the value out, extending it from f32 to f80.
7151 // FIXME: Avoid the extend by constructing the right constant pool?
7152 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7153 FudgePtr, MachinePointerInfo::getConstantPool(),
7154 MVT::f32, false, false, 4);
7155 // Extend everything to 80 bits to force it to be done on x87.
7156 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7157 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7160 std::pair<SDValue,SDValue> X86TargetLowering::
7161 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7162 DebugLoc DL = Op.getDebugLoc();
7164 EVT DstTy = Op.getValueType();
7167 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7171 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7172 DstTy.getSimpleVT() >= MVT::i16 &&
7173 "Unknown FP_TO_SINT to lower!");
7175 // These are really Legal.
7176 if (DstTy == MVT::i32 &&
7177 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7178 return std::make_pair(SDValue(), SDValue());
7179 if (Subtarget->is64Bit() &&
7180 DstTy == MVT::i64 &&
7181 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7182 return std::make_pair(SDValue(), SDValue());
7184 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7186 MachineFunction &MF = DAG.getMachineFunction();
7187 unsigned MemSize = DstTy.getSizeInBits()/8;
7188 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7189 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7194 switch (DstTy.getSimpleVT().SimpleTy) {
7195 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7196 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7197 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7198 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7201 SDValue Chain = DAG.getEntryNode();
7202 SDValue Value = Op.getOperand(0);
7203 EVT TheVT = Op.getOperand(0).getValueType();
7204 if (isScalarFPTypeInSSEReg(TheVT)) {
7205 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7206 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7207 MachinePointerInfo::getFixedStack(SSFI),
7209 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7211 Chain, StackSlot, DAG.getValueType(TheVT)
7214 MachineMemOperand *MMO =
7215 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7216 MachineMemOperand::MOLoad, MemSize, MemSize);
7217 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7219 Chain = Value.getValue(1);
7220 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7221 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7224 MachineMemOperand *MMO =
7225 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7226 MachineMemOperand::MOStore, MemSize, MemSize);
7228 // Build the FP_TO_INT*_IN_MEM
7229 SDValue Ops[] = { Chain, Value, StackSlot };
7230 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7231 Ops, 3, DstTy, MMO);
7233 return std::make_pair(FIST, StackSlot);
7236 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7237 SelectionDAG &DAG) const {
7238 if (Op.getValueType().isVector())
7241 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7242 SDValue FIST = Vals.first, StackSlot = Vals.second;
7243 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7244 if (FIST.getNode() == 0) return Op;
7247 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7248 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7251 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7252 SelectionDAG &DAG) const {
7253 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7254 SDValue FIST = Vals.first, StackSlot = Vals.second;
7255 assert(FIST.getNode() && "Unexpected failure");
7258 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7259 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7262 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7263 SelectionDAG &DAG) const {
7264 LLVMContext *Context = DAG.getContext();
7265 DebugLoc dl = Op.getDebugLoc();
7266 EVT VT = Op.getValueType();
7269 EltVT = VT.getVectorElementType();
7270 std::vector<Constant*> CV;
7271 if (EltVT == MVT::f64) {
7272 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7276 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7282 Constant *C = ConstantVector::get(CV);
7283 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7284 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7285 MachinePointerInfo::getConstantPool(),
7287 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7290 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7291 LLVMContext *Context = DAG.getContext();
7292 DebugLoc dl = Op.getDebugLoc();
7293 EVT VT = Op.getValueType();
7296 EltVT = VT.getVectorElementType();
7297 std::vector<Constant*> CV;
7298 if (EltVT == MVT::f64) {
7299 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7303 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7309 Constant *C = ConstantVector::get(CV);
7310 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7311 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7312 MachinePointerInfo::getConstantPool(),
7314 if (VT.isVector()) {
7315 return DAG.getNode(ISD::BITCAST, dl, VT,
7316 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7317 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7319 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7321 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7325 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7326 LLVMContext *Context = DAG.getContext();
7327 SDValue Op0 = Op.getOperand(0);
7328 SDValue Op1 = Op.getOperand(1);
7329 DebugLoc dl = Op.getDebugLoc();
7330 EVT VT = Op.getValueType();
7331 EVT SrcVT = Op1.getValueType();
7333 // If second operand is smaller, extend it first.
7334 if (SrcVT.bitsLT(VT)) {
7335 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7338 // And if it is bigger, shrink it first.
7339 if (SrcVT.bitsGT(VT)) {
7340 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7344 // At this point the operands and the result should have the same
7345 // type, and that won't be f80 since that is not custom lowered.
7347 // First get the sign bit of second operand.
7348 std::vector<Constant*> CV;
7349 if (SrcVT == MVT::f64) {
7350 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7351 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7353 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7354 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7355 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7356 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7358 Constant *C = ConstantVector::get(CV);
7359 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7360 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7361 MachinePointerInfo::getConstantPool(),
7363 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7365 // Shift sign bit right or left if the two operands have different types.
7366 if (SrcVT.bitsGT(VT)) {
7367 // Op0 is MVT::f32, Op1 is MVT::f64.
7368 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7369 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7370 DAG.getConstant(32, MVT::i32));
7371 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7372 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7373 DAG.getIntPtrConstant(0));
7376 // Clear first operand sign bit.
7378 if (VT == MVT::f64) {
7379 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7380 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7382 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7383 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7384 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7385 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7387 C = ConstantVector::get(CV);
7388 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7389 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7390 MachinePointerInfo::getConstantPool(),
7392 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7394 // Or the value with the sign bit.
7395 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7398 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7399 SDValue N0 = Op.getOperand(0);
7400 DebugLoc dl = Op.getDebugLoc();
7401 EVT VT = Op.getValueType();
7403 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7404 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7405 DAG.getConstant(1, VT));
7406 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7409 /// Emit nodes that will be selected as "test Op0,Op0", or something
7411 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7412 SelectionDAG &DAG) const {
7413 DebugLoc dl = Op.getDebugLoc();
7415 // CF and OF aren't always set the way we want. Determine which
7416 // of these we need.
7417 bool NeedCF = false;
7418 bool NeedOF = false;
7421 case X86::COND_A: case X86::COND_AE:
7422 case X86::COND_B: case X86::COND_BE:
7425 case X86::COND_G: case X86::COND_GE:
7426 case X86::COND_L: case X86::COND_LE:
7427 case X86::COND_O: case X86::COND_NO:
7432 // See if we can use the EFLAGS value from the operand instead of
7433 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7434 // we prove that the arithmetic won't overflow, we can't use OF or CF.
7435 if (Op.getResNo() != 0 || NeedOF || NeedCF)
7436 // Emit a CMP with 0, which is the TEST pattern.
7437 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7438 DAG.getConstant(0, Op.getValueType()));
7440 unsigned Opcode = 0;
7441 unsigned NumOperands = 0;
7442 switch (Op.getNode()->getOpcode()) {
7444 // Due to an isel shortcoming, be conservative if this add is likely to be
7445 // selected as part of a load-modify-store instruction. When the root node
7446 // in a match is a store, isel doesn't know how to remap non-chain non-flag
7447 // uses of other nodes in the match, such as the ADD in this case. This
7448 // leads to the ADD being left around and reselected, with the result being
7449 // two adds in the output. Alas, even if none our users are stores, that
7450 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
7451 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
7452 // climbing the DAG back to the root, and it doesn't seem to be worth the
7454 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7455 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7456 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7459 if (ConstantSDNode *C =
7460 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7461 // An add of one will be selected as an INC.
7462 if (C->getAPIntValue() == 1) {
7463 Opcode = X86ISD::INC;
7468 // An add of negative one (subtract of one) will be selected as a DEC.
7469 if (C->getAPIntValue().isAllOnesValue()) {
7470 Opcode = X86ISD::DEC;
7476 // Otherwise use a regular EFLAGS-setting add.
7477 Opcode = X86ISD::ADD;
7481 // If the primary and result isn't used, don't bother using X86ISD::AND,
7482 // because a TEST instruction will be better.
7483 bool NonFlagUse = false;
7484 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7485 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7487 unsigned UOpNo = UI.getOperandNo();
7488 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7489 // Look pass truncate.
7490 UOpNo = User->use_begin().getOperandNo();
7491 User = *User->use_begin();
7494 if (User->getOpcode() != ISD::BRCOND &&
7495 User->getOpcode() != ISD::SETCC &&
7496 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7509 // Due to the ISEL shortcoming noted above, be conservative if this op is
7510 // likely to be selected as part of a load-modify-store instruction.
7511 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7512 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7513 if (UI->getOpcode() == ISD::STORE)
7516 // Otherwise use a regular EFLAGS-setting instruction.
7517 switch (Op.getNode()->getOpcode()) {
7518 default: llvm_unreachable("unexpected operator!");
7519 case ISD::SUB: Opcode = X86ISD::SUB; break;
7520 case ISD::OR: Opcode = X86ISD::OR; break;
7521 case ISD::XOR: Opcode = X86ISD::XOR; break;
7522 case ISD::AND: Opcode = X86ISD::AND; break;
7534 return SDValue(Op.getNode(), 1);
7541 // Emit a CMP with 0, which is the TEST pattern.
7542 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7543 DAG.getConstant(0, Op.getValueType()));
7545 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7546 SmallVector<SDValue, 4> Ops;
7547 for (unsigned i = 0; i != NumOperands; ++i)
7548 Ops.push_back(Op.getOperand(i));
7550 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7551 DAG.ReplaceAllUsesWith(Op, New);
7552 return SDValue(New.getNode(), 1);
7555 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7557 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7558 SelectionDAG &DAG) const {
7559 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7560 if (C->getAPIntValue() == 0)
7561 return EmitTest(Op0, X86CC, DAG);
7563 DebugLoc dl = Op0.getDebugLoc();
7564 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7567 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7568 /// if it's possible.
7569 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7570 DebugLoc dl, SelectionDAG &DAG) const {
7571 SDValue Op0 = And.getOperand(0);
7572 SDValue Op1 = And.getOperand(1);
7573 if (Op0.getOpcode() == ISD::TRUNCATE)
7574 Op0 = Op0.getOperand(0);
7575 if (Op1.getOpcode() == ISD::TRUNCATE)
7576 Op1 = Op1.getOperand(0);
7579 if (Op1.getOpcode() == ISD::SHL)
7580 std::swap(Op0, Op1);
7581 if (Op0.getOpcode() == ISD::SHL) {
7582 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7583 if (And00C->getZExtValue() == 1) {
7584 // If we looked past a truncate, check that it's only truncating away
7586 unsigned BitWidth = Op0.getValueSizeInBits();
7587 unsigned AndBitWidth = And.getValueSizeInBits();
7588 if (BitWidth > AndBitWidth) {
7589 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7590 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7591 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7595 RHS = Op0.getOperand(1);
7597 } else if (Op1.getOpcode() == ISD::Constant) {
7598 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7599 SDValue AndLHS = Op0;
7600 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7601 LHS = AndLHS.getOperand(0);
7602 RHS = AndLHS.getOperand(1);
7606 if (LHS.getNode()) {
7607 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
7608 // instruction. Since the shift amount is in-range-or-undefined, we know
7609 // that doing a bittest on the i32 value is ok. We extend to i32 because
7610 // the encoding for the i16 version is larger than the i32 version.
7611 // Also promote i16 to i32 for performance / code size reason.
7612 if (LHS.getValueType() == MVT::i8 ||
7613 LHS.getValueType() == MVT::i16)
7614 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7616 // If the operand types disagree, extend the shift amount to match. Since
7617 // BT ignores high bits (like shifts) we can use anyextend.
7618 if (LHS.getValueType() != RHS.getValueType())
7619 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7621 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7622 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7623 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7624 DAG.getConstant(Cond, MVT::i8), BT);
7630 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7631 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7632 SDValue Op0 = Op.getOperand(0);
7633 SDValue Op1 = Op.getOperand(1);
7634 DebugLoc dl = Op.getDebugLoc();
7635 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7637 // Optimize to BT if possible.
7638 // Lower (X & (1 << N)) == 0 to BT(X, N).
7639 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7640 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7641 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7642 Op1.getOpcode() == ISD::Constant &&
7643 cast<ConstantSDNode>(Op1)->isNullValue() &&
7644 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7645 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7646 if (NewSetCC.getNode())
7650 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
7652 if (Op1.getOpcode() == ISD::Constant &&
7653 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7654 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7655 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7657 // If the input is a setcc, then reuse the input setcc or use a new one with
7658 // the inverted condition.
7659 if (Op0.getOpcode() == X86ISD::SETCC) {
7660 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7661 bool Invert = (CC == ISD::SETNE) ^
7662 cast<ConstantSDNode>(Op1)->isNullValue();
7663 if (!Invert) return Op0;
7665 CCode = X86::GetOppositeBranchCondition(CCode);
7666 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7667 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7671 bool isFP = Op1.getValueType().isFloatingPoint();
7672 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7673 if (X86CC == X86::COND_INVALID)
7676 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7677 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7678 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7681 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7683 SDValue Op0 = Op.getOperand(0);
7684 SDValue Op1 = Op.getOperand(1);
7685 SDValue CC = Op.getOperand(2);
7686 EVT VT = Op.getValueType();
7687 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7688 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7689 DebugLoc dl = Op.getDebugLoc();
7693 EVT VT0 = Op0.getValueType();
7694 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7695 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7698 switch (SetCCOpcode) {
7701 case ISD::SETEQ: SSECC = 0; break;
7703 case ISD::SETGT: Swap = true; // Fallthrough
7705 case ISD::SETOLT: SSECC = 1; break;
7707 case ISD::SETGE: Swap = true; // Fallthrough
7709 case ISD::SETOLE: SSECC = 2; break;
7710 case ISD::SETUO: SSECC = 3; break;
7712 case ISD::SETNE: SSECC = 4; break;
7713 case ISD::SETULE: Swap = true;
7714 case ISD::SETUGE: SSECC = 5; break;
7715 case ISD::SETULT: Swap = true;
7716 case ISD::SETUGT: SSECC = 6; break;
7717 case ISD::SETO: SSECC = 7; break;
7720 std::swap(Op0, Op1);
7722 // In the two special cases we can't handle, emit two comparisons.
7724 if (SetCCOpcode == ISD::SETUEQ) {
7726 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7727 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7728 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7730 else if (SetCCOpcode == ISD::SETONE) {
7732 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7733 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7734 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7736 llvm_unreachable("Illegal FP comparison");
7738 // Handle all other FP comparisons here.
7739 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7742 // We are handling one of the integer comparisons here. Since SSE only has
7743 // GT and EQ comparisons for integer, swapping operands and multiple
7744 // operations may be required for some comparisons.
7745 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7746 bool Swap = false, Invert = false, FlipSigns = false;
7748 switch (VT.getSimpleVT().SimpleTy) {
7750 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7751 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7752 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7753 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7756 switch (SetCCOpcode) {
7758 case ISD::SETNE: Invert = true;
7759 case ISD::SETEQ: Opc = EQOpc; break;
7760 case ISD::SETLT: Swap = true;
7761 case ISD::SETGT: Opc = GTOpc; break;
7762 case ISD::SETGE: Swap = true;
7763 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7764 case ISD::SETULT: Swap = true;
7765 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7766 case ISD::SETUGE: Swap = true;
7767 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7770 std::swap(Op0, Op1);
7772 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7773 // bits of the inputs before performing those operations.
7775 EVT EltVT = VT.getVectorElementType();
7776 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7778 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7779 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7781 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7782 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7785 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7787 // If the logical-not of the result is required, perform that now.
7789 Result = DAG.getNOT(dl, Result, VT);
7794 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7795 static bool isX86LogicalCmp(SDValue Op) {
7796 unsigned Opc = Op.getNode()->getOpcode();
7797 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7799 if (Op.getResNo() == 1 &&
7800 (Opc == X86ISD::ADD ||
7801 Opc == X86ISD::SUB ||
7802 Opc == X86ISD::ADC ||
7803 Opc == X86ISD::SBB ||
7804 Opc == X86ISD::SMUL ||
7805 Opc == X86ISD::UMUL ||
7806 Opc == X86ISD::INC ||
7807 Opc == X86ISD::DEC ||
7808 Opc == X86ISD::OR ||
7809 Opc == X86ISD::XOR ||
7810 Opc == X86ISD::AND))
7813 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7819 static bool isZero(SDValue V) {
7820 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7821 return C && C->isNullValue();
7824 static bool isAllOnes(SDValue V) {
7825 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7826 return C && C->isAllOnesValue();
7829 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7830 bool addTest = true;
7831 SDValue Cond = Op.getOperand(0);
7832 SDValue Op1 = Op.getOperand(1);
7833 SDValue Op2 = Op.getOperand(2);
7834 DebugLoc DL = Op.getDebugLoc();
7837 if (Cond.getOpcode() == ISD::SETCC) {
7838 SDValue NewCond = LowerSETCC(Cond, DAG);
7839 if (NewCond.getNode())
7843 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7844 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7845 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7846 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7847 if (Cond.getOpcode() == X86ISD::SETCC &&
7848 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7849 isZero(Cond.getOperand(1).getOperand(1))) {
7850 SDValue Cmp = Cond.getOperand(1);
7852 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7854 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7855 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7856 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7858 SDValue CmpOp0 = Cmp.getOperand(0);
7859 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7860 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7862 SDValue Res = // Res = 0 or -1.
7863 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7864 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7866 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7867 Res = DAG.getNOT(DL, Res, Res.getValueType());
7869 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7870 if (N2C == 0 || !N2C->isNullValue())
7871 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7876 // Look past (and (setcc_carry (cmp ...)), 1).
7877 if (Cond.getOpcode() == ISD::AND &&
7878 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7879 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7880 if (C && C->getAPIntValue() == 1)
7881 Cond = Cond.getOperand(0);
7884 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7885 // setting operand in place of the X86ISD::SETCC.
7886 if (Cond.getOpcode() == X86ISD::SETCC ||
7887 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7888 CC = Cond.getOperand(0);
7890 SDValue Cmp = Cond.getOperand(1);
7891 unsigned Opc = Cmp.getOpcode();
7892 EVT VT = Op.getValueType();
7894 bool IllegalFPCMov = false;
7895 if (VT.isFloatingPoint() && !VT.isVector() &&
7896 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7897 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7899 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7900 Opc == X86ISD::BT) { // FIXME
7907 // Look pass the truncate.
7908 if (Cond.getOpcode() == ISD::TRUNCATE)
7909 Cond = Cond.getOperand(0);
7911 // We know the result of AND is compared against zero. Try to match
7913 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7914 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7915 if (NewSetCC.getNode()) {
7916 CC = NewSetCC.getOperand(0);
7917 Cond = NewSetCC.getOperand(1);
7924 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7925 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7928 // a < b ? -1 : 0 -> RES = ~setcc_carry
7929 // a < b ? 0 : -1 -> RES = setcc_carry
7930 // a >= b ? -1 : 0 -> RES = setcc_carry
7931 // a >= b ? 0 : -1 -> RES = ~setcc_carry
7932 if (Cond.getOpcode() == X86ISD::CMP) {
7933 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7935 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7936 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7937 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7938 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7939 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7940 return DAG.getNOT(DL, Res, Res.getValueType());
7945 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7946 // condition is true.
7947 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7948 SDValue Ops[] = { Op2, Op1, CC, Cond };
7949 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7952 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7953 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7954 // from the AND / OR.
7955 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7956 Opc = Op.getOpcode();
7957 if (Opc != ISD::OR && Opc != ISD::AND)
7959 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7960 Op.getOperand(0).hasOneUse() &&
7961 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7962 Op.getOperand(1).hasOneUse());
7965 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7966 // 1 and that the SETCC node has a single use.
7967 static bool isXor1OfSetCC(SDValue Op) {
7968 if (Op.getOpcode() != ISD::XOR)
7970 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7971 if (N1C && N1C->getAPIntValue() == 1) {
7972 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7973 Op.getOperand(0).hasOneUse();
7978 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7979 bool addTest = true;
7980 SDValue Chain = Op.getOperand(0);
7981 SDValue Cond = Op.getOperand(1);
7982 SDValue Dest = Op.getOperand(2);
7983 DebugLoc dl = Op.getDebugLoc();
7986 if (Cond.getOpcode() == ISD::SETCC) {
7987 SDValue NewCond = LowerSETCC(Cond, DAG);
7988 if (NewCond.getNode())
7992 // FIXME: LowerXALUO doesn't handle these!!
7993 else if (Cond.getOpcode() == X86ISD::ADD ||
7994 Cond.getOpcode() == X86ISD::SUB ||
7995 Cond.getOpcode() == X86ISD::SMUL ||
7996 Cond.getOpcode() == X86ISD::UMUL)
7997 Cond = LowerXALUO(Cond, DAG);
8000 // Look pass (and (setcc_carry (cmp ...)), 1).
8001 if (Cond.getOpcode() == ISD::AND &&
8002 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8003 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8004 if (C && C->getAPIntValue() == 1)
8005 Cond = Cond.getOperand(0);
8008 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8009 // setting operand in place of the X86ISD::SETCC.
8010 if (Cond.getOpcode() == X86ISD::SETCC ||
8011 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8012 CC = Cond.getOperand(0);
8014 SDValue Cmp = Cond.getOperand(1);
8015 unsigned Opc = Cmp.getOpcode();
8016 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8017 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8021 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8025 // These can only come from an arithmetic instruction with overflow,
8026 // e.g. SADDO, UADDO.
8027 Cond = Cond.getNode()->getOperand(1);
8034 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8035 SDValue Cmp = Cond.getOperand(0).getOperand(1);
8036 if (CondOpc == ISD::OR) {
8037 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8038 // two branches instead of an explicit OR instruction with a
8040 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8041 isX86LogicalCmp(Cmp)) {
8042 CC = Cond.getOperand(0).getOperand(0);
8043 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8044 Chain, Dest, CC, Cmp);
8045 CC = Cond.getOperand(1).getOperand(0);
8049 } else { // ISD::AND
8050 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8051 // two branches instead of an explicit AND instruction with a
8052 // separate test. However, we only do this if this block doesn't
8053 // have a fall-through edge, because this requires an explicit
8054 // jmp when the condition is false.
8055 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8056 isX86LogicalCmp(Cmp) &&
8057 Op.getNode()->hasOneUse()) {
8058 X86::CondCode CCode =
8059 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8060 CCode = X86::GetOppositeBranchCondition(CCode);
8061 CC = DAG.getConstant(CCode, MVT::i8);
8062 SDNode *User = *Op.getNode()->use_begin();
8063 // Look for an unconditional branch following this conditional branch.
8064 // We need this because we need to reverse the successors in order
8065 // to implement FCMP_OEQ.
8066 if (User->getOpcode() == ISD::BR) {
8067 SDValue FalseBB = User->getOperand(1);
8069 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8070 assert(NewBR == User);
8074 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8075 Chain, Dest, CC, Cmp);
8076 X86::CondCode CCode =
8077 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8078 CCode = X86::GetOppositeBranchCondition(CCode);
8079 CC = DAG.getConstant(CCode, MVT::i8);
8085 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8086 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8087 // It should be transformed during dag combiner except when the condition
8088 // is set by a arithmetics with overflow node.
8089 X86::CondCode CCode =
8090 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8091 CCode = X86::GetOppositeBranchCondition(CCode);
8092 CC = DAG.getConstant(CCode, MVT::i8);
8093 Cond = Cond.getOperand(0).getOperand(1);
8099 // Look pass the truncate.
8100 if (Cond.getOpcode() == ISD::TRUNCATE)
8101 Cond = Cond.getOperand(0);
8103 // We know the result of AND is compared against zero. Try to match
8105 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8106 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8107 if (NewSetCC.getNode()) {
8108 CC = NewSetCC.getOperand(0);
8109 Cond = NewSetCC.getOperand(1);
8116 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8117 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8119 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8120 Chain, Dest, CC, Cond);
8124 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8125 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8126 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8127 // that the guard pages used by the OS virtual memory manager are allocated in
8128 // correct sequence.
8130 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8131 SelectionDAG &DAG) const {
8132 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8133 "This should be used only on Windows targets");
8134 assert(!Subtarget->isTargetEnvMacho());
8135 DebugLoc dl = Op.getDebugLoc();
8138 SDValue Chain = Op.getOperand(0);
8139 SDValue Size = Op.getOperand(1);
8140 // FIXME: Ensure alignment here
8144 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8145 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8147 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8148 Flag = Chain.getValue(1);
8150 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8152 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8153 Flag = Chain.getValue(1);
8155 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8157 SDValue Ops1[2] = { Chain.getValue(0), Chain };
8158 return DAG.getMergeValues(Ops1, 2, dl);
8161 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8162 MachineFunction &MF = DAG.getMachineFunction();
8163 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8165 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8166 DebugLoc DL = Op.getDebugLoc();
8168 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8169 // vastart just stores the address of the VarArgsFrameIndex slot into the
8170 // memory location argument.
8171 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8173 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8174 MachinePointerInfo(SV), false, false, 0);
8178 // gp_offset (0 - 6 * 8)
8179 // fp_offset (48 - 48 + 8 * 16)
8180 // overflow_arg_area (point to parameters coming in memory).
8182 SmallVector<SDValue, 8> MemOps;
8183 SDValue FIN = Op.getOperand(1);
8185 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8186 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8188 FIN, MachinePointerInfo(SV), false, false, 0);
8189 MemOps.push_back(Store);
8192 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8193 FIN, DAG.getIntPtrConstant(4));
8194 Store = DAG.getStore(Op.getOperand(0), DL,
8195 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8197 FIN, MachinePointerInfo(SV, 4), false, false, 0);
8198 MemOps.push_back(Store);
8200 // Store ptr to overflow_arg_area
8201 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8202 FIN, DAG.getIntPtrConstant(4));
8203 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8205 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8206 MachinePointerInfo(SV, 8),
8208 MemOps.push_back(Store);
8210 // Store ptr to reg_save_area.
8211 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8212 FIN, DAG.getIntPtrConstant(8));
8213 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8215 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8216 MachinePointerInfo(SV, 16), false, false, 0);
8217 MemOps.push_back(Store);
8218 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8219 &MemOps[0], MemOps.size());
8222 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8223 assert(Subtarget->is64Bit() &&
8224 "LowerVAARG only handles 64-bit va_arg!");
8225 assert((Subtarget->isTargetLinux() ||
8226 Subtarget->isTargetDarwin()) &&
8227 "Unhandled target in LowerVAARG");
8228 assert(Op.getNode()->getNumOperands() == 4);
8229 SDValue Chain = Op.getOperand(0);
8230 SDValue SrcPtr = Op.getOperand(1);
8231 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8232 unsigned Align = Op.getConstantOperandVal(3);
8233 DebugLoc dl = Op.getDebugLoc();
8235 EVT ArgVT = Op.getNode()->getValueType(0);
8236 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8237 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8240 // Decide which area this value should be read from.
8241 // TODO: Implement the AMD64 ABI in its entirety. This simple
8242 // selection mechanism works only for the basic types.
8243 if (ArgVT == MVT::f80) {
8244 llvm_unreachable("va_arg for f80 not yet implemented");
8245 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8246 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
8247 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8248 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
8250 llvm_unreachable("Unhandled argument type in LowerVAARG");
8254 // Sanity Check: Make sure using fp_offset makes sense.
8255 assert(!UseSoftFloat &&
8256 !(DAG.getMachineFunction()
8257 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8258 Subtarget->hasXMM());
8261 // Insert VAARG_64 node into the DAG
8262 // VAARG_64 returns two values: Variable Argument Address, Chain
8263 SmallVector<SDValue, 11> InstOps;
8264 InstOps.push_back(Chain);
8265 InstOps.push_back(SrcPtr);
8266 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8267 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8268 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8269 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8270 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8271 VTs, &InstOps[0], InstOps.size(),
8273 MachinePointerInfo(SV),
8278 Chain = VAARG.getValue(1);
8280 // Load the next argument and return it
8281 return DAG.getLoad(ArgVT, dl,
8284 MachinePointerInfo(),
8288 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8289 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8290 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8291 SDValue Chain = Op.getOperand(0);
8292 SDValue DstPtr = Op.getOperand(1);
8293 SDValue SrcPtr = Op.getOperand(2);
8294 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8295 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8296 DebugLoc DL = Op.getDebugLoc();
8298 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8299 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8301 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8305 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8306 DebugLoc dl = Op.getDebugLoc();
8307 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8309 default: return SDValue(); // Don't custom lower most intrinsics.
8310 // Comparison intrinsics.
8311 case Intrinsic::x86_sse_comieq_ss:
8312 case Intrinsic::x86_sse_comilt_ss:
8313 case Intrinsic::x86_sse_comile_ss:
8314 case Intrinsic::x86_sse_comigt_ss:
8315 case Intrinsic::x86_sse_comige_ss:
8316 case Intrinsic::x86_sse_comineq_ss:
8317 case Intrinsic::x86_sse_ucomieq_ss:
8318 case Intrinsic::x86_sse_ucomilt_ss:
8319 case Intrinsic::x86_sse_ucomile_ss:
8320 case Intrinsic::x86_sse_ucomigt_ss:
8321 case Intrinsic::x86_sse_ucomige_ss:
8322 case Intrinsic::x86_sse_ucomineq_ss:
8323 case Intrinsic::x86_sse2_comieq_sd:
8324 case Intrinsic::x86_sse2_comilt_sd:
8325 case Intrinsic::x86_sse2_comile_sd:
8326 case Intrinsic::x86_sse2_comigt_sd:
8327 case Intrinsic::x86_sse2_comige_sd:
8328 case Intrinsic::x86_sse2_comineq_sd:
8329 case Intrinsic::x86_sse2_ucomieq_sd:
8330 case Intrinsic::x86_sse2_ucomilt_sd:
8331 case Intrinsic::x86_sse2_ucomile_sd:
8332 case Intrinsic::x86_sse2_ucomigt_sd:
8333 case Intrinsic::x86_sse2_ucomige_sd:
8334 case Intrinsic::x86_sse2_ucomineq_sd: {
8336 ISD::CondCode CC = ISD::SETCC_INVALID;
8339 case Intrinsic::x86_sse_comieq_ss:
8340 case Intrinsic::x86_sse2_comieq_sd:
8344 case Intrinsic::x86_sse_comilt_ss:
8345 case Intrinsic::x86_sse2_comilt_sd:
8349 case Intrinsic::x86_sse_comile_ss:
8350 case Intrinsic::x86_sse2_comile_sd:
8354 case Intrinsic::x86_sse_comigt_ss:
8355 case Intrinsic::x86_sse2_comigt_sd:
8359 case Intrinsic::x86_sse_comige_ss:
8360 case Intrinsic::x86_sse2_comige_sd:
8364 case Intrinsic::x86_sse_comineq_ss:
8365 case Intrinsic::x86_sse2_comineq_sd:
8369 case Intrinsic::x86_sse_ucomieq_ss:
8370 case Intrinsic::x86_sse2_ucomieq_sd:
8371 Opc = X86ISD::UCOMI;
8374 case Intrinsic::x86_sse_ucomilt_ss:
8375 case Intrinsic::x86_sse2_ucomilt_sd:
8376 Opc = X86ISD::UCOMI;
8379 case Intrinsic::x86_sse_ucomile_ss:
8380 case Intrinsic::x86_sse2_ucomile_sd:
8381 Opc = X86ISD::UCOMI;
8384 case Intrinsic::x86_sse_ucomigt_ss:
8385 case Intrinsic::x86_sse2_ucomigt_sd:
8386 Opc = X86ISD::UCOMI;
8389 case Intrinsic::x86_sse_ucomige_ss:
8390 case Intrinsic::x86_sse2_ucomige_sd:
8391 Opc = X86ISD::UCOMI;
8394 case Intrinsic::x86_sse_ucomineq_ss:
8395 case Intrinsic::x86_sse2_ucomineq_sd:
8396 Opc = X86ISD::UCOMI;
8401 SDValue LHS = Op.getOperand(1);
8402 SDValue RHS = Op.getOperand(2);
8403 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8404 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8405 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8406 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8407 DAG.getConstant(X86CC, MVT::i8), Cond);
8408 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8410 // ptest and testp intrinsics. The intrinsic these come from are designed to
8411 // return an integer value, not just an instruction so lower it to the ptest
8412 // or testp pattern and a setcc for the result.
8413 case Intrinsic::x86_sse41_ptestz:
8414 case Intrinsic::x86_sse41_ptestc:
8415 case Intrinsic::x86_sse41_ptestnzc:
8416 case Intrinsic::x86_avx_ptestz_256:
8417 case Intrinsic::x86_avx_ptestc_256:
8418 case Intrinsic::x86_avx_ptestnzc_256:
8419 case Intrinsic::x86_avx_vtestz_ps:
8420 case Intrinsic::x86_avx_vtestc_ps:
8421 case Intrinsic::x86_avx_vtestnzc_ps:
8422 case Intrinsic::x86_avx_vtestz_pd:
8423 case Intrinsic::x86_avx_vtestc_pd:
8424 case Intrinsic::x86_avx_vtestnzc_pd:
8425 case Intrinsic::x86_avx_vtestz_ps_256:
8426 case Intrinsic::x86_avx_vtestc_ps_256:
8427 case Intrinsic::x86_avx_vtestnzc_ps_256:
8428 case Intrinsic::x86_avx_vtestz_pd_256:
8429 case Intrinsic::x86_avx_vtestc_pd_256:
8430 case Intrinsic::x86_avx_vtestnzc_pd_256: {
8431 bool IsTestPacked = false;
8434 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8435 case Intrinsic::x86_avx_vtestz_ps:
8436 case Intrinsic::x86_avx_vtestz_pd:
8437 case Intrinsic::x86_avx_vtestz_ps_256:
8438 case Intrinsic::x86_avx_vtestz_pd_256:
8439 IsTestPacked = true; // Fallthrough
8440 case Intrinsic::x86_sse41_ptestz:
8441 case Intrinsic::x86_avx_ptestz_256:
8443 X86CC = X86::COND_E;
8445 case Intrinsic::x86_avx_vtestc_ps:
8446 case Intrinsic::x86_avx_vtestc_pd:
8447 case Intrinsic::x86_avx_vtestc_ps_256:
8448 case Intrinsic::x86_avx_vtestc_pd_256:
8449 IsTestPacked = true; // Fallthrough
8450 case Intrinsic::x86_sse41_ptestc:
8451 case Intrinsic::x86_avx_ptestc_256:
8453 X86CC = X86::COND_B;
8455 case Intrinsic::x86_avx_vtestnzc_ps:
8456 case Intrinsic::x86_avx_vtestnzc_pd:
8457 case Intrinsic::x86_avx_vtestnzc_ps_256:
8458 case Intrinsic::x86_avx_vtestnzc_pd_256:
8459 IsTestPacked = true; // Fallthrough
8460 case Intrinsic::x86_sse41_ptestnzc:
8461 case Intrinsic::x86_avx_ptestnzc_256:
8463 X86CC = X86::COND_A;
8467 SDValue LHS = Op.getOperand(1);
8468 SDValue RHS = Op.getOperand(2);
8469 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8470 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8471 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8472 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8473 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8476 // Fix vector shift instructions where the last operand is a non-immediate
8478 case Intrinsic::x86_sse2_pslli_w:
8479 case Intrinsic::x86_sse2_pslli_d:
8480 case Intrinsic::x86_sse2_pslli_q:
8481 case Intrinsic::x86_sse2_psrli_w:
8482 case Intrinsic::x86_sse2_psrli_d:
8483 case Intrinsic::x86_sse2_psrli_q:
8484 case Intrinsic::x86_sse2_psrai_w:
8485 case Intrinsic::x86_sse2_psrai_d:
8486 case Intrinsic::x86_mmx_pslli_w:
8487 case Intrinsic::x86_mmx_pslli_d:
8488 case Intrinsic::x86_mmx_pslli_q:
8489 case Intrinsic::x86_mmx_psrli_w:
8490 case Intrinsic::x86_mmx_psrli_d:
8491 case Intrinsic::x86_mmx_psrli_q:
8492 case Intrinsic::x86_mmx_psrai_w:
8493 case Intrinsic::x86_mmx_psrai_d: {
8494 SDValue ShAmt = Op.getOperand(2);
8495 if (isa<ConstantSDNode>(ShAmt))
8498 unsigned NewIntNo = 0;
8499 EVT ShAmtVT = MVT::v4i32;
8501 case Intrinsic::x86_sse2_pslli_w:
8502 NewIntNo = Intrinsic::x86_sse2_psll_w;
8504 case Intrinsic::x86_sse2_pslli_d:
8505 NewIntNo = Intrinsic::x86_sse2_psll_d;
8507 case Intrinsic::x86_sse2_pslli_q:
8508 NewIntNo = Intrinsic::x86_sse2_psll_q;
8510 case Intrinsic::x86_sse2_psrli_w:
8511 NewIntNo = Intrinsic::x86_sse2_psrl_w;
8513 case Intrinsic::x86_sse2_psrli_d:
8514 NewIntNo = Intrinsic::x86_sse2_psrl_d;
8516 case Intrinsic::x86_sse2_psrli_q:
8517 NewIntNo = Intrinsic::x86_sse2_psrl_q;
8519 case Intrinsic::x86_sse2_psrai_w:
8520 NewIntNo = Intrinsic::x86_sse2_psra_w;
8522 case Intrinsic::x86_sse2_psrai_d:
8523 NewIntNo = Intrinsic::x86_sse2_psra_d;
8526 ShAmtVT = MVT::v2i32;
8528 case Intrinsic::x86_mmx_pslli_w:
8529 NewIntNo = Intrinsic::x86_mmx_psll_w;
8531 case Intrinsic::x86_mmx_pslli_d:
8532 NewIntNo = Intrinsic::x86_mmx_psll_d;
8534 case Intrinsic::x86_mmx_pslli_q:
8535 NewIntNo = Intrinsic::x86_mmx_psll_q;
8537 case Intrinsic::x86_mmx_psrli_w:
8538 NewIntNo = Intrinsic::x86_mmx_psrl_w;
8540 case Intrinsic::x86_mmx_psrli_d:
8541 NewIntNo = Intrinsic::x86_mmx_psrl_d;
8543 case Intrinsic::x86_mmx_psrli_q:
8544 NewIntNo = Intrinsic::x86_mmx_psrl_q;
8546 case Intrinsic::x86_mmx_psrai_w:
8547 NewIntNo = Intrinsic::x86_mmx_psra_w;
8549 case Intrinsic::x86_mmx_psrai_d:
8550 NewIntNo = Intrinsic::x86_mmx_psra_d;
8552 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8558 // The vector shift intrinsics with scalars uses 32b shift amounts but
8559 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8563 ShOps[1] = DAG.getConstant(0, MVT::i32);
8564 if (ShAmtVT == MVT::v4i32) {
8565 ShOps[2] = DAG.getUNDEF(MVT::i32);
8566 ShOps[3] = DAG.getUNDEF(MVT::i32);
8567 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8569 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8570 // FIXME this must be lowered to get rid of the invalid type.
8573 EVT VT = Op.getValueType();
8574 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8575 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8576 DAG.getConstant(NewIntNo, MVT::i32),
8577 Op.getOperand(1), ShAmt);
8582 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8583 SelectionDAG &DAG) const {
8584 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8585 MFI->setReturnAddressIsTaken(true);
8587 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8588 DebugLoc dl = Op.getDebugLoc();
8591 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8593 DAG.getConstant(TD->getPointerSize(),
8594 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8595 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8596 DAG.getNode(ISD::ADD, dl, getPointerTy(),
8598 MachinePointerInfo(), false, false, 0);
8601 // Just load the return address.
8602 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8603 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8604 RetAddrFI, MachinePointerInfo(), false, false, 0);
8607 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8608 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8609 MFI->setFrameAddressIsTaken(true);
8611 EVT VT = Op.getValueType();
8612 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
8613 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8614 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8615 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8617 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8618 MachinePointerInfo(),
8623 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8624 SelectionDAG &DAG) const {
8625 return DAG.getIntPtrConstant(2*TD->getPointerSize());
8628 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8629 MachineFunction &MF = DAG.getMachineFunction();
8630 SDValue Chain = Op.getOperand(0);
8631 SDValue Offset = Op.getOperand(1);
8632 SDValue Handler = Op.getOperand(2);
8633 DebugLoc dl = Op.getDebugLoc();
8635 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8636 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8638 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8640 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8641 DAG.getIntPtrConstant(TD->getPointerSize()));
8642 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8643 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8645 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8646 MF.getRegInfo().addLiveOut(StoreAddrReg);
8648 return DAG.getNode(X86ISD::EH_RETURN, dl,
8650 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8653 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8654 SelectionDAG &DAG) const {
8655 SDValue Root = Op.getOperand(0);
8656 SDValue Trmp = Op.getOperand(1); // trampoline
8657 SDValue FPtr = Op.getOperand(2); // nested function
8658 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8659 DebugLoc dl = Op.getDebugLoc();
8661 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8663 if (Subtarget->is64Bit()) {
8664 SDValue OutChains[6];
8666 // Large code-model.
8667 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8668 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8670 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
8671 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
8673 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8675 // Load the pointer to the nested function into R11.
8676 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8677 SDValue Addr = Trmp;
8678 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8679 Addr, MachinePointerInfo(TrmpAddr),
8682 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8683 DAG.getConstant(2, MVT::i64));
8684 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8685 MachinePointerInfo(TrmpAddr, 2),
8688 // Load the 'nest' parameter value into R10.
8689 // R10 is specified in X86CallingConv.td
8690 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8691 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8692 DAG.getConstant(10, MVT::i64));
8693 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8694 Addr, MachinePointerInfo(TrmpAddr, 10),
8697 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8698 DAG.getConstant(12, MVT::i64));
8699 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8700 MachinePointerInfo(TrmpAddr, 12),
8703 // Jump to the nested function.
8704 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8705 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8706 DAG.getConstant(20, MVT::i64));
8707 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8708 Addr, MachinePointerInfo(TrmpAddr, 20),
8711 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8712 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8713 DAG.getConstant(22, MVT::i64));
8714 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8715 MachinePointerInfo(TrmpAddr, 22),
8719 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8720 return DAG.getMergeValues(Ops, 2, dl);
8722 const Function *Func =
8723 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8724 CallingConv::ID CC = Func->getCallingConv();
8729 llvm_unreachable("Unsupported calling convention");
8730 case CallingConv::C:
8731 case CallingConv::X86_StdCall: {
8732 // Pass 'nest' parameter in ECX.
8733 // Must be kept in sync with X86CallingConv.td
8736 // Check that ECX wasn't needed by an 'inreg' parameter.
8737 FunctionType *FTy = Func->getFunctionType();
8738 const AttrListPtr &Attrs = Func->getAttributes();
8740 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8741 unsigned InRegCount = 0;
8744 for (FunctionType::param_iterator I = FTy->param_begin(),
8745 E = FTy->param_end(); I != E; ++I, ++Idx)
8746 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8747 // FIXME: should only count parameters that are lowered to integers.
8748 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8750 if (InRegCount > 2) {
8751 report_fatal_error("Nest register in use - reduce number of inreg"
8757 case CallingConv::X86_FastCall:
8758 case CallingConv::X86_ThisCall:
8759 case CallingConv::Fast:
8760 // Pass 'nest' parameter in EAX.
8761 // Must be kept in sync with X86CallingConv.td
8766 SDValue OutChains[4];
8769 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8770 DAG.getConstant(10, MVT::i32));
8771 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8773 // This is storing the opcode for MOV32ri.
8774 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8775 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
8776 OutChains[0] = DAG.getStore(Root, dl,
8777 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8778 Trmp, MachinePointerInfo(TrmpAddr),
8781 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8782 DAG.getConstant(1, MVT::i32));
8783 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8784 MachinePointerInfo(TrmpAddr, 1),
8787 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8788 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8789 DAG.getConstant(5, MVT::i32));
8790 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8791 MachinePointerInfo(TrmpAddr, 5),
8794 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8795 DAG.getConstant(6, MVT::i32));
8796 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8797 MachinePointerInfo(TrmpAddr, 6),
8801 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8802 return DAG.getMergeValues(Ops, 2, dl);
8806 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8807 SelectionDAG &DAG) const {
8809 The rounding mode is in bits 11:10 of FPSR, and has the following
8816 FLT_ROUNDS, on the other hand, expects the following:
8823 To perform the conversion, we do:
8824 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8827 MachineFunction &MF = DAG.getMachineFunction();
8828 const TargetMachine &TM = MF.getTarget();
8829 const TargetFrameLowering &TFI = *TM.getFrameLowering();
8830 unsigned StackAlignment = TFI.getStackAlignment();
8831 EVT VT = Op.getValueType();
8832 DebugLoc DL = Op.getDebugLoc();
8834 // Save FP Control Word to stack slot
8835 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8836 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8839 MachineMemOperand *MMO =
8840 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8841 MachineMemOperand::MOStore, 2, 2);
8843 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8844 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8845 DAG.getVTList(MVT::Other),
8846 Ops, 2, MVT::i16, MMO);
8848 // Load FP Control Word from stack slot
8849 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8850 MachinePointerInfo(), false, false, 0);
8852 // Transform as necessary
8854 DAG.getNode(ISD::SRL, DL, MVT::i16,
8855 DAG.getNode(ISD::AND, DL, MVT::i16,
8856 CWD, DAG.getConstant(0x800, MVT::i16)),
8857 DAG.getConstant(11, MVT::i8));
8859 DAG.getNode(ISD::SRL, DL, MVT::i16,
8860 DAG.getNode(ISD::AND, DL, MVT::i16,
8861 CWD, DAG.getConstant(0x400, MVT::i16)),
8862 DAG.getConstant(9, MVT::i8));
8865 DAG.getNode(ISD::AND, DL, MVT::i16,
8866 DAG.getNode(ISD::ADD, DL, MVT::i16,
8867 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8868 DAG.getConstant(1, MVT::i16)),
8869 DAG.getConstant(3, MVT::i16));
8872 return DAG.getNode((VT.getSizeInBits() < 16 ?
8873 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8876 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8877 EVT VT = Op.getValueType();
8879 unsigned NumBits = VT.getSizeInBits();
8880 DebugLoc dl = Op.getDebugLoc();
8882 Op = Op.getOperand(0);
8883 if (VT == MVT::i8) {
8884 // Zero extend to i32 since there is not an i8 bsr.
8886 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8889 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8890 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8891 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8893 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8896 DAG.getConstant(NumBits+NumBits-1, OpVT),
8897 DAG.getConstant(X86::COND_E, MVT::i8),
8900 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8902 // Finally xor with NumBits-1.
8903 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8906 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8910 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8911 EVT VT = Op.getValueType();
8913 unsigned NumBits = VT.getSizeInBits();
8914 DebugLoc dl = Op.getDebugLoc();
8916 Op = Op.getOperand(0);
8917 if (VT == MVT::i8) {
8919 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8922 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8923 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8924 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8926 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8929 DAG.getConstant(NumBits, OpVT),
8930 DAG.getConstant(X86::COND_E, MVT::i8),
8933 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8936 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8940 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8941 EVT VT = Op.getValueType();
8942 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8943 DebugLoc dl = Op.getDebugLoc();
8945 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8946 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8947 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8948 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8949 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8951 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8952 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8953 // return AloBlo + AloBhi + AhiBlo;
8955 SDValue A = Op.getOperand(0);
8956 SDValue B = Op.getOperand(1);
8958 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8959 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8960 A, DAG.getConstant(32, MVT::i32));
8961 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8962 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8963 B, DAG.getConstant(32, MVT::i32));
8964 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8965 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8967 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8968 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8970 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8971 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8973 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8974 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8975 AloBhi, DAG.getConstant(32, MVT::i32));
8976 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8977 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8978 AhiBlo, DAG.getConstant(32, MVT::i32));
8979 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8980 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8984 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8986 EVT VT = Op.getValueType();
8987 DebugLoc dl = Op.getDebugLoc();
8988 SDValue R = Op.getOperand(0);
8989 SDValue Amt = Op.getOperand(1);
8991 LLVMContext *Context = DAG.getContext();
8994 if (!Subtarget->hasSSE2()) return SDValue();
8996 // Optimize shl/srl/sra with constant shift amount.
8997 if (isSplatVector(Amt.getNode())) {
8998 SDValue SclrAmt = Amt->getOperand(0);
8999 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
9000 uint64_t ShiftAmt = C->getZExtValue();
9002 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
9003 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9004 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9005 R, DAG.getConstant(ShiftAmt, MVT::i32));
9007 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
9008 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9009 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9010 R, DAG.getConstant(ShiftAmt, MVT::i32));
9012 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
9013 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9014 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9015 R, DAG.getConstant(ShiftAmt, MVT::i32));
9017 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
9018 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9019 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9020 R, DAG.getConstant(ShiftAmt, MVT::i32));
9022 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
9023 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9024 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9025 R, DAG.getConstant(ShiftAmt, MVT::i32));
9027 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
9028 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9029 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9030 R, DAG.getConstant(ShiftAmt, MVT::i32));
9032 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
9033 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9034 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9035 R, DAG.getConstant(ShiftAmt, MVT::i32));
9037 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
9038 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9039 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9040 R, DAG.getConstant(ShiftAmt, MVT::i32));
9044 // Lower SHL with variable shift amount.
9045 // Cannot lower SHL without SSE2 or later.
9046 if (!Subtarget->hasSSE2()) return SDValue();
9048 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
9049 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9050 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9051 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
9053 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
9055 std::vector<Constant*> CV(4, CI);
9056 Constant *C = ConstantVector::get(CV);
9057 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9058 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9059 MachinePointerInfo::getConstantPool(),
9062 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
9063 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
9064 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9065 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9067 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9069 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9070 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9071 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9073 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
9074 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
9076 std::vector<Constant*> CVM1(16, CM1);
9077 std::vector<Constant*> CVM2(16, CM2);
9078 Constant *C = ConstantVector::get(CVM1);
9079 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9080 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9081 MachinePointerInfo::getConstantPool(),
9084 // r = pblendv(r, psllw(r & (char16)15, 4), a);
9085 M = DAG.getNode(ISD::AND, dl, VT, R, M);
9086 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9087 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9088 DAG.getConstant(4, MVT::i32));
9089 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9091 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9093 C = ConstantVector::get(CVM2);
9094 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9095 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9096 MachinePointerInfo::getConstantPool(),
9099 // r = pblendv(r, psllw(r & (char16)63, 2), a);
9100 M = DAG.getNode(ISD::AND, dl, VT, R, M);
9101 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9102 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9103 DAG.getConstant(2, MVT::i32));
9104 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9106 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9108 // return pblendv(r, r+r, a);
9109 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
9110 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
9116 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
9117 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
9118 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
9119 // looks for this combo and may remove the "setcc" instruction if the "setcc"
9120 // has only one use.
9121 SDNode *N = Op.getNode();
9122 SDValue LHS = N->getOperand(0);
9123 SDValue RHS = N->getOperand(1);
9124 unsigned BaseOp = 0;
9126 DebugLoc DL = Op.getDebugLoc();
9127 switch (Op.getOpcode()) {
9128 default: llvm_unreachable("Unknown ovf instruction!");
9130 // A subtract of one will be selected as a INC. Note that INC doesn't
9131 // set CF, so we can't do this for UADDO.
9132 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9134 BaseOp = X86ISD::INC;
9138 BaseOp = X86ISD::ADD;
9142 BaseOp = X86ISD::ADD;
9146 // A subtract of one will be selected as a DEC. Note that DEC doesn't
9147 // set CF, so we can't do this for USUBO.
9148 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9150 BaseOp = X86ISD::DEC;
9154 BaseOp = X86ISD::SUB;
9158 BaseOp = X86ISD::SUB;
9162 BaseOp = X86ISD::SMUL;
9165 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9166 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9168 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9171 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9172 DAG.getConstant(X86::COND_O, MVT::i32),
9173 SDValue(Sum.getNode(), 2));
9175 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9180 // Also sets EFLAGS.
9181 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9182 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9185 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9186 DAG.getConstant(Cond, MVT::i32),
9187 SDValue(Sum.getNode(), 1));
9189 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9193 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
9194 DebugLoc dl = Op.getDebugLoc();
9195 SDNode* Node = Op.getNode();
9196 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
9197 EVT VT = Node->getValueType(0);
9199 if (Subtarget->hasSSE2() && VT.isVector()) {
9200 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
9201 ExtraVT.getScalarType().getSizeInBits();
9202 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
9204 unsigned SHLIntrinsicsID = 0;
9205 unsigned SRAIntrinsicsID = 0;
9206 switch (VT.getSimpleVT().SimpleTy) {
9210 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q;
9211 SRAIntrinsicsID = 0;
9215 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
9216 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
9220 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
9221 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
9226 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9227 DAG.getConstant(SHLIntrinsicsID, MVT::i32),
9228 Node->getOperand(0), ShAmt);
9230 // In case of 1 bit sext, no need to shr
9231 if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
9233 if (SRAIntrinsicsID) {
9234 Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9235 DAG.getConstant(SRAIntrinsicsID, MVT::i32),
9245 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9246 DebugLoc dl = Op.getDebugLoc();
9248 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
9249 // There isn't any reason to disable it if the target processor supports it.
9250 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
9251 SDValue Chain = Op.getOperand(0);
9252 SDValue Zero = DAG.getConstant(0, MVT::i32);
9254 DAG.getRegister(X86::ESP, MVT::i32), // Base
9255 DAG.getTargetConstant(1, MVT::i8), // Scale
9256 DAG.getRegister(0, MVT::i32), // Index
9257 DAG.getTargetConstant(0, MVT::i32), // Disp
9258 DAG.getRegister(0, MVT::i32), // Segment.
9263 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9264 array_lengthof(Ops));
9265 return SDValue(Res, 0);
9268 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9270 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9272 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9273 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9274 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9275 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9277 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9278 if (!Op1 && !Op2 && !Op3 && Op4)
9279 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9281 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9282 if (Op1 && !Op2 && !Op3 && !Op4)
9283 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9285 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9287 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9290 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9291 EVT T = Op.getValueType();
9292 DebugLoc DL = Op.getDebugLoc();
9295 switch(T.getSimpleVT().SimpleTy) {
9297 assert(false && "Invalid value type!");
9298 case MVT::i8: Reg = X86::AL; size = 1; break;
9299 case MVT::i16: Reg = X86::AX; size = 2; break;
9300 case MVT::i32: Reg = X86::EAX; size = 4; break;
9302 assert(Subtarget->is64Bit() && "Node not type legal!");
9303 Reg = X86::RAX; size = 8;
9306 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9307 Op.getOperand(2), SDValue());
9308 SDValue Ops[] = { cpIn.getValue(0),
9311 DAG.getTargetConstant(size, MVT::i8),
9313 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9314 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9315 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9318 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9322 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9323 SelectionDAG &DAG) const {
9324 assert(Subtarget->is64Bit() && "Result not type legalized?");
9325 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9326 SDValue TheChain = Op.getOperand(0);
9327 DebugLoc dl = Op.getDebugLoc();
9328 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9329 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9330 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9332 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9333 DAG.getConstant(32, MVT::i8));
9335 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9338 return DAG.getMergeValues(Ops, 2, dl);
9341 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9342 SelectionDAG &DAG) const {
9343 EVT SrcVT = Op.getOperand(0).getValueType();
9344 EVT DstVT = Op.getValueType();
9345 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9346 Subtarget->hasMMX() && "Unexpected custom BITCAST");
9347 assert((DstVT == MVT::i64 ||
9348 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9349 "Unexpected custom BITCAST");
9350 // i64 <=> MMX conversions are Legal.
9351 if (SrcVT==MVT::i64 && DstVT.isVector())
9353 if (DstVT==MVT::i64 && SrcVT.isVector())
9355 // MMX <=> MMX conversions are Legal.
9356 if (SrcVT.isVector() && DstVT.isVector())
9358 // All other conversions need to be expanded.
9362 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9363 SDNode *Node = Op.getNode();
9364 DebugLoc dl = Node->getDebugLoc();
9365 EVT T = Node->getValueType(0);
9366 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9367 DAG.getConstant(0, T), Node->getOperand(2));
9368 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9369 cast<AtomicSDNode>(Node)->getMemoryVT(),
9370 Node->getOperand(0),
9371 Node->getOperand(1), negOp,
9372 cast<AtomicSDNode>(Node)->getSrcValue(),
9373 cast<AtomicSDNode>(Node)->getAlignment());
9376 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9377 EVT VT = Op.getNode()->getValueType(0);
9379 // Let legalize expand this if it isn't a legal type yet.
9380 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9383 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9386 bool ExtraOp = false;
9387 switch (Op.getOpcode()) {
9388 default: assert(0 && "Invalid code");
9389 case ISD::ADDC: Opc = X86ISD::ADD; break;
9390 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9391 case ISD::SUBC: Opc = X86ISD::SUB; break;
9392 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9396 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9398 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9399 Op.getOperand(1), Op.getOperand(2));
9402 /// LowerOperation - Provide custom lowering hooks for some operations.
9404 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9405 switch (Op.getOpcode()) {
9406 default: llvm_unreachable("Should not custom lower this!");
9407 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
9408 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
9409 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
9410 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
9411 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
9412 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
9413 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
9414 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9415 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9416 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
9417 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
9418 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
9419 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9420 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9421 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9422 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
9423 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
9424 case ISD::SHL_PARTS:
9425 case ISD::SRA_PARTS:
9426 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
9427 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
9428 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
9429 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
9430 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
9431 case ISD::FABS: return LowerFABS(Op, DAG);
9432 case ISD::FNEG: return LowerFNEG(Op, DAG);
9433 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
9434 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
9435 case ISD::SETCC: return LowerSETCC(Op, DAG);
9436 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
9437 case ISD::SELECT: return LowerSELECT(Op, DAG);
9438 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
9439 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
9440 case ISD::VASTART: return LowerVASTART(Op, DAG);
9441 case ISD::VAARG: return LowerVAARG(Op, DAG);
9442 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
9443 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9444 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
9445 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
9446 case ISD::FRAME_TO_ARGS_OFFSET:
9447 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9448 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9449 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
9450 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
9451 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
9452 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
9453 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
9454 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
9457 case ISD::SHL: return LowerShift(Op, DAG);
9463 case ISD::UMULO: return LowerXALUO(Op, DAG);
9464 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
9465 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
9469 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9473 void X86TargetLowering::
9474 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9475 SelectionDAG &DAG, unsigned NewOp) const {
9476 EVT T = Node->getValueType(0);
9477 DebugLoc dl = Node->getDebugLoc();
9478 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9480 SDValue Chain = Node->getOperand(0);
9481 SDValue In1 = Node->getOperand(1);
9482 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9483 Node->getOperand(2), DAG.getIntPtrConstant(0));
9484 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9485 Node->getOperand(2), DAG.getIntPtrConstant(1));
9486 SDValue Ops[] = { Chain, In1, In2L, In2H };
9487 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9489 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9490 cast<MemSDNode>(Node)->getMemOperand());
9491 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9492 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9493 Results.push_back(Result.getValue(2));
9496 /// ReplaceNodeResults - Replace a node with an illegal result type
9497 /// with a new node built out of custom code.
9498 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9499 SmallVectorImpl<SDValue>&Results,
9500 SelectionDAG &DAG) const {
9501 DebugLoc dl = N->getDebugLoc();
9502 switch (N->getOpcode()) {
9504 assert(false && "Do not know how to custom type legalize this operation!");
9506 case ISD::SIGN_EXTEND_INREG:
9511 // We don't want to expand or promote these.
9513 case ISD::FP_TO_SINT: {
9514 std::pair<SDValue,SDValue> Vals =
9515 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9516 SDValue FIST = Vals.first, StackSlot = Vals.second;
9517 if (FIST.getNode() != 0) {
9518 EVT VT = N->getValueType(0);
9519 // Return a load from the stack slot.
9520 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9521 MachinePointerInfo(), false, false, 0));
9525 case ISD::READCYCLECOUNTER: {
9526 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9527 SDValue TheChain = N->getOperand(0);
9528 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9529 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9531 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9533 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9534 SDValue Ops[] = { eax, edx };
9535 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9536 Results.push_back(edx.getValue(1));
9539 case ISD::ATOMIC_CMP_SWAP: {
9540 EVT T = N->getValueType(0);
9541 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9542 SDValue cpInL, cpInH;
9543 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9544 DAG.getConstant(0, MVT::i32));
9545 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9546 DAG.getConstant(1, MVT::i32));
9547 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9548 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9550 SDValue swapInL, swapInH;
9551 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9552 DAG.getConstant(0, MVT::i32));
9553 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9554 DAG.getConstant(1, MVT::i32));
9555 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9557 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9558 swapInL.getValue(1));
9559 SDValue Ops[] = { swapInH.getValue(0),
9561 swapInH.getValue(1) };
9562 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9563 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9564 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9566 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9567 MVT::i32, Result.getValue(1));
9568 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9569 MVT::i32, cpOutL.getValue(2));
9570 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9571 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9572 Results.push_back(cpOutH.getValue(1));
9575 case ISD::ATOMIC_LOAD_ADD:
9576 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9578 case ISD::ATOMIC_LOAD_AND:
9579 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9581 case ISD::ATOMIC_LOAD_NAND:
9582 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9584 case ISD::ATOMIC_LOAD_OR:
9585 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9587 case ISD::ATOMIC_LOAD_SUB:
9588 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9590 case ISD::ATOMIC_LOAD_XOR:
9591 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9593 case ISD::ATOMIC_SWAP:
9594 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9599 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9601 default: return NULL;
9602 case X86ISD::BSF: return "X86ISD::BSF";
9603 case X86ISD::BSR: return "X86ISD::BSR";
9604 case X86ISD::SHLD: return "X86ISD::SHLD";
9605 case X86ISD::SHRD: return "X86ISD::SHRD";
9606 case X86ISD::FAND: return "X86ISD::FAND";
9607 case X86ISD::FOR: return "X86ISD::FOR";
9608 case X86ISD::FXOR: return "X86ISD::FXOR";
9609 case X86ISD::FSRL: return "X86ISD::FSRL";
9610 case X86ISD::FILD: return "X86ISD::FILD";
9611 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
9612 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9613 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9614 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9615 case X86ISD::FLD: return "X86ISD::FLD";
9616 case X86ISD::FST: return "X86ISD::FST";
9617 case X86ISD::CALL: return "X86ISD::CALL";
9618 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
9619 case X86ISD::BT: return "X86ISD::BT";
9620 case X86ISD::CMP: return "X86ISD::CMP";
9621 case X86ISD::COMI: return "X86ISD::COMI";
9622 case X86ISD::UCOMI: return "X86ISD::UCOMI";
9623 case X86ISD::SETCC: return "X86ISD::SETCC";
9624 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
9625 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
9626 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
9627 case X86ISD::CMOV: return "X86ISD::CMOV";
9628 case X86ISD::BRCOND: return "X86ISD::BRCOND";
9629 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
9630 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
9631 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
9632 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
9633 case X86ISD::Wrapper: return "X86ISD::Wrapper";
9634 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
9635 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
9636 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
9637 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
9638 case X86ISD::PINSRB: return "X86ISD::PINSRB";
9639 case X86ISD::PINSRW: return "X86ISD::PINSRW";
9640 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
9641 case X86ISD::ANDNP: return "X86ISD::ANDNP";
9642 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
9643 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
9644 case X86ISD::PSIGND: return "X86ISD::PSIGND";
9645 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB";
9646 case X86ISD::FMAX: return "X86ISD::FMAX";
9647 case X86ISD::FMIN: return "X86ISD::FMIN";
9648 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
9649 case X86ISD::FRCP: return "X86ISD::FRCP";
9650 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
9651 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
9652 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
9653 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
9654 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
9655 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
9656 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
9657 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
9658 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
9659 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
9660 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
9661 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
9662 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
9663 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
9664 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
9665 case X86ISD::VSHL: return "X86ISD::VSHL";
9666 case X86ISD::VSRL: return "X86ISD::VSRL";
9667 case X86ISD::CMPPD: return "X86ISD::CMPPD";
9668 case X86ISD::CMPPS: return "X86ISD::CMPPS";
9669 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
9670 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
9671 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
9672 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
9673 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
9674 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
9675 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
9676 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
9677 case X86ISD::ADD: return "X86ISD::ADD";
9678 case X86ISD::SUB: return "X86ISD::SUB";
9679 case X86ISD::ADC: return "X86ISD::ADC";
9680 case X86ISD::SBB: return "X86ISD::SBB";
9681 case X86ISD::SMUL: return "X86ISD::SMUL";
9682 case X86ISD::UMUL: return "X86ISD::UMUL";
9683 case X86ISD::INC: return "X86ISD::INC";
9684 case X86ISD::DEC: return "X86ISD::DEC";
9685 case X86ISD::OR: return "X86ISD::OR";
9686 case X86ISD::XOR: return "X86ISD::XOR";
9687 case X86ISD::AND: return "X86ISD::AND";
9688 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
9689 case X86ISD::PTEST: return "X86ISD::PTEST";
9690 case X86ISD::TESTP: return "X86ISD::TESTP";
9691 case X86ISD::PALIGN: return "X86ISD::PALIGN";
9692 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
9693 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
9694 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
9695 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
9696 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
9697 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
9698 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
9699 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
9700 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
9701 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
9702 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
9703 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
9704 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
9705 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
9706 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
9707 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
9708 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
9709 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
9710 case X86ISD::MOVSD: return "X86ISD::MOVSD";
9711 case X86ISD::MOVSS: return "X86ISD::MOVSS";
9712 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
9713 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
9714 case X86ISD::VUNPCKLPS: return "X86ISD::VUNPCKLPS";
9715 case X86ISD::VUNPCKLPD: return "X86ISD::VUNPCKLPD";
9716 case X86ISD::VUNPCKLPSY: return "X86ISD::VUNPCKLPSY";
9717 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
9718 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
9719 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
9720 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
9721 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
9722 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
9723 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
9724 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
9725 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
9726 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
9727 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
9728 case X86ISD::VPERMIL: return "X86ISD::VPERMIL";
9729 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9730 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
9731 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
9735 // isLegalAddressingMode - Return true if the addressing mode represented
9736 // by AM is legal for this target, for a load/store of the specified type.
9737 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9739 // X86 supports extremely general addressing modes.
9740 CodeModel::Model M = getTargetMachine().getCodeModel();
9741 Reloc::Model R = getTargetMachine().getRelocationModel();
9743 // X86 allows a sign-extended 32-bit immediate field as a displacement.
9744 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9749 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9751 // If a reference to this global requires an extra load, we can't fold it.
9752 if (isGlobalStubReference(GVFlags))
9755 // If BaseGV requires a register for the PIC base, we cannot also have a
9756 // BaseReg specified.
9757 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9760 // If lower 4G is not available, then we must use rip-relative addressing.
9761 if ((M != CodeModel::Small || R != Reloc::Static) &&
9762 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9772 // These scales always work.
9777 // These scales are formed with basereg+scalereg. Only accept if there is
9782 default: // Other stuff never works.
9790 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9791 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9793 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9794 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9795 if (NumBits1 <= NumBits2)
9800 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9801 if (!VT1.isInteger() || !VT2.isInteger())
9803 unsigned NumBits1 = VT1.getSizeInBits();
9804 unsigned NumBits2 = VT2.getSizeInBits();
9805 if (NumBits1 <= NumBits2)
9810 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
9811 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9812 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9815 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9816 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9817 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9820 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9821 // i16 instructions are longer (0x66 prefix) and potentially slower.
9822 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9825 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9826 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9827 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9828 /// are assumed to be legal.
9830 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9832 // Very little shuffling can be done for 64-bit vectors right now.
9833 if (VT.getSizeInBits() == 64)
9834 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9836 // FIXME: pshufb, blends, shifts.
9837 return (VT.getVectorNumElements() == 2 ||
9838 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9839 isMOVLMask(M, VT) ||
9840 isSHUFPMask(M, VT) ||
9841 isPSHUFDMask(M, VT) ||
9842 isPSHUFHWMask(M, VT) ||
9843 isPSHUFLWMask(M, VT) ||
9844 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9845 isUNPCKLMask(M, VT) ||
9846 isUNPCKHMask(M, VT) ||
9847 isUNPCKL_v_undef_Mask(M, VT) ||
9848 isUNPCKH_v_undef_Mask(M, VT));
9852 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9854 unsigned NumElts = VT.getVectorNumElements();
9855 // FIXME: This collection of masks seems suspect.
9858 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9859 return (isMOVLMask(Mask, VT) ||
9860 isCommutedMOVLMask(Mask, VT, true) ||
9861 isSHUFPMask(Mask, VT) ||
9862 isCommutedSHUFPMask(Mask, VT));
9867 //===----------------------------------------------------------------------===//
9868 // X86 Scheduler Hooks
9869 //===----------------------------------------------------------------------===//
9871 // private utility function
9873 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9874 MachineBasicBlock *MBB,
9881 TargetRegisterClass *RC,
9882 bool invSrc) const {
9883 // For the atomic bitwise operator, we generate
9886 // ld t1 = [bitinstr.addr]
9887 // op t2 = t1, [bitinstr.val]
9889 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9891 // fallthrough -->nextMBB
9892 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9893 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9894 MachineFunction::iterator MBBIter = MBB;
9897 /// First build the CFG
9898 MachineFunction *F = MBB->getParent();
9899 MachineBasicBlock *thisMBB = MBB;
9900 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9901 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9902 F->insert(MBBIter, newMBB);
9903 F->insert(MBBIter, nextMBB);
9905 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9906 nextMBB->splice(nextMBB->begin(), thisMBB,
9907 llvm::next(MachineBasicBlock::iterator(bInstr)),
9909 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9911 // Update thisMBB to fall through to newMBB
9912 thisMBB->addSuccessor(newMBB);
9914 // newMBB jumps to itself and fall through to nextMBB
9915 newMBB->addSuccessor(nextMBB);
9916 newMBB->addSuccessor(newMBB);
9918 // Insert instructions into newMBB based on incoming instruction
9919 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9920 "unexpected number of operands");
9921 DebugLoc dl = bInstr->getDebugLoc();
9922 MachineOperand& destOper = bInstr->getOperand(0);
9923 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9924 int numArgs = bInstr->getNumOperands() - 1;
9925 for (int i=0; i < numArgs; ++i)
9926 argOpers[i] = &bInstr->getOperand(i+1);
9928 // x86 address has 4 operands: base, index, scale, and displacement
9929 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9930 int valArgIndx = lastAddrIndx + 1;
9932 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9933 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9934 for (int i=0; i <= lastAddrIndx; ++i)
9935 (*MIB).addOperand(*argOpers[i]);
9937 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9939 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9944 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9945 assert((argOpers[valArgIndx]->isReg() ||
9946 argOpers[valArgIndx]->isImm()) &&
9948 if (argOpers[valArgIndx]->isReg())
9949 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9951 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9953 (*MIB).addOperand(*argOpers[valArgIndx]);
9955 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9958 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9959 for (int i=0; i <= lastAddrIndx; ++i)
9960 (*MIB).addOperand(*argOpers[i]);
9962 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9963 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9964 bInstr->memoperands_end());
9966 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9970 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9972 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9976 // private utility function: 64 bit atomics on 32 bit host.
9978 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9979 MachineBasicBlock *MBB,
9984 bool invSrc) const {
9985 // For the atomic bitwise operator, we generate
9986 // thisMBB (instructions are in pairs, except cmpxchg8b)
9987 // ld t1,t2 = [bitinstr.addr]
9989 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9990 // op t5, t6 <- out1, out2, [bitinstr.val]
9991 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9992 // mov ECX, EBX <- t5, t6
9993 // mov EAX, EDX <- t1, t2
9994 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9995 // mov t3, t4 <- EAX, EDX
9997 // result in out1, out2
9998 // fallthrough -->nextMBB
10000 const TargetRegisterClass *RC = X86::GR32RegisterClass;
10001 const unsigned LoadOpc = X86::MOV32rm;
10002 const unsigned NotOpc = X86::NOT32r;
10003 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10004 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10005 MachineFunction::iterator MBBIter = MBB;
10008 /// First build the CFG
10009 MachineFunction *F = MBB->getParent();
10010 MachineBasicBlock *thisMBB = MBB;
10011 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10012 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10013 F->insert(MBBIter, newMBB);
10014 F->insert(MBBIter, nextMBB);
10016 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10017 nextMBB->splice(nextMBB->begin(), thisMBB,
10018 llvm::next(MachineBasicBlock::iterator(bInstr)),
10020 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10022 // Update thisMBB to fall through to newMBB
10023 thisMBB->addSuccessor(newMBB);
10025 // newMBB jumps to itself and fall through to nextMBB
10026 newMBB->addSuccessor(nextMBB);
10027 newMBB->addSuccessor(newMBB);
10029 DebugLoc dl = bInstr->getDebugLoc();
10030 // Insert instructions into newMBB based on incoming instruction
10031 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
10032 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
10033 "unexpected number of operands");
10034 MachineOperand& dest1Oper = bInstr->getOperand(0);
10035 MachineOperand& dest2Oper = bInstr->getOperand(1);
10036 MachineOperand* argOpers[2 + X86::AddrNumOperands];
10037 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
10038 argOpers[i] = &bInstr->getOperand(i+2);
10040 // We use some of the operands multiple times, so conservatively just
10041 // clear any kill flags that might be present.
10042 if (argOpers[i]->isReg() && argOpers[i]->isUse())
10043 argOpers[i]->setIsKill(false);
10046 // x86 address has 5 operands: base, index, scale, displacement, and segment.
10047 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10049 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10050 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
10051 for (int i=0; i <= lastAddrIndx; ++i)
10052 (*MIB).addOperand(*argOpers[i]);
10053 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10054 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
10055 // add 4 to displacement.
10056 for (int i=0; i <= lastAddrIndx-2; ++i)
10057 (*MIB).addOperand(*argOpers[i]);
10058 MachineOperand newOp3 = *(argOpers[3]);
10059 if (newOp3.isImm())
10060 newOp3.setImm(newOp3.getImm()+4);
10062 newOp3.setOffset(newOp3.getOffset()+4);
10063 (*MIB).addOperand(newOp3);
10064 (*MIB).addOperand(*argOpers[lastAddrIndx]);
10066 // t3/4 are defined later, at the bottom of the loop
10067 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
10068 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
10069 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
10070 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
10071 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
10072 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
10074 // The subsequent operations should be using the destination registers of
10075 //the PHI instructions.
10077 t1 = F->getRegInfo().createVirtualRegister(RC);
10078 t2 = F->getRegInfo().createVirtualRegister(RC);
10079 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
10080 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
10082 t1 = dest1Oper.getReg();
10083 t2 = dest2Oper.getReg();
10086 int valArgIndx = lastAddrIndx + 1;
10087 assert((argOpers[valArgIndx]->isReg() ||
10088 argOpers[valArgIndx]->isImm()) &&
10089 "invalid operand");
10090 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
10091 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
10092 if (argOpers[valArgIndx]->isReg())
10093 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
10095 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
10096 if (regOpcL != X86::MOV32rr)
10098 (*MIB).addOperand(*argOpers[valArgIndx]);
10099 assert(argOpers[valArgIndx + 1]->isReg() ==
10100 argOpers[valArgIndx]->isReg());
10101 assert(argOpers[valArgIndx + 1]->isImm() ==
10102 argOpers[valArgIndx]->isImm());
10103 if (argOpers[valArgIndx + 1]->isReg())
10104 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
10106 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
10107 if (regOpcH != X86::MOV32rr)
10109 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
10111 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10113 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
10116 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
10118 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
10121 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
10122 for (int i=0; i <= lastAddrIndx; ++i)
10123 (*MIB).addOperand(*argOpers[i]);
10125 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10126 (*MIB).setMemRefs(bInstr->memoperands_begin(),
10127 bInstr->memoperands_end());
10129 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
10130 MIB.addReg(X86::EAX);
10131 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
10132 MIB.addReg(X86::EDX);
10135 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10137 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
10141 // private utility function
10142 MachineBasicBlock *
10143 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
10144 MachineBasicBlock *MBB,
10145 unsigned cmovOpc) const {
10146 // For the atomic min/max operator, we generate
10149 // ld t1 = [min/max.addr]
10150 // mov t2 = [min/max.val]
10152 // cmov[cond] t2 = t1
10154 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
10156 // fallthrough -->nextMBB
10158 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10159 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10160 MachineFunction::iterator MBBIter = MBB;
10163 /// First build the CFG
10164 MachineFunction *F = MBB->getParent();
10165 MachineBasicBlock *thisMBB = MBB;
10166 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10167 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10168 F->insert(MBBIter, newMBB);
10169 F->insert(MBBIter, nextMBB);
10171 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10172 nextMBB->splice(nextMBB->begin(), thisMBB,
10173 llvm::next(MachineBasicBlock::iterator(mInstr)),
10175 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10177 // Update thisMBB to fall through to newMBB
10178 thisMBB->addSuccessor(newMBB);
10180 // newMBB jumps to newMBB and fall through to nextMBB
10181 newMBB->addSuccessor(nextMBB);
10182 newMBB->addSuccessor(newMBB);
10184 DebugLoc dl = mInstr->getDebugLoc();
10185 // Insert instructions into newMBB based on incoming instruction
10186 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10187 "unexpected number of operands");
10188 MachineOperand& destOper = mInstr->getOperand(0);
10189 MachineOperand* argOpers[2 + X86::AddrNumOperands];
10190 int numArgs = mInstr->getNumOperands() - 1;
10191 for (int i=0; i < numArgs; ++i)
10192 argOpers[i] = &mInstr->getOperand(i+1);
10194 // x86 address has 4 operands: base, index, scale, and displacement
10195 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10196 int valArgIndx = lastAddrIndx + 1;
10198 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10199 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10200 for (int i=0; i <= lastAddrIndx; ++i)
10201 (*MIB).addOperand(*argOpers[i]);
10203 // We only support register and immediate values
10204 assert((argOpers[valArgIndx]->isReg() ||
10205 argOpers[valArgIndx]->isImm()) &&
10206 "invalid operand");
10208 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10209 if (argOpers[valArgIndx]->isReg())
10210 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10212 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10213 (*MIB).addOperand(*argOpers[valArgIndx]);
10215 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10218 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10223 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10224 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10228 // Cmp and exchange if none has modified the memory location
10229 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10230 for (int i=0; i <= lastAddrIndx; ++i)
10231 (*MIB).addOperand(*argOpers[i]);
10233 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10234 (*MIB).setMemRefs(mInstr->memoperands_begin(),
10235 mInstr->memoperands_end());
10237 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10238 MIB.addReg(X86::EAX);
10241 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10243 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
10247 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10248 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10249 // in the .td file.
10250 MachineBasicBlock *
10251 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10252 unsigned numArgs, bool memArg) const {
10253 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10254 "Target must have SSE4.2 or AVX features enabled");
10256 DebugLoc dl = MI->getDebugLoc();
10257 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10259 if (!Subtarget->hasAVX()) {
10261 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10263 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10266 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10268 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10271 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10272 for (unsigned i = 0; i < numArgs; ++i) {
10273 MachineOperand &Op = MI->getOperand(i+1);
10274 if (!(Op.isReg() && Op.isImplicit()))
10275 MIB.addOperand(Op);
10277 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10278 .addReg(X86::XMM0);
10280 MI->eraseFromParent();
10284 MachineBasicBlock *
10285 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10286 DebugLoc dl = MI->getDebugLoc();
10287 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10289 // Address into RAX/EAX, other two args into ECX, EDX.
10290 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10291 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10292 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10293 for (int i = 0; i < X86::AddrNumOperands; ++i)
10294 MIB.addOperand(MI->getOperand(i));
10296 unsigned ValOps = X86::AddrNumOperands;
10297 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10298 .addReg(MI->getOperand(ValOps).getReg());
10299 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10300 .addReg(MI->getOperand(ValOps+1).getReg());
10302 // The instruction doesn't actually take any operands though.
10303 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10305 MI->eraseFromParent(); // The pseudo is gone now.
10309 MachineBasicBlock *
10310 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10311 DebugLoc dl = MI->getDebugLoc();
10312 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10314 // First arg in ECX, the second in EAX.
10315 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10316 .addReg(MI->getOperand(0).getReg());
10317 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10318 .addReg(MI->getOperand(1).getReg());
10320 // The instruction doesn't actually take any operands though.
10321 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10323 MI->eraseFromParent(); // The pseudo is gone now.
10327 MachineBasicBlock *
10328 X86TargetLowering::EmitVAARG64WithCustomInserter(
10330 MachineBasicBlock *MBB) const {
10331 // Emit va_arg instruction on X86-64.
10333 // Operands to this pseudo-instruction:
10334 // 0 ) Output : destination address (reg)
10335 // 1-5) Input : va_list address (addr, i64mem)
10336 // 6 ) ArgSize : Size (in bytes) of vararg type
10337 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10338 // 8 ) Align : Alignment of type
10339 // 9 ) EFLAGS (implicit-def)
10341 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10342 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10344 unsigned DestReg = MI->getOperand(0).getReg();
10345 MachineOperand &Base = MI->getOperand(1);
10346 MachineOperand &Scale = MI->getOperand(2);
10347 MachineOperand &Index = MI->getOperand(3);
10348 MachineOperand &Disp = MI->getOperand(4);
10349 MachineOperand &Segment = MI->getOperand(5);
10350 unsigned ArgSize = MI->getOperand(6).getImm();
10351 unsigned ArgMode = MI->getOperand(7).getImm();
10352 unsigned Align = MI->getOperand(8).getImm();
10354 // Memory Reference
10355 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10356 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10357 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10359 // Machine Information
10360 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10361 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10362 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10363 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10364 DebugLoc DL = MI->getDebugLoc();
10366 // struct va_list {
10369 // i64 overflow_area (address)
10370 // i64 reg_save_area (address)
10372 // sizeof(va_list) = 24
10373 // alignment(va_list) = 8
10375 unsigned TotalNumIntRegs = 6;
10376 unsigned TotalNumXMMRegs = 8;
10377 bool UseGPOffset = (ArgMode == 1);
10378 bool UseFPOffset = (ArgMode == 2);
10379 unsigned MaxOffset = TotalNumIntRegs * 8 +
10380 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10382 /* Align ArgSize to a multiple of 8 */
10383 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10384 bool NeedsAlign = (Align > 8);
10386 MachineBasicBlock *thisMBB = MBB;
10387 MachineBasicBlock *overflowMBB;
10388 MachineBasicBlock *offsetMBB;
10389 MachineBasicBlock *endMBB;
10391 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
10392 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
10393 unsigned OffsetReg = 0;
10395 if (!UseGPOffset && !UseFPOffset) {
10396 // If we only pull from the overflow region, we don't create a branch.
10397 // We don't need to alter control flow.
10398 OffsetDestReg = 0; // unused
10399 OverflowDestReg = DestReg;
10402 overflowMBB = thisMBB;
10405 // First emit code to check if gp_offset (or fp_offset) is below the bound.
10406 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10407 // If not, pull from overflow_area. (branch to overflowMBB)
10412 // offsetMBB overflowMBB
10417 // Registers for the PHI in endMBB
10418 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10419 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10421 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10422 MachineFunction *MF = MBB->getParent();
10423 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10424 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10425 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10427 MachineFunction::iterator MBBIter = MBB;
10430 // Insert the new basic blocks
10431 MF->insert(MBBIter, offsetMBB);
10432 MF->insert(MBBIter, overflowMBB);
10433 MF->insert(MBBIter, endMBB);
10435 // Transfer the remainder of MBB and its successor edges to endMBB.
10436 endMBB->splice(endMBB->begin(), thisMBB,
10437 llvm::next(MachineBasicBlock::iterator(MI)),
10439 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10441 // Make offsetMBB and overflowMBB successors of thisMBB
10442 thisMBB->addSuccessor(offsetMBB);
10443 thisMBB->addSuccessor(overflowMBB);
10445 // endMBB is a successor of both offsetMBB and overflowMBB
10446 offsetMBB->addSuccessor(endMBB);
10447 overflowMBB->addSuccessor(endMBB);
10449 // Load the offset value into a register
10450 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10451 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10455 .addDisp(Disp, UseFPOffset ? 4 : 0)
10456 .addOperand(Segment)
10457 .setMemRefs(MMOBegin, MMOEnd);
10459 // Check if there is enough room left to pull this argument.
10460 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10462 .addImm(MaxOffset + 8 - ArgSizeA8);
10464 // Branch to "overflowMBB" if offset >= max
10465 // Fall through to "offsetMBB" otherwise
10466 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10467 .addMBB(overflowMBB);
10470 // In offsetMBB, emit code to use the reg_save_area.
10472 assert(OffsetReg != 0);
10474 // Read the reg_save_area address.
10475 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10476 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10481 .addOperand(Segment)
10482 .setMemRefs(MMOBegin, MMOEnd);
10484 // Zero-extend the offset
10485 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10486 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10489 .addImm(X86::sub_32bit);
10491 // Add the offset to the reg_save_area to get the final address.
10492 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10493 .addReg(OffsetReg64)
10494 .addReg(RegSaveReg);
10496 // Compute the offset for the next argument
10497 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10498 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10500 .addImm(UseFPOffset ? 16 : 8);
10502 // Store it back into the va_list.
10503 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10507 .addDisp(Disp, UseFPOffset ? 4 : 0)
10508 .addOperand(Segment)
10509 .addReg(NextOffsetReg)
10510 .setMemRefs(MMOBegin, MMOEnd);
10513 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10518 // Emit code to use overflow area
10521 // Load the overflow_area address into a register.
10522 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10523 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10528 .addOperand(Segment)
10529 .setMemRefs(MMOBegin, MMOEnd);
10531 // If we need to align it, do so. Otherwise, just copy the address
10532 // to OverflowDestReg.
10534 // Align the overflow address
10535 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10536 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10538 // aligned_addr = (addr + (align-1)) & ~(align-1)
10539 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10540 .addReg(OverflowAddrReg)
10543 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10545 .addImm(~(uint64_t)(Align-1));
10547 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10548 .addReg(OverflowAddrReg);
10551 // Compute the next overflow address after this argument.
10552 // (the overflow address should be kept 8-byte aligned)
10553 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10554 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10555 .addReg(OverflowDestReg)
10556 .addImm(ArgSizeA8);
10558 // Store the new overflow address.
10559 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10564 .addOperand(Segment)
10565 .addReg(NextAddrReg)
10566 .setMemRefs(MMOBegin, MMOEnd);
10568 // If we branched, emit the PHI to the front of endMBB.
10570 BuildMI(*endMBB, endMBB->begin(), DL,
10571 TII->get(X86::PHI), DestReg)
10572 .addReg(OffsetDestReg).addMBB(offsetMBB)
10573 .addReg(OverflowDestReg).addMBB(overflowMBB);
10576 // Erase the pseudo instruction
10577 MI->eraseFromParent();
10582 MachineBasicBlock *
10583 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10585 MachineBasicBlock *MBB) const {
10586 // Emit code to save XMM registers to the stack. The ABI says that the
10587 // number of registers to save is given in %al, so it's theoretically
10588 // possible to do an indirect jump trick to avoid saving all of them,
10589 // however this code takes a simpler approach and just executes all
10590 // of the stores if %al is non-zero. It's less code, and it's probably
10591 // easier on the hardware branch predictor, and stores aren't all that
10592 // expensive anyway.
10594 // Create the new basic blocks. One block contains all the XMM stores,
10595 // and one block is the final destination regardless of whether any
10596 // stores were performed.
10597 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10598 MachineFunction *F = MBB->getParent();
10599 MachineFunction::iterator MBBIter = MBB;
10601 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10602 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10603 F->insert(MBBIter, XMMSaveMBB);
10604 F->insert(MBBIter, EndMBB);
10606 // Transfer the remainder of MBB and its successor edges to EndMBB.
10607 EndMBB->splice(EndMBB->begin(), MBB,
10608 llvm::next(MachineBasicBlock::iterator(MI)),
10610 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10612 // The original block will now fall through to the XMM save block.
10613 MBB->addSuccessor(XMMSaveMBB);
10614 // The XMMSaveMBB will fall through to the end block.
10615 XMMSaveMBB->addSuccessor(EndMBB);
10617 // Now add the instructions.
10618 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10619 DebugLoc DL = MI->getDebugLoc();
10621 unsigned CountReg = MI->getOperand(0).getReg();
10622 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10623 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10625 if (!Subtarget->isTargetWin64()) {
10626 // If %al is 0, branch around the XMM save block.
10627 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10628 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10629 MBB->addSuccessor(EndMBB);
10632 // In the XMM save block, save all the XMM argument registers.
10633 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10634 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10635 MachineMemOperand *MMO =
10636 F->getMachineMemOperand(
10637 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10638 MachineMemOperand::MOStore,
10639 /*Size=*/16, /*Align=*/16);
10640 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10641 .addFrameIndex(RegSaveFrameIndex)
10642 .addImm(/*Scale=*/1)
10643 .addReg(/*IndexReg=*/0)
10644 .addImm(/*Disp=*/Offset)
10645 .addReg(/*Segment=*/0)
10646 .addReg(MI->getOperand(i).getReg())
10647 .addMemOperand(MMO);
10650 MI->eraseFromParent(); // The pseudo instruction is gone now.
10655 MachineBasicBlock *
10656 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10657 MachineBasicBlock *BB) const {
10658 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10659 DebugLoc DL = MI->getDebugLoc();
10661 // To "insert" a SELECT_CC instruction, we actually have to insert the
10662 // diamond control-flow pattern. The incoming instruction knows the
10663 // destination vreg to set, the condition code register to branch on, the
10664 // true/false values to select between, and a branch opcode to use.
10665 const BasicBlock *LLVM_BB = BB->getBasicBlock();
10666 MachineFunction::iterator It = BB;
10672 // cmpTY ccX, r1, r2
10674 // fallthrough --> copy0MBB
10675 MachineBasicBlock *thisMBB = BB;
10676 MachineFunction *F = BB->getParent();
10677 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10678 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10679 F->insert(It, copy0MBB);
10680 F->insert(It, sinkMBB);
10682 // If the EFLAGS register isn't dead in the terminator, then claim that it's
10683 // live into the sink and copy blocks.
10684 const MachineFunction *MF = BB->getParent();
10685 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10686 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10688 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10689 const MachineOperand &MO = MI->getOperand(I);
10690 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10691 unsigned Reg = MO.getReg();
10692 if (Reg != X86::EFLAGS) continue;
10693 copy0MBB->addLiveIn(Reg);
10694 sinkMBB->addLiveIn(Reg);
10697 // Transfer the remainder of BB and its successor edges to sinkMBB.
10698 sinkMBB->splice(sinkMBB->begin(), BB,
10699 llvm::next(MachineBasicBlock::iterator(MI)),
10701 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10703 // Add the true and fallthrough blocks as its successors.
10704 BB->addSuccessor(copy0MBB);
10705 BB->addSuccessor(sinkMBB);
10707 // Create the conditional branch instruction.
10709 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10710 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10713 // %FalseValue = ...
10714 // # fallthrough to sinkMBB
10715 copy0MBB->addSuccessor(sinkMBB);
10718 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10720 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10721 TII->get(X86::PHI), MI->getOperand(0).getReg())
10722 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10723 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10725 MI->eraseFromParent(); // The pseudo instruction is gone now.
10729 MachineBasicBlock *
10730 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10731 MachineBasicBlock *BB) const {
10732 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10733 DebugLoc DL = MI->getDebugLoc();
10735 assert(!Subtarget->isTargetEnvMacho());
10737 // The lowering is pretty easy: we're just emitting the call to _alloca. The
10738 // non-trivial part is impdef of ESP.
10740 if (Subtarget->isTargetWin64()) {
10741 if (Subtarget->isTargetCygMing()) {
10742 // ___chkstk(Mingw64):
10743 // Clobbers R10, R11, RAX and EFLAGS.
10745 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10746 .addExternalSymbol("___chkstk")
10747 .addReg(X86::RAX, RegState::Implicit)
10748 .addReg(X86::RSP, RegState::Implicit)
10749 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10750 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10751 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10753 // __chkstk(MSVCRT): does not update stack pointer.
10754 // Clobbers R10, R11 and EFLAGS.
10755 // FIXME: RAX(allocated size) might be reused and not killed.
10756 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10757 .addExternalSymbol("__chkstk")
10758 .addReg(X86::RAX, RegState::Implicit)
10759 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10760 // RAX has the offset to subtracted from RSP.
10761 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10766 const char *StackProbeSymbol =
10767 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10769 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10770 .addExternalSymbol(StackProbeSymbol)
10771 .addReg(X86::EAX, RegState::Implicit)
10772 .addReg(X86::ESP, RegState::Implicit)
10773 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10774 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10775 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10778 MI->eraseFromParent(); // The pseudo instruction is gone now.
10782 MachineBasicBlock *
10783 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10784 MachineBasicBlock *BB) const {
10785 // This is pretty easy. We're taking the value that we received from
10786 // our load from the relocation, sticking it in either RDI (x86-64)
10787 // or EAX and doing an indirect call. The return value will then
10788 // be in the normal return register.
10789 const X86InstrInfo *TII
10790 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10791 DebugLoc DL = MI->getDebugLoc();
10792 MachineFunction *F = BB->getParent();
10794 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10795 assert(MI->getOperand(3).isGlobal() && "This should be a global");
10797 if (Subtarget->is64Bit()) {
10798 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10799 TII->get(X86::MOV64rm), X86::RDI)
10801 .addImm(0).addReg(0)
10802 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10803 MI->getOperand(3).getTargetFlags())
10805 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10806 addDirectMem(MIB, X86::RDI);
10807 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10808 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10809 TII->get(X86::MOV32rm), X86::EAX)
10811 .addImm(0).addReg(0)
10812 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10813 MI->getOperand(3).getTargetFlags())
10815 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10816 addDirectMem(MIB, X86::EAX);
10818 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10819 TII->get(X86::MOV32rm), X86::EAX)
10820 .addReg(TII->getGlobalBaseReg(F))
10821 .addImm(0).addReg(0)
10822 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10823 MI->getOperand(3).getTargetFlags())
10825 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10826 addDirectMem(MIB, X86::EAX);
10829 MI->eraseFromParent(); // The pseudo instruction is gone now.
10833 MachineBasicBlock *
10834 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10835 MachineBasicBlock *BB) const {
10836 switch (MI->getOpcode()) {
10837 default: assert(false && "Unexpected instr type to insert");
10838 case X86::TAILJMPd64:
10839 case X86::TAILJMPr64:
10840 case X86::TAILJMPm64:
10841 assert(!"TAILJMP64 would not be touched here.");
10842 case X86::TCRETURNdi64:
10843 case X86::TCRETURNri64:
10844 case X86::TCRETURNmi64:
10845 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10846 // On AMD64, additional defs should be added before register allocation.
10847 if (!Subtarget->isTargetWin64()) {
10848 MI->addRegisterDefined(X86::RSI);
10849 MI->addRegisterDefined(X86::RDI);
10850 MI->addRegisterDefined(X86::XMM6);
10851 MI->addRegisterDefined(X86::XMM7);
10852 MI->addRegisterDefined(X86::XMM8);
10853 MI->addRegisterDefined(X86::XMM9);
10854 MI->addRegisterDefined(X86::XMM10);
10855 MI->addRegisterDefined(X86::XMM11);
10856 MI->addRegisterDefined(X86::XMM12);
10857 MI->addRegisterDefined(X86::XMM13);
10858 MI->addRegisterDefined(X86::XMM14);
10859 MI->addRegisterDefined(X86::XMM15);
10862 case X86::WIN_ALLOCA:
10863 return EmitLoweredWinAlloca(MI, BB);
10864 case X86::TLSCall_32:
10865 case X86::TLSCall_64:
10866 return EmitLoweredTLSCall(MI, BB);
10867 case X86::CMOV_GR8:
10868 case X86::CMOV_FR32:
10869 case X86::CMOV_FR64:
10870 case X86::CMOV_V4F32:
10871 case X86::CMOV_V2F64:
10872 case X86::CMOV_V2I64:
10873 case X86::CMOV_GR16:
10874 case X86::CMOV_GR32:
10875 case X86::CMOV_RFP32:
10876 case X86::CMOV_RFP64:
10877 case X86::CMOV_RFP80:
10878 return EmitLoweredSelect(MI, BB);
10880 case X86::FP32_TO_INT16_IN_MEM:
10881 case X86::FP32_TO_INT32_IN_MEM:
10882 case X86::FP32_TO_INT64_IN_MEM:
10883 case X86::FP64_TO_INT16_IN_MEM:
10884 case X86::FP64_TO_INT32_IN_MEM:
10885 case X86::FP64_TO_INT64_IN_MEM:
10886 case X86::FP80_TO_INT16_IN_MEM:
10887 case X86::FP80_TO_INT32_IN_MEM:
10888 case X86::FP80_TO_INT64_IN_MEM: {
10889 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10890 DebugLoc DL = MI->getDebugLoc();
10892 // Change the floating point control register to use "round towards zero"
10893 // mode when truncating to an integer value.
10894 MachineFunction *F = BB->getParent();
10895 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10896 addFrameReference(BuildMI(*BB, MI, DL,
10897 TII->get(X86::FNSTCW16m)), CWFrameIdx);
10899 // Load the old value of the high byte of the control word...
10901 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10902 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10905 // Set the high part to be round to zero...
10906 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10909 // Reload the modified control word now...
10910 addFrameReference(BuildMI(*BB, MI, DL,
10911 TII->get(X86::FLDCW16m)), CWFrameIdx);
10913 // Restore the memory image of control word to original value
10914 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10917 // Get the X86 opcode to use.
10919 switch (MI->getOpcode()) {
10920 default: llvm_unreachable("illegal opcode!");
10921 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10922 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10923 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10924 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10925 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10926 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10927 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10928 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10929 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10933 MachineOperand &Op = MI->getOperand(0);
10935 AM.BaseType = X86AddressMode::RegBase;
10936 AM.Base.Reg = Op.getReg();
10938 AM.BaseType = X86AddressMode::FrameIndexBase;
10939 AM.Base.FrameIndex = Op.getIndex();
10941 Op = MI->getOperand(1);
10943 AM.Scale = Op.getImm();
10944 Op = MI->getOperand(2);
10946 AM.IndexReg = Op.getImm();
10947 Op = MI->getOperand(3);
10948 if (Op.isGlobal()) {
10949 AM.GV = Op.getGlobal();
10951 AM.Disp = Op.getImm();
10953 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10954 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10956 // Reload the original control word now.
10957 addFrameReference(BuildMI(*BB, MI, DL,
10958 TII->get(X86::FLDCW16m)), CWFrameIdx);
10960 MI->eraseFromParent(); // The pseudo instruction is gone now.
10963 // String/text processing lowering.
10964 case X86::PCMPISTRM128REG:
10965 case X86::VPCMPISTRM128REG:
10966 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10967 case X86::PCMPISTRM128MEM:
10968 case X86::VPCMPISTRM128MEM:
10969 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10970 case X86::PCMPESTRM128REG:
10971 case X86::VPCMPESTRM128REG:
10972 return EmitPCMP(MI, BB, 5, false /* in mem */);
10973 case X86::PCMPESTRM128MEM:
10974 case X86::VPCMPESTRM128MEM:
10975 return EmitPCMP(MI, BB, 5, true /* in mem */);
10977 // Thread synchronization.
10979 return EmitMonitor(MI, BB);
10981 return EmitMwait(MI, BB);
10983 // Atomic Lowering.
10984 case X86::ATOMAND32:
10985 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10986 X86::AND32ri, X86::MOV32rm,
10988 X86::NOT32r, X86::EAX,
10989 X86::GR32RegisterClass);
10990 case X86::ATOMOR32:
10991 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10992 X86::OR32ri, X86::MOV32rm,
10994 X86::NOT32r, X86::EAX,
10995 X86::GR32RegisterClass);
10996 case X86::ATOMXOR32:
10997 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10998 X86::XOR32ri, X86::MOV32rm,
11000 X86::NOT32r, X86::EAX,
11001 X86::GR32RegisterClass);
11002 case X86::ATOMNAND32:
11003 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
11004 X86::AND32ri, X86::MOV32rm,
11006 X86::NOT32r, X86::EAX,
11007 X86::GR32RegisterClass, true);
11008 case X86::ATOMMIN32:
11009 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
11010 case X86::ATOMMAX32:
11011 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
11012 case X86::ATOMUMIN32:
11013 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
11014 case X86::ATOMUMAX32:
11015 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
11017 case X86::ATOMAND16:
11018 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
11019 X86::AND16ri, X86::MOV16rm,
11021 X86::NOT16r, X86::AX,
11022 X86::GR16RegisterClass);
11023 case X86::ATOMOR16:
11024 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
11025 X86::OR16ri, X86::MOV16rm,
11027 X86::NOT16r, X86::AX,
11028 X86::GR16RegisterClass);
11029 case X86::ATOMXOR16:
11030 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
11031 X86::XOR16ri, X86::MOV16rm,
11033 X86::NOT16r, X86::AX,
11034 X86::GR16RegisterClass);
11035 case X86::ATOMNAND16:
11036 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
11037 X86::AND16ri, X86::MOV16rm,
11039 X86::NOT16r, X86::AX,
11040 X86::GR16RegisterClass, true);
11041 case X86::ATOMMIN16:
11042 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
11043 case X86::ATOMMAX16:
11044 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
11045 case X86::ATOMUMIN16:
11046 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
11047 case X86::ATOMUMAX16:
11048 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
11050 case X86::ATOMAND8:
11051 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
11052 X86::AND8ri, X86::MOV8rm,
11054 X86::NOT8r, X86::AL,
11055 X86::GR8RegisterClass);
11057 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
11058 X86::OR8ri, X86::MOV8rm,
11060 X86::NOT8r, X86::AL,
11061 X86::GR8RegisterClass);
11062 case X86::ATOMXOR8:
11063 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
11064 X86::XOR8ri, X86::MOV8rm,
11066 X86::NOT8r, X86::AL,
11067 X86::GR8RegisterClass);
11068 case X86::ATOMNAND8:
11069 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
11070 X86::AND8ri, X86::MOV8rm,
11072 X86::NOT8r, X86::AL,
11073 X86::GR8RegisterClass, true);
11074 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
11075 // This group is for 64-bit host.
11076 case X86::ATOMAND64:
11077 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
11078 X86::AND64ri32, X86::MOV64rm,
11080 X86::NOT64r, X86::RAX,
11081 X86::GR64RegisterClass);
11082 case X86::ATOMOR64:
11083 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
11084 X86::OR64ri32, X86::MOV64rm,
11086 X86::NOT64r, X86::RAX,
11087 X86::GR64RegisterClass);
11088 case X86::ATOMXOR64:
11089 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
11090 X86::XOR64ri32, X86::MOV64rm,
11092 X86::NOT64r, X86::RAX,
11093 X86::GR64RegisterClass);
11094 case X86::ATOMNAND64:
11095 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
11096 X86::AND64ri32, X86::MOV64rm,
11098 X86::NOT64r, X86::RAX,
11099 X86::GR64RegisterClass, true);
11100 case X86::ATOMMIN64:
11101 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
11102 case X86::ATOMMAX64:
11103 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
11104 case X86::ATOMUMIN64:
11105 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
11106 case X86::ATOMUMAX64:
11107 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
11109 // This group does 64-bit operations on a 32-bit host.
11110 case X86::ATOMAND6432:
11111 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11112 X86::AND32rr, X86::AND32rr,
11113 X86::AND32ri, X86::AND32ri,
11115 case X86::ATOMOR6432:
11116 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11117 X86::OR32rr, X86::OR32rr,
11118 X86::OR32ri, X86::OR32ri,
11120 case X86::ATOMXOR6432:
11121 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11122 X86::XOR32rr, X86::XOR32rr,
11123 X86::XOR32ri, X86::XOR32ri,
11125 case X86::ATOMNAND6432:
11126 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11127 X86::AND32rr, X86::AND32rr,
11128 X86::AND32ri, X86::AND32ri,
11130 case X86::ATOMADD6432:
11131 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11132 X86::ADD32rr, X86::ADC32rr,
11133 X86::ADD32ri, X86::ADC32ri,
11135 case X86::ATOMSUB6432:
11136 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11137 X86::SUB32rr, X86::SBB32rr,
11138 X86::SUB32ri, X86::SBB32ri,
11140 case X86::ATOMSWAP6432:
11141 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11142 X86::MOV32rr, X86::MOV32rr,
11143 X86::MOV32ri, X86::MOV32ri,
11145 case X86::VASTART_SAVE_XMM_REGS:
11146 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
11148 case X86::VAARG_64:
11149 return EmitVAARG64WithCustomInserter(MI, BB);
11153 //===----------------------------------------------------------------------===//
11154 // X86 Optimization Hooks
11155 //===----------------------------------------------------------------------===//
11157 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
11161 const SelectionDAG &DAG,
11162 unsigned Depth) const {
11163 unsigned Opc = Op.getOpcode();
11164 assert((Opc >= ISD::BUILTIN_OP_END ||
11165 Opc == ISD::INTRINSIC_WO_CHAIN ||
11166 Opc == ISD::INTRINSIC_W_CHAIN ||
11167 Opc == ISD::INTRINSIC_VOID) &&
11168 "Should use MaskedValueIsZero if you don't know whether Op"
11169 " is a target node!");
11171 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
11185 // These nodes' second result is a boolean.
11186 if (Op.getResNo() == 0)
11189 case X86ISD::SETCC:
11190 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11191 Mask.getBitWidth() - 1);
11196 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11197 unsigned Depth) const {
11198 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11199 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11200 return Op.getValueType().getScalarType().getSizeInBits();
11206 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11207 /// node is a GlobalAddress + offset.
11208 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11209 const GlobalValue* &GA,
11210 int64_t &Offset) const {
11211 if (N->getOpcode() == X86ISD::Wrapper) {
11212 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11213 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11214 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11218 return TargetLowering::isGAPlusOffset(N, GA, Offset);
11221 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
11222 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
11223 /// if the load addresses are consecutive, non-overlapping, and in the right
11225 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11226 TargetLowering::DAGCombinerInfo &DCI) {
11227 DebugLoc dl = N->getDebugLoc();
11228 EVT VT = N->getValueType(0);
11230 if (VT.getSizeInBits() != 128)
11233 // Don't create instructions with illegal types after legalize types has run.
11234 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11235 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11238 SmallVector<SDValue, 16> Elts;
11239 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11240 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11242 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11245 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11246 /// generation and convert it from being a bunch of shuffles and extracts
11247 /// to a simple store and scalar loads to extract the elements.
11248 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11249 const TargetLowering &TLI) {
11250 SDValue InputVector = N->getOperand(0);
11252 // Only operate on vectors of 4 elements, where the alternative shuffling
11253 // gets to be more expensive.
11254 if (InputVector.getValueType() != MVT::v4i32)
11257 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11258 // single use which is a sign-extend or zero-extend, and all elements are
11260 SmallVector<SDNode *, 4> Uses;
11261 unsigned ExtractedElements = 0;
11262 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11263 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11264 if (UI.getUse().getResNo() != InputVector.getResNo())
11267 SDNode *Extract = *UI;
11268 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11271 if (Extract->getValueType(0) != MVT::i32)
11273 if (!Extract->hasOneUse())
11275 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11276 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11278 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11281 // Record which element was extracted.
11282 ExtractedElements |=
11283 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11285 Uses.push_back(Extract);
11288 // If not all the elements were used, this may not be worthwhile.
11289 if (ExtractedElements != 15)
11292 // Ok, we've now decided to do the transformation.
11293 DebugLoc dl = InputVector.getDebugLoc();
11295 // Store the value to a temporary stack slot.
11296 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11297 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11298 MachinePointerInfo(), false, false, 0);
11300 // Replace each use (extract) with a load of the appropriate element.
11301 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11302 UE = Uses.end(); UI != UE; ++UI) {
11303 SDNode *Extract = *UI;
11305 // cOMpute the element's address.
11306 SDValue Idx = Extract->getOperand(1);
11308 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11309 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11310 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11312 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11313 StackPtr, OffsetVal);
11315 // Load the scalar.
11316 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11317 ScalarAddr, MachinePointerInfo(),
11320 // Replace the exact with the load.
11321 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11324 // The replacement was made in place; don't return anything.
11328 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11329 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11330 const X86Subtarget *Subtarget) {
11331 DebugLoc DL = N->getDebugLoc();
11332 SDValue Cond = N->getOperand(0);
11333 // Get the LHS/RHS of the select.
11334 SDValue LHS = N->getOperand(1);
11335 SDValue RHS = N->getOperand(2);
11337 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11338 // instructions match the semantics of the common C idiom x<y?x:y but not
11339 // x<=y?x:y, because of how they handle negative zero (which can be
11340 // ignored in unsafe-math mode).
11341 if (Subtarget->hasSSE2() &&
11342 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11343 Cond.getOpcode() == ISD::SETCC) {
11344 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11346 unsigned Opcode = 0;
11347 // Check for x CC y ? x : y.
11348 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11349 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11353 // Converting this to a min would handle NaNs incorrectly, and swapping
11354 // the operands would cause it to handle comparisons between positive
11355 // and negative zero incorrectly.
11356 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11357 if (!UnsafeFPMath &&
11358 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11360 std::swap(LHS, RHS);
11362 Opcode = X86ISD::FMIN;
11365 // Converting this to a min would handle comparisons between positive
11366 // and negative zero incorrectly.
11367 if (!UnsafeFPMath &&
11368 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11370 Opcode = X86ISD::FMIN;
11373 // Converting this to a min would handle both negative zeros and NaNs
11374 // incorrectly, but we can swap the operands to fix both.
11375 std::swap(LHS, RHS);
11379 Opcode = X86ISD::FMIN;
11383 // Converting this to a max would handle comparisons between positive
11384 // and negative zero incorrectly.
11385 if (!UnsafeFPMath &&
11386 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11388 Opcode = X86ISD::FMAX;
11391 // Converting this to a max would handle NaNs incorrectly, and swapping
11392 // the operands would cause it to handle comparisons between positive
11393 // and negative zero incorrectly.
11394 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11395 if (!UnsafeFPMath &&
11396 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11398 std::swap(LHS, RHS);
11400 Opcode = X86ISD::FMAX;
11403 // Converting this to a max would handle both negative zeros and NaNs
11404 // incorrectly, but we can swap the operands to fix both.
11405 std::swap(LHS, RHS);
11409 Opcode = X86ISD::FMAX;
11412 // Check for x CC y ? y : x -- a min/max with reversed arms.
11413 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11414 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11418 // Converting this to a min would handle comparisons between positive
11419 // and negative zero incorrectly, and swapping the operands would
11420 // cause it to handle NaNs incorrectly.
11421 if (!UnsafeFPMath &&
11422 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11423 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11425 std::swap(LHS, RHS);
11427 Opcode = X86ISD::FMIN;
11430 // Converting this to a min would handle NaNs incorrectly.
11431 if (!UnsafeFPMath &&
11432 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11434 Opcode = X86ISD::FMIN;
11437 // Converting this to a min would handle both negative zeros and NaNs
11438 // incorrectly, but we can swap the operands to fix both.
11439 std::swap(LHS, RHS);
11443 Opcode = X86ISD::FMIN;
11447 // Converting this to a max would handle NaNs incorrectly.
11448 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11450 Opcode = X86ISD::FMAX;
11453 // Converting this to a max would handle comparisons between positive
11454 // and negative zero incorrectly, and swapping the operands would
11455 // cause it to handle NaNs incorrectly.
11456 if (!UnsafeFPMath &&
11457 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11458 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11460 std::swap(LHS, RHS);
11462 Opcode = X86ISD::FMAX;
11465 // Converting this to a max would handle both negative zeros and NaNs
11466 // incorrectly, but we can swap the operands to fix both.
11467 std::swap(LHS, RHS);
11471 Opcode = X86ISD::FMAX;
11477 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11480 // If this is a select between two integer constants, try to do some
11482 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11483 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11484 // Don't do this for crazy integer types.
11485 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11486 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11487 // so that TrueC (the true value) is larger than FalseC.
11488 bool NeedsCondInvert = false;
11490 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11491 // Efficiently invertible.
11492 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
11493 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
11494 isa<ConstantSDNode>(Cond.getOperand(1))))) {
11495 NeedsCondInvert = true;
11496 std::swap(TrueC, FalseC);
11499 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
11500 if (FalseC->getAPIntValue() == 0 &&
11501 TrueC->getAPIntValue().isPowerOf2()) {
11502 if (NeedsCondInvert) // Invert the condition if needed.
11503 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11504 DAG.getConstant(1, Cond.getValueType()));
11506 // Zero extend the condition if needed.
11507 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11509 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11510 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11511 DAG.getConstant(ShAmt, MVT::i8));
11514 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11515 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11516 if (NeedsCondInvert) // Invert the condition if needed.
11517 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11518 DAG.getConstant(1, Cond.getValueType()));
11520 // Zero extend the condition if needed.
11521 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11522 FalseC->getValueType(0), Cond);
11523 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11524 SDValue(FalseC, 0));
11527 // Optimize cases that will turn into an LEA instruction. This requires
11528 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11529 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11530 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11531 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11533 bool isFastMultiplier = false;
11535 switch ((unsigned char)Diff) {
11537 case 1: // result = add base, cond
11538 case 2: // result = lea base( , cond*2)
11539 case 3: // result = lea base(cond, cond*2)
11540 case 4: // result = lea base( , cond*4)
11541 case 5: // result = lea base(cond, cond*4)
11542 case 8: // result = lea base( , cond*8)
11543 case 9: // result = lea base(cond, cond*8)
11544 isFastMultiplier = true;
11549 if (isFastMultiplier) {
11550 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11551 if (NeedsCondInvert) // Invert the condition if needed.
11552 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11553 DAG.getConstant(1, Cond.getValueType()));
11555 // Zero extend the condition if needed.
11556 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11558 // Scale the condition by the difference.
11560 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11561 DAG.getConstant(Diff, Cond.getValueType()));
11563 // Add the base if non-zero.
11564 if (FalseC->getAPIntValue() != 0)
11565 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11566 SDValue(FalseC, 0));
11576 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11577 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11578 TargetLowering::DAGCombinerInfo &DCI) {
11579 DebugLoc DL = N->getDebugLoc();
11581 // If the flag operand isn't dead, don't touch this CMOV.
11582 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11585 SDValue FalseOp = N->getOperand(0);
11586 SDValue TrueOp = N->getOperand(1);
11587 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11588 SDValue Cond = N->getOperand(3);
11589 if (CC == X86::COND_E || CC == X86::COND_NE) {
11590 switch (Cond.getOpcode()) {
11594 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11595 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11596 return (CC == X86::COND_E) ? FalseOp : TrueOp;
11600 // If this is a select between two integer constants, try to do some
11601 // optimizations. Note that the operands are ordered the opposite of SELECT
11603 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11604 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11605 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11606 // larger than FalseC (the false value).
11607 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11608 CC = X86::GetOppositeBranchCondition(CC);
11609 std::swap(TrueC, FalseC);
11612 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
11613 // This is efficient for any integer data type (including i8/i16) and
11615 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11616 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11617 DAG.getConstant(CC, MVT::i8), Cond);
11619 // Zero extend the condition if needed.
11620 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11622 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11623 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11624 DAG.getConstant(ShAmt, MVT::i8));
11625 if (N->getNumValues() == 2) // Dead flag value?
11626 return DCI.CombineTo(N, Cond, SDValue());
11630 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
11631 // for any integer data type, including i8/i16.
11632 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11633 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11634 DAG.getConstant(CC, MVT::i8), Cond);
11636 // Zero extend the condition if needed.
11637 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11638 FalseC->getValueType(0), Cond);
11639 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11640 SDValue(FalseC, 0));
11642 if (N->getNumValues() == 2) // Dead flag value?
11643 return DCI.CombineTo(N, Cond, SDValue());
11647 // Optimize cases that will turn into an LEA instruction. This requires
11648 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11649 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11650 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11651 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11653 bool isFastMultiplier = false;
11655 switch ((unsigned char)Diff) {
11657 case 1: // result = add base, cond
11658 case 2: // result = lea base( , cond*2)
11659 case 3: // result = lea base(cond, cond*2)
11660 case 4: // result = lea base( , cond*4)
11661 case 5: // result = lea base(cond, cond*4)
11662 case 8: // result = lea base( , cond*8)
11663 case 9: // result = lea base(cond, cond*8)
11664 isFastMultiplier = true;
11669 if (isFastMultiplier) {
11670 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11671 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11672 DAG.getConstant(CC, MVT::i8), Cond);
11673 // Zero extend the condition if needed.
11674 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11676 // Scale the condition by the difference.
11678 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11679 DAG.getConstant(Diff, Cond.getValueType()));
11681 // Add the base if non-zero.
11682 if (FalseC->getAPIntValue() != 0)
11683 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11684 SDValue(FalseC, 0));
11685 if (N->getNumValues() == 2) // Dead flag value?
11686 return DCI.CombineTo(N, Cond, SDValue());
11696 /// PerformMulCombine - Optimize a single multiply with constant into two
11697 /// in order to implement it with two cheaper instructions, e.g.
11698 /// LEA + SHL, LEA + LEA.
11699 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11700 TargetLowering::DAGCombinerInfo &DCI) {
11701 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11704 EVT VT = N->getValueType(0);
11705 if (VT != MVT::i64)
11708 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11711 uint64_t MulAmt = C->getZExtValue();
11712 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11715 uint64_t MulAmt1 = 0;
11716 uint64_t MulAmt2 = 0;
11717 if ((MulAmt % 9) == 0) {
11719 MulAmt2 = MulAmt / 9;
11720 } else if ((MulAmt % 5) == 0) {
11722 MulAmt2 = MulAmt / 5;
11723 } else if ((MulAmt % 3) == 0) {
11725 MulAmt2 = MulAmt / 3;
11728 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11729 DebugLoc DL = N->getDebugLoc();
11731 if (isPowerOf2_64(MulAmt2) &&
11732 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11733 // If second multiplifer is pow2, issue it first. We want the multiply by
11734 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11736 std::swap(MulAmt1, MulAmt2);
11739 if (isPowerOf2_64(MulAmt1))
11740 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11741 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11743 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11744 DAG.getConstant(MulAmt1, VT));
11746 if (isPowerOf2_64(MulAmt2))
11747 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11748 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11750 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11751 DAG.getConstant(MulAmt2, VT));
11753 // Do not add new nodes to DAG combiner worklist.
11754 DCI.CombineTo(N, NewMul, false);
11759 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11760 SDValue N0 = N->getOperand(0);
11761 SDValue N1 = N->getOperand(1);
11762 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11763 EVT VT = N0.getValueType();
11765 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11766 // since the result of setcc_c is all zero's or all ones.
11767 if (N1C && N0.getOpcode() == ISD::AND &&
11768 N0.getOperand(1).getOpcode() == ISD::Constant) {
11769 SDValue N00 = N0.getOperand(0);
11770 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11771 ((N00.getOpcode() == ISD::ANY_EXTEND ||
11772 N00.getOpcode() == ISD::ZERO_EXTEND) &&
11773 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11774 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11775 APInt ShAmt = N1C->getAPIntValue();
11776 Mask = Mask.shl(ShAmt);
11778 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11779 N00, DAG.getConstant(Mask, VT));
11786 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11788 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11789 const X86Subtarget *Subtarget) {
11790 EVT VT = N->getValueType(0);
11791 if (!VT.isVector() && VT.isInteger() &&
11792 N->getOpcode() == ISD::SHL)
11793 return PerformSHLCombine(N, DAG);
11795 // On X86 with SSE2 support, we can transform this to a vector shift if
11796 // all elements are shifted by the same amount. We can't do this in legalize
11797 // because the a constant vector is typically transformed to a constant pool
11798 // so we have no knowledge of the shift amount.
11799 if (!Subtarget->hasSSE2())
11802 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11805 SDValue ShAmtOp = N->getOperand(1);
11806 EVT EltVT = VT.getVectorElementType();
11807 DebugLoc DL = N->getDebugLoc();
11808 SDValue BaseShAmt = SDValue();
11809 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11810 unsigned NumElts = VT.getVectorNumElements();
11812 for (; i != NumElts; ++i) {
11813 SDValue Arg = ShAmtOp.getOperand(i);
11814 if (Arg.getOpcode() == ISD::UNDEF) continue;
11818 for (; i != NumElts; ++i) {
11819 SDValue Arg = ShAmtOp.getOperand(i);
11820 if (Arg.getOpcode() == ISD::UNDEF) continue;
11821 if (Arg != BaseShAmt) {
11825 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11826 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11827 SDValue InVec = ShAmtOp.getOperand(0);
11828 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11829 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11831 for (; i != NumElts; ++i) {
11832 SDValue Arg = InVec.getOperand(i);
11833 if (Arg.getOpcode() == ISD::UNDEF) continue;
11837 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11838 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11839 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11840 if (C->getZExtValue() == SplatIdx)
11841 BaseShAmt = InVec.getOperand(1);
11844 if (BaseShAmt.getNode() == 0)
11845 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11846 DAG.getIntPtrConstant(0));
11850 // The shift amount is an i32.
11851 if (EltVT.bitsGT(MVT::i32))
11852 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11853 else if (EltVT.bitsLT(MVT::i32))
11854 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11856 // The shift amount is identical so we can do a vector shift.
11857 SDValue ValOp = N->getOperand(0);
11858 switch (N->getOpcode()) {
11860 llvm_unreachable("Unknown shift opcode!");
11863 if (VT == MVT::v2i64)
11864 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11865 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11867 if (VT == MVT::v4i32)
11868 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11869 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11871 if (VT == MVT::v8i16)
11872 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11873 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11877 if (VT == MVT::v4i32)
11878 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11879 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11881 if (VT == MVT::v8i16)
11882 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11883 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11887 if (VT == MVT::v2i64)
11888 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11889 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11891 if (VT == MVT::v4i32)
11892 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11893 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11895 if (VT == MVT::v8i16)
11896 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11897 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11905 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
11906 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
11907 // and friends. Likewise for OR -> CMPNEQSS.
11908 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
11909 TargetLowering::DAGCombinerInfo &DCI,
11910 const X86Subtarget *Subtarget) {
11913 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
11914 // we're requiring SSE2 for both.
11915 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
11916 SDValue N0 = N->getOperand(0);
11917 SDValue N1 = N->getOperand(1);
11918 SDValue CMP0 = N0->getOperand(1);
11919 SDValue CMP1 = N1->getOperand(1);
11920 DebugLoc DL = N->getDebugLoc();
11922 // The SETCCs should both refer to the same CMP.
11923 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
11926 SDValue CMP00 = CMP0->getOperand(0);
11927 SDValue CMP01 = CMP0->getOperand(1);
11928 EVT VT = CMP00.getValueType();
11930 if (VT == MVT::f32 || VT == MVT::f64) {
11931 bool ExpectingFlags = false;
11932 // Check for any users that want flags:
11933 for (SDNode::use_iterator UI = N->use_begin(),
11935 !ExpectingFlags && UI != UE; ++UI)
11936 switch (UI->getOpcode()) {
11941 ExpectingFlags = true;
11943 case ISD::CopyToReg:
11944 case ISD::SIGN_EXTEND:
11945 case ISD::ZERO_EXTEND:
11946 case ISD::ANY_EXTEND:
11950 if (!ExpectingFlags) {
11951 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
11952 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
11954 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
11955 X86::CondCode tmp = cc0;
11960 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
11961 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
11962 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
11963 X86ISD::NodeType NTOperator = is64BitFP ?
11964 X86ISD::FSETCCsd : X86ISD::FSETCCss;
11965 // FIXME: need symbolic constants for these magic numbers.
11966 // See X86ATTInstPrinter.cpp:printSSECC().
11967 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
11968 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
11969 DAG.getConstant(x86cc, MVT::i8));
11970 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
11972 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
11973 DAG.getConstant(1, MVT::i32));
11974 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
11975 return OneBitOfTruth;
11983 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11984 TargetLowering::DAGCombinerInfo &DCI,
11985 const X86Subtarget *Subtarget) {
11986 if (DCI.isBeforeLegalizeOps())
11989 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11993 // Want to form ANDNP nodes:
11994 // 1) In the hopes of then easily combining them with OR and AND nodes
11995 // to form PBLEND/PSIGN.
11996 // 2) To match ANDN packed intrinsics
11997 EVT VT = N->getValueType(0);
11998 if (VT != MVT::v2i64 && VT != MVT::v4i64)
12001 SDValue N0 = N->getOperand(0);
12002 SDValue N1 = N->getOperand(1);
12003 DebugLoc DL = N->getDebugLoc();
12005 // Check LHS for vnot
12006 if (N0.getOpcode() == ISD::XOR &&
12007 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
12008 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
12010 // Check RHS for vnot
12011 if (N1.getOpcode() == ISD::XOR &&
12012 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
12013 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
12018 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
12019 TargetLowering::DAGCombinerInfo &DCI,
12020 const X86Subtarget *Subtarget) {
12021 if (DCI.isBeforeLegalizeOps())
12024 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
12028 EVT VT = N->getValueType(0);
12029 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
12032 SDValue N0 = N->getOperand(0);
12033 SDValue N1 = N->getOperand(1);
12035 // look for psign/blend
12036 if (Subtarget->hasSSSE3()) {
12037 if (VT == MVT::v2i64) {
12038 // Canonicalize pandn to RHS
12039 if (N0.getOpcode() == X86ISD::ANDNP)
12041 // or (and (m, x), (pandn m, y))
12042 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
12043 SDValue Mask = N1.getOperand(0);
12044 SDValue X = N1.getOperand(1);
12046 if (N0.getOperand(0) == Mask)
12047 Y = N0.getOperand(1);
12048 if (N0.getOperand(1) == Mask)
12049 Y = N0.getOperand(0);
12051 // Check to see if the mask appeared in both the AND and ANDNP and
12055 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
12056 if (Mask.getOpcode() != ISD::BITCAST ||
12057 X.getOpcode() != ISD::BITCAST ||
12058 Y.getOpcode() != ISD::BITCAST)
12061 // Look through mask bitcast.
12062 Mask = Mask.getOperand(0);
12063 EVT MaskVT = Mask.getValueType();
12065 // Validate that the Mask operand is a vector sra node. The sra node
12066 // will be an intrinsic.
12067 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
12070 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
12071 // there is no psrai.b
12072 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
12073 case Intrinsic::x86_sse2_psrai_w:
12074 case Intrinsic::x86_sse2_psrai_d:
12076 default: return SDValue();
12079 // Check that the SRA is all signbits.
12080 SDValue SraC = Mask.getOperand(2);
12081 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
12082 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
12083 if ((SraAmt + 1) != EltBits)
12086 DebugLoc DL = N->getDebugLoc();
12088 // Now we know we at least have a plendvb with the mask val. See if
12089 // we can form a psignb/w/d.
12090 // psign = x.type == y.type == mask.type && y = sub(0, x);
12091 X = X.getOperand(0);
12092 Y = Y.getOperand(0);
12093 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
12094 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
12095 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
12098 case 8: Opc = X86ISD::PSIGNB; break;
12099 case 16: Opc = X86ISD::PSIGNW; break;
12100 case 32: Opc = X86ISD::PSIGND; break;
12104 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
12105 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
12108 // PBLENDVB only available on SSE 4.1
12109 if (!Subtarget->hasSSE41())
12112 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
12113 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
12114 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
12115 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
12116 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
12121 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
12122 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
12124 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
12126 if (!N0.hasOneUse() || !N1.hasOneUse())
12129 SDValue ShAmt0 = N0.getOperand(1);
12130 if (ShAmt0.getValueType() != MVT::i8)
12132 SDValue ShAmt1 = N1.getOperand(1);
12133 if (ShAmt1.getValueType() != MVT::i8)
12135 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
12136 ShAmt0 = ShAmt0.getOperand(0);
12137 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
12138 ShAmt1 = ShAmt1.getOperand(0);
12140 DebugLoc DL = N->getDebugLoc();
12141 unsigned Opc = X86ISD::SHLD;
12142 SDValue Op0 = N0.getOperand(0);
12143 SDValue Op1 = N1.getOperand(0);
12144 if (ShAmt0.getOpcode() == ISD::SUB) {
12145 Opc = X86ISD::SHRD;
12146 std::swap(Op0, Op1);
12147 std::swap(ShAmt0, ShAmt1);
12150 unsigned Bits = VT.getSizeInBits();
12151 if (ShAmt1.getOpcode() == ISD::SUB) {
12152 SDValue Sum = ShAmt1.getOperand(0);
12153 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
12154 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
12155 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
12156 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
12157 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
12158 return DAG.getNode(Opc, DL, VT,
12160 DAG.getNode(ISD::TRUNCATE, DL,
12163 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
12164 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
12166 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
12167 return DAG.getNode(Opc, DL, VT,
12168 N0.getOperand(0), N1.getOperand(0),
12169 DAG.getNode(ISD::TRUNCATE, DL,
12176 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
12177 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
12178 const X86Subtarget *Subtarget) {
12179 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
12180 // the FP state in cases where an emms may be missing.
12181 // A preferable solution to the general problem is to figure out the right
12182 // places to insert EMMS. This qualifies as a quick hack.
12184 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
12185 StoreSDNode *St = cast<StoreSDNode>(N);
12186 EVT VT = St->getValue().getValueType();
12187 if (VT.getSizeInBits() != 64)
12190 const Function *F = DAG.getMachineFunction().getFunction();
12191 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
12192 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
12193 && Subtarget->hasSSE2();
12194 if ((VT.isVector() ||
12195 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
12196 isa<LoadSDNode>(St->getValue()) &&
12197 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
12198 St->getChain().hasOneUse() && !St->isVolatile()) {
12199 SDNode* LdVal = St->getValue().getNode();
12200 LoadSDNode *Ld = 0;
12201 int TokenFactorIndex = -1;
12202 SmallVector<SDValue, 8> Ops;
12203 SDNode* ChainVal = St->getChain().getNode();
12204 // Must be a store of a load. We currently handle two cases: the load
12205 // is a direct child, and it's under an intervening TokenFactor. It is
12206 // possible to dig deeper under nested TokenFactors.
12207 if (ChainVal == LdVal)
12208 Ld = cast<LoadSDNode>(St->getChain());
12209 else if (St->getValue().hasOneUse() &&
12210 ChainVal->getOpcode() == ISD::TokenFactor) {
12211 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
12212 if (ChainVal->getOperand(i).getNode() == LdVal) {
12213 TokenFactorIndex = i;
12214 Ld = cast<LoadSDNode>(St->getValue());
12216 Ops.push_back(ChainVal->getOperand(i));
12220 if (!Ld || !ISD::isNormalLoad(Ld))
12223 // If this is not the MMX case, i.e. we are just turning i64 load/store
12224 // into f64 load/store, avoid the transformation if there are multiple
12225 // uses of the loaded value.
12226 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
12229 DebugLoc LdDL = Ld->getDebugLoc();
12230 DebugLoc StDL = N->getDebugLoc();
12231 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
12232 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
12234 if (Subtarget->is64Bit() || F64IsLegal) {
12235 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
12236 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
12237 Ld->getPointerInfo(), Ld->isVolatile(),
12238 Ld->isNonTemporal(), Ld->getAlignment());
12239 SDValue NewChain = NewLd.getValue(1);
12240 if (TokenFactorIndex != -1) {
12241 Ops.push_back(NewChain);
12242 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12245 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
12246 St->getPointerInfo(),
12247 St->isVolatile(), St->isNonTemporal(),
12248 St->getAlignment());
12251 // Otherwise, lower to two pairs of 32-bit loads / stores.
12252 SDValue LoAddr = Ld->getBasePtr();
12253 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
12254 DAG.getConstant(4, MVT::i32));
12256 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
12257 Ld->getPointerInfo(),
12258 Ld->isVolatile(), Ld->isNonTemporal(),
12259 Ld->getAlignment());
12260 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
12261 Ld->getPointerInfo().getWithOffset(4),
12262 Ld->isVolatile(), Ld->isNonTemporal(),
12263 MinAlign(Ld->getAlignment(), 4));
12265 SDValue NewChain = LoLd.getValue(1);
12266 if (TokenFactorIndex != -1) {
12267 Ops.push_back(LoLd);
12268 Ops.push_back(HiLd);
12269 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12273 LoAddr = St->getBasePtr();
12274 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
12275 DAG.getConstant(4, MVT::i32));
12277 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
12278 St->getPointerInfo(),
12279 St->isVolatile(), St->isNonTemporal(),
12280 St->getAlignment());
12281 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12282 St->getPointerInfo().getWithOffset(4),
12284 St->isNonTemporal(),
12285 MinAlign(St->getAlignment(), 4));
12286 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12291 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12292 /// X86ISD::FXOR nodes.
12293 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12294 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12295 // F[X]OR(0.0, x) -> x
12296 // F[X]OR(x, 0.0) -> x
12297 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12298 if (C->getValueAPF().isPosZero())
12299 return N->getOperand(1);
12300 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12301 if (C->getValueAPF().isPosZero())
12302 return N->getOperand(0);
12306 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12307 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12308 // FAND(0.0, x) -> 0.0
12309 // FAND(x, 0.0) -> 0.0
12310 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12311 if (C->getValueAPF().isPosZero())
12312 return N->getOperand(0);
12313 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12314 if (C->getValueAPF().isPosZero())
12315 return N->getOperand(1);
12319 static SDValue PerformBTCombine(SDNode *N,
12321 TargetLowering::DAGCombinerInfo &DCI) {
12322 // BT ignores high bits in the bit index operand.
12323 SDValue Op1 = N->getOperand(1);
12324 if (Op1.hasOneUse()) {
12325 unsigned BitWidth = Op1.getValueSizeInBits();
12326 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12327 APInt KnownZero, KnownOne;
12328 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12329 !DCI.isBeforeLegalizeOps());
12330 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12331 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12332 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12333 DCI.CommitTargetLoweringOpt(TLO);
12338 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12339 SDValue Op = N->getOperand(0);
12340 if (Op.getOpcode() == ISD::BITCAST)
12341 Op = Op.getOperand(0);
12342 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12343 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12344 VT.getVectorElementType().getSizeInBits() ==
12345 OpVT.getVectorElementType().getSizeInBits()) {
12346 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12351 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12352 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
12353 // (and (i32 x86isd::setcc_carry), 1)
12354 // This eliminates the zext. This transformation is necessary because
12355 // ISD::SETCC is always legalized to i8.
12356 DebugLoc dl = N->getDebugLoc();
12357 SDValue N0 = N->getOperand(0);
12358 EVT VT = N->getValueType(0);
12359 if (N0.getOpcode() == ISD::AND &&
12361 N0.getOperand(0).hasOneUse()) {
12362 SDValue N00 = N0.getOperand(0);
12363 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12365 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12366 if (!C || C->getZExtValue() != 1)
12368 return DAG.getNode(ISD::AND, dl, VT,
12369 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12370 N00.getOperand(0), N00.getOperand(1)),
12371 DAG.getConstant(1, VT));
12377 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12378 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12379 unsigned X86CC = N->getConstantOperandVal(0);
12380 SDValue EFLAG = N->getOperand(1);
12381 DebugLoc DL = N->getDebugLoc();
12383 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12384 // a zext and produces an all-ones bit which is more useful than 0/1 in some
12386 if (X86CC == X86::COND_B)
12387 return DAG.getNode(ISD::AND, DL, MVT::i8,
12388 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12389 DAG.getConstant(X86CC, MVT::i8), EFLAG),
12390 DAG.getConstant(1, MVT::i8));
12395 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
12396 const X86TargetLowering *XTLI) {
12397 SDValue Op0 = N->getOperand(0);
12398 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
12399 // a 32-bit target where SSE doesn't support i64->FP operations.
12400 if (Op0.getOpcode() == ISD::LOAD) {
12401 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
12402 EVT VT = Ld->getValueType(0);
12403 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
12404 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
12405 !XTLI->getSubtarget()->is64Bit() &&
12406 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12407 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
12408 Ld->getChain(), Op0, DAG);
12409 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
12416 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12417 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12418 X86TargetLowering::DAGCombinerInfo &DCI) {
12419 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12420 // the result is either zero or one (depending on the input carry bit).
12421 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12422 if (X86::isZeroNode(N->getOperand(0)) &&
12423 X86::isZeroNode(N->getOperand(1)) &&
12424 // We don't have a good way to replace an EFLAGS use, so only do this when
12426 SDValue(N, 1).use_empty()) {
12427 DebugLoc DL = N->getDebugLoc();
12428 EVT VT = N->getValueType(0);
12429 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12430 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12431 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12432 DAG.getConstant(X86::COND_B,MVT::i8),
12434 DAG.getConstant(1, VT));
12435 return DCI.CombineTo(N, Res1, CarryOut);
12441 // fold (add Y, (sete X, 0)) -> adc 0, Y
12442 // (add Y, (setne X, 0)) -> sbb -1, Y
12443 // (sub (sete X, 0), Y) -> sbb 0, Y
12444 // (sub (setne X, 0), Y) -> adc -1, Y
12445 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12446 DebugLoc DL = N->getDebugLoc();
12448 // Look through ZExts.
12449 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12450 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12453 SDValue SetCC = Ext.getOperand(0);
12454 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12457 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12458 if (CC != X86::COND_E && CC != X86::COND_NE)
12461 SDValue Cmp = SetCC.getOperand(1);
12462 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12463 !X86::isZeroNode(Cmp.getOperand(1)) ||
12464 !Cmp.getOperand(0).getValueType().isInteger())
12467 SDValue CmpOp0 = Cmp.getOperand(0);
12468 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12469 DAG.getConstant(1, CmpOp0.getValueType()));
12471 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12472 if (CC == X86::COND_NE)
12473 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12474 DL, OtherVal.getValueType(), OtherVal,
12475 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12476 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12477 DL, OtherVal.getValueType(), OtherVal,
12478 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12481 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12482 DAGCombinerInfo &DCI) const {
12483 SelectionDAG &DAG = DCI.DAG;
12484 switch (N->getOpcode()) {
12486 case ISD::EXTRACT_VECTOR_ELT:
12487 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12488 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
12489 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
12491 case ISD::SUB: return OptimizeConditonalInDecrement(N, DAG);
12492 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
12493 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
12496 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
12497 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
12498 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
12499 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
12500 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
12502 case X86ISD::FOR: return PerformFORCombine(N, DAG);
12503 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
12504 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
12505 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
12506 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
12507 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
12508 case X86ISD::SHUFPS: // Handle all target specific shuffles
12509 case X86ISD::SHUFPD:
12510 case X86ISD::PALIGN:
12511 case X86ISD::PUNPCKHBW:
12512 case X86ISD::PUNPCKHWD:
12513 case X86ISD::PUNPCKHDQ:
12514 case X86ISD::PUNPCKHQDQ:
12515 case X86ISD::UNPCKHPS:
12516 case X86ISD::UNPCKHPD:
12517 case X86ISD::PUNPCKLBW:
12518 case X86ISD::PUNPCKLWD:
12519 case X86ISD::PUNPCKLDQ:
12520 case X86ISD::PUNPCKLQDQ:
12521 case X86ISD::UNPCKLPS:
12522 case X86ISD::UNPCKLPD:
12523 case X86ISD::VUNPCKLPS:
12524 case X86ISD::VUNPCKLPD:
12525 case X86ISD::VUNPCKLPSY:
12526 case X86ISD::VUNPCKLPDY:
12527 case X86ISD::MOVHLPS:
12528 case X86ISD::MOVLHPS:
12529 case X86ISD::PSHUFD:
12530 case X86ISD::PSHUFHW:
12531 case X86ISD::PSHUFLW:
12532 case X86ISD::MOVSS:
12533 case X86ISD::MOVSD:
12534 case X86ISD::VPERMIL:
12535 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12541 /// isTypeDesirableForOp - Return true if the target has native support for
12542 /// the specified value type and it is 'desirable' to use the type for the
12543 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12544 /// instruction encodings are longer and some i16 instructions are slow.
12545 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12546 if (!isTypeLegal(VT))
12548 if (VT != MVT::i16)
12555 case ISD::SIGN_EXTEND:
12556 case ISD::ZERO_EXTEND:
12557 case ISD::ANY_EXTEND:
12570 /// IsDesirableToPromoteOp - This method query the target whether it is
12571 /// beneficial for dag combiner to promote the specified node. If true, it
12572 /// should return the desired promotion type by reference.
12573 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12574 EVT VT = Op.getValueType();
12575 if (VT != MVT::i16)
12578 bool Promote = false;
12579 bool Commute = false;
12580 switch (Op.getOpcode()) {
12583 LoadSDNode *LD = cast<LoadSDNode>(Op);
12584 // If the non-extending load has a single use and it's not live out, then it
12585 // might be folded.
12586 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12587 Op.hasOneUse()*/) {
12588 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12589 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12590 // The only case where we'd want to promote LOAD (rather then it being
12591 // promoted as an operand is when it's only use is liveout.
12592 if (UI->getOpcode() != ISD::CopyToReg)
12599 case ISD::SIGN_EXTEND:
12600 case ISD::ZERO_EXTEND:
12601 case ISD::ANY_EXTEND:
12606 SDValue N0 = Op.getOperand(0);
12607 // Look out for (store (shl (load), x)).
12608 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12621 SDValue N0 = Op.getOperand(0);
12622 SDValue N1 = Op.getOperand(1);
12623 if (!Commute && MayFoldLoad(N1))
12625 // Avoid disabling potential load folding opportunities.
12626 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12628 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12638 //===----------------------------------------------------------------------===//
12639 // X86 Inline Assembly Support
12640 //===----------------------------------------------------------------------===//
12642 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12643 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12645 std::string AsmStr = IA->getAsmString();
12647 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12648 SmallVector<StringRef, 4> AsmPieces;
12649 SplitString(AsmStr, AsmPieces, ";\n");
12651 switch (AsmPieces.size()) {
12652 default: return false;
12654 AsmStr = AsmPieces[0];
12656 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
12658 // FIXME: this should verify that we are targeting a 486 or better. If not,
12659 // we will turn this bswap into something that will be lowered to logical ops
12660 // instead of emitting the bswap asm. For now, we don't support 486 or lower
12661 // so don't worry about this.
12663 if (AsmPieces.size() == 2 &&
12664 (AsmPieces[0] == "bswap" ||
12665 AsmPieces[0] == "bswapq" ||
12666 AsmPieces[0] == "bswapl") &&
12667 (AsmPieces[1] == "$0" ||
12668 AsmPieces[1] == "${0:q}")) {
12669 // No need to check constraints, nothing other than the equivalent of
12670 // "=r,0" would be valid here.
12671 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12672 if (!Ty || Ty->getBitWidth() % 16 != 0)
12674 return IntrinsicLowering::LowerToByteSwap(CI);
12676 // rorw $$8, ${0:w} --> llvm.bswap.i16
12677 if (CI->getType()->isIntegerTy(16) &&
12678 AsmPieces.size() == 3 &&
12679 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12680 AsmPieces[1] == "$$8," &&
12681 AsmPieces[2] == "${0:w}" &&
12682 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12684 const std::string &ConstraintsStr = IA->getConstraintString();
12685 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12686 std::sort(AsmPieces.begin(), AsmPieces.end());
12687 if (AsmPieces.size() == 4 &&
12688 AsmPieces[0] == "~{cc}" &&
12689 AsmPieces[1] == "~{dirflag}" &&
12690 AsmPieces[2] == "~{flags}" &&
12691 AsmPieces[3] == "~{fpsr}") {
12692 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12693 if (!Ty || Ty->getBitWidth() % 16 != 0)
12695 return IntrinsicLowering::LowerToByteSwap(CI);
12700 if (CI->getType()->isIntegerTy(32) &&
12701 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12702 SmallVector<StringRef, 4> Words;
12703 SplitString(AsmPieces[0], Words, " \t,");
12704 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12705 Words[2] == "${0:w}") {
12707 SplitString(AsmPieces[1], Words, " \t,");
12708 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12709 Words[2] == "$0") {
12711 SplitString(AsmPieces[2], Words, " \t,");
12712 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12713 Words[2] == "${0:w}") {
12715 const std::string &ConstraintsStr = IA->getConstraintString();
12716 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12717 std::sort(AsmPieces.begin(), AsmPieces.end());
12718 if (AsmPieces.size() == 4 &&
12719 AsmPieces[0] == "~{cc}" &&
12720 AsmPieces[1] == "~{dirflag}" &&
12721 AsmPieces[2] == "~{flags}" &&
12722 AsmPieces[3] == "~{fpsr}") {
12723 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12724 if (!Ty || Ty->getBitWidth() % 16 != 0)
12726 return IntrinsicLowering::LowerToByteSwap(CI);
12733 if (CI->getType()->isIntegerTy(64)) {
12734 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12735 if (Constraints.size() >= 2 &&
12736 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12737 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12738 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
12739 SmallVector<StringRef, 4> Words;
12740 SplitString(AsmPieces[0], Words, " \t");
12741 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12743 SplitString(AsmPieces[1], Words, " \t");
12744 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12746 SplitString(AsmPieces[2], Words, " \t,");
12747 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12748 Words[2] == "%edx") {
12749 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12750 if (!Ty || Ty->getBitWidth() % 16 != 0)
12752 return IntrinsicLowering::LowerToByteSwap(CI);
12765 /// getConstraintType - Given a constraint letter, return the type of
12766 /// constraint it is for this target.
12767 X86TargetLowering::ConstraintType
12768 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12769 if (Constraint.size() == 1) {
12770 switch (Constraint[0]) {
12781 return C_RegisterClass;
12805 return TargetLowering::getConstraintType(Constraint);
12808 /// Examine constraint type and operand type and determine a weight value.
12809 /// This object must already have been set up with the operand type
12810 /// and the current alternative constraint selected.
12811 TargetLowering::ConstraintWeight
12812 X86TargetLowering::getSingleConstraintMatchWeight(
12813 AsmOperandInfo &info, const char *constraint) const {
12814 ConstraintWeight weight = CW_Invalid;
12815 Value *CallOperandVal = info.CallOperandVal;
12816 // If we don't have a value, we can't do a match,
12817 // but allow it at the lowest weight.
12818 if (CallOperandVal == NULL)
12820 Type *type = CallOperandVal->getType();
12821 // Look at the constraint type.
12822 switch (*constraint) {
12824 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12835 if (CallOperandVal->getType()->isIntegerTy())
12836 weight = CW_SpecificReg;
12841 if (type->isFloatingPointTy())
12842 weight = CW_SpecificReg;
12845 if (type->isX86_MMXTy() && Subtarget->hasMMX())
12846 weight = CW_SpecificReg;
12850 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12851 weight = CW_Register;
12854 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12855 if (C->getZExtValue() <= 31)
12856 weight = CW_Constant;
12860 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12861 if (C->getZExtValue() <= 63)
12862 weight = CW_Constant;
12866 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12867 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12868 weight = CW_Constant;
12872 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12873 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12874 weight = CW_Constant;
12878 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12879 if (C->getZExtValue() <= 3)
12880 weight = CW_Constant;
12884 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12885 if (C->getZExtValue() <= 0xff)
12886 weight = CW_Constant;
12891 if (dyn_cast<ConstantFP>(CallOperandVal)) {
12892 weight = CW_Constant;
12896 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12897 if ((C->getSExtValue() >= -0x80000000LL) &&
12898 (C->getSExtValue() <= 0x7fffffffLL))
12899 weight = CW_Constant;
12903 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12904 if (C->getZExtValue() <= 0xffffffff)
12905 weight = CW_Constant;
12912 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12913 /// with another that has more specific requirements based on the type of the
12914 /// corresponding operand.
12915 const char *X86TargetLowering::
12916 LowerXConstraint(EVT ConstraintVT) const {
12917 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12918 // 'f' like normal targets.
12919 if (ConstraintVT.isFloatingPoint()) {
12920 if (Subtarget->hasXMMInt())
12922 if (Subtarget->hasXMM())
12926 return TargetLowering::LowerXConstraint(ConstraintVT);
12929 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12930 /// vector. If it is invalid, don't add anything to Ops.
12931 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12932 std::string &Constraint,
12933 std::vector<SDValue>&Ops,
12934 SelectionDAG &DAG) const {
12935 SDValue Result(0, 0);
12937 // Only support length 1 constraints for now.
12938 if (Constraint.length() > 1) return;
12940 char ConstraintLetter = Constraint[0];
12941 switch (ConstraintLetter) {
12944 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12945 if (C->getZExtValue() <= 31) {
12946 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12952 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12953 if (C->getZExtValue() <= 63) {
12954 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12960 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12961 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12962 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12968 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12969 if (C->getZExtValue() <= 255) {
12970 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12976 // 32-bit signed value
12977 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12978 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12979 C->getSExtValue())) {
12980 // Widen to 64 bits here to get it sign extended.
12981 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12984 // FIXME gcc accepts some relocatable values here too, but only in certain
12985 // memory models; it's complicated.
12990 // 32-bit unsigned value
12991 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12992 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12993 C->getZExtValue())) {
12994 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12998 // FIXME gcc accepts some relocatable values here too, but only in certain
12999 // memory models; it's complicated.
13003 // Literal immediates are always ok.
13004 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
13005 // Widen to 64 bits here to get it sign extended.
13006 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
13010 // In any sort of PIC mode addresses need to be computed at runtime by
13011 // adding in a register or some sort of table lookup. These can't
13012 // be used as immediates.
13013 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
13016 // If we are in non-pic codegen mode, we allow the address of a global (with
13017 // an optional displacement) to be used with 'i'.
13018 GlobalAddressSDNode *GA = 0;
13019 int64_t Offset = 0;
13021 // Match either (GA), (GA+C), (GA+C1+C2), etc.
13023 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
13024 Offset += GA->getOffset();
13026 } else if (Op.getOpcode() == ISD::ADD) {
13027 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
13028 Offset += C->getZExtValue();
13029 Op = Op.getOperand(0);
13032 } else if (Op.getOpcode() == ISD::SUB) {
13033 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
13034 Offset += -C->getZExtValue();
13035 Op = Op.getOperand(0);
13040 // Otherwise, this isn't something we can handle, reject it.
13044 const GlobalValue *GV = GA->getGlobal();
13045 // If we require an extra load to get this address, as in PIC mode, we
13046 // can't accept it.
13047 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
13048 getTargetMachine())))
13051 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
13052 GA->getValueType(0), Offset);
13057 if (Result.getNode()) {
13058 Ops.push_back(Result);
13061 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13064 std::pair<unsigned, const TargetRegisterClass*>
13065 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
13067 // First, see if this is a constraint that directly corresponds to an LLVM
13069 if (Constraint.size() == 1) {
13070 // GCC Constraint Letters
13071 switch (Constraint[0]) {
13073 // TODO: Slight differences here in allocation order and leaving
13074 // RIP in the class. Do they matter any more here than they do
13075 // in the normal allocation?
13076 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
13077 if (Subtarget->is64Bit()) {
13078 if (VT == MVT::i32 || VT == MVT::f32)
13079 return std::make_pair(0U, X86::GR32RegisterClass);
13080 else if (VT == MVT::i16)
13081 return std::make_pair(0U, X86::GR16RegisterClass);
13082 else if (VT == MVT::i8 || VT == MVT::i1)
13083 return std::make_pair(0U, X86::GR8RegisterClass);
13084 else if (VT == MVT::i64 || VT == MVT::f64)
13085 return std::make_pair(0U, X86::GR64RegisterClass);
13088 // 32-bit fallthrough
13089 case 'Q': // Q_REGS
13090 if (VT == MVT::i32 || VT == MVT::f32)
13091 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
13092 else if (VT == MVT::i16)
13093 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
13094 else if (VT == MVT::i8 || VT == MVT::i1)
13095 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
13096 else if (VT == MVT::i64)
13097 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
13099 case 'r': // GENERAL_REGS
13100 case 'l': // INDEX_REGS
13101 if (VT == MVT::i8 || VT == MVT::i1)
13102 return std::make_pair(0U, X86::GR8RegisterClass);
13103 if (VT == MVT::i16)
13104 return std::make_pair(0U, X86::GR16RegisterClass);
13105 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
13106 return std::make_pair(0U, X86::GR32RegisterClass);
13107 return std::make_pair(0U, X86::GR64RegisterClass);
13108 case 'R': // LEGACY_REGS
13109 if (VT == MVT::i8 || VT == MVT::i1)
13110 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
13111 if (VT == MVT::i16)
13112 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
13113 if (VT == MVT::i32 || !Subtarget->is64Bit())
13114 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
13115 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
13116 case 'f': // FP Stack registers.
13117 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
13118 // value to the correct fpstack register class.
13119 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
13120 return std::make_pair(0U, X86::RFP32RegisterClass);
13121 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
13122 return std::make_pair(0U, X86::RFP64RegisterClass);
13123 return std::make_pair(0U, X86::RFP80RegisterClass);
13124 case 'y': // MMX_REGS if MMX allowed.
13125 if (!Subtarget->hasMMX()) break;
13126 return std::make_pair(0U, X86::VR64RegisterClass);
13127 case 'Y': // SSE_REGS if SSE2 allowed
13128 if (!Subtarget->hasXMMInt()) break;
13130 case 'x': // SSE_REGS if SSE1 allowed
13131 if (!Subtarget->hasXMM()) break;
13133 switch (VT.getSimpleVT().SimpleTy) {
13135 // Scalar SSE types.
13138 return std::make_pair(0U, X86::FR32RegisterClass);
13141 return std::make_pair(0U, X86::FR64RegisterClass);
13149 return std::make_pair(0U, X86::VR128RegisterClass);
13155 // Use the default implementation in TargetLowering to convert the register
13156 // constraint into a member of a register class.
13157 std::pair<unsigned, const TargetRegisterClass*> Res;
13158 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
13160 // Not found as a standard register?
13161 if (Res.second == 0) {
13162 // Map st(0) -> st(7) -> ST0
13163 if (Constraint.size() == 7 && Constraint[0] == '{' &&
13164 tolower(Constraint[1]) == 's' &&
13165 tolower(Constraint[2]) == 't' &&
13166 Constraint[3] == '(' &&
13167 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
13168 Constraint[5] == ')' &&
13169 Constraint[6] == '}') {
13171 Res.first = X86::ST0+Constraint[4]-'0';
13172 Res.second = X86::RFP80RegisterClass;
13176 // GCC allows "st(0)" to be called just plain "st".
13177 if (StringRef("{st}").equals_lower(Constraint)) {
13178 Res.first = X86::ST0;
13179 Res.second = X86::RFP80RegisterClass;
13184 if (StringRef("{flags}").equals_lower(Constraint)) {
13185 Res.first = X86::EFLAGS;
13186 Res.second = X86::CCRRegisterClass;
13190 // 'A' means EAX + EDX.
13191 if (Constraint == "A") {
13192 Res.first = X86::EAX;
13193 Res.second = X86::GR32_ADRegisterClass;
13199 // Otherwise, check to see if this is a register class of the wrong value
13200 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
13201 // turn into {ax},{dx}.
13202 if (Res.second->hasType(VT))
13203 return Res; // Correct type already, nothing to do.
13205 // All of the single-register GCC register classes map their values onto
13206 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
13207 // really want an 8-bit or 32-bit register, map to the appropriate register
13208 // class and return the appropriate register.
13209 if (Res.second == X86::GR16RegisterClass) {
13210 if (VT == MVT::i8) {
13211 unsigned DestReg = 0;
13212 switch (Res.first) {
13214 case X86::AX: DestReg = X86::AL; break;
13215 case X86::DX: DestReg = X86::DL; break;
13216 case X86::CX: DestReg = X86::CL; break;
13217 case X86::BX: DestReg = X86::BL; break;
13220 Res.first = DestReg;
13221 Res.second = X86::GR8RegisterClass;
13223 } else if (VT == MVT::i32) {
13224 unsigned DestReg = 0;
13225 switch (Res.first) {
13227 case X86::AX: DestReg = X86::EAX; break;
13228 case X86::DX: DestReg = X86::EDX; break;
13229 case X86::CX: DestReg = X86::ECX; break;
13230 case X86::BX: DestReg = X86::EBX; break;
13231 case X86::SI: DestReg = X86::ESI; break;
13232 case X86::DI: DestReg = X86::EDI; break;
13233 case X86::BP: DestReg = X86::EBP; break;
13234 case X86::SP: DestReg = X86::ESP; break;
13237 Res.first = DestReg;
13238 Res.second = X86::GR32RegisterClass;
13240 } else if (VT == MVT::i64) {
13241 unsigned DestReg = 0;
13242 switch (Res.first) {
13244 case X86::AX: DestReg = X86::RAX; break;
13245 case X86::DX: DestReg = X86::RDX; break;
13246 case X86::CX: DestReg = X86::RCX; break;
13247 case X86::BX: DestReg = X86::RBX; break;
13248 case X86::SI: DestReg = X86::RSI; break;
13249 case X86::DI: DestReg = X86::RDI; break;
13250 case X86::BP: DestReg = X86::RBP; break;
13251 case X86::SP: DestReg = X86::RSP; break;
13254 Res.first = DestReg;
13255 Res.second = X86::GR64RegisterClass;
13258 } else if (Res.second == X86::FR32RegisterClass ||
13259 Res.second == X86::FR64RegisterClass ||
13260 Res.second == X86::VR128RegisterClass) {
13261 // Handle references to XMM physical registers that got mapped into the
13262 // wrong class. This can happen with constraints like {xmm0} where the
13263 // target independent register mapper will just pick the first match it can
13264 // find, ignoring the required type.
13265 if (VT == MVT::f32)
13266 Res.second = X86::FR32RegisterClass;
13267 else if (VT == MVT::f64)
13268 Res.second = X86::FR64RegisterClass;
13269 else if (X86::VR128RegisterClass->hasType(VT))
13270 Res.second = X86::VR128RegisterClass;