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 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
75 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
76 /// simple subregister reference. Idx is an index in the 128 bits we
77 /// want. It need not be aligned to a 128-bit bounday. That makes
78 /// lowering EXTRACT_VECTOR_ELT operations easier.
79 static SDValue Extract128BitVector(SDValue Vec,
83 EVT VT = Vec.getValueType();
84 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
85 EVT ElVT = VT.getVectorElementType();
86 int Factor = VT.getSizeInBits()/128;
87 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
88 VT.getVectorNumElements()/Factor);
90 // Extract from UNDEF is UNDEF.
91 if (Vec.getOpcode() == ISD::UNDEF)
92 return DAG.getNode(ISD::UNDEF, dl, ResultVT);
94 if (isa<ConstantSDNode>(Idx)) {
95 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
97 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
98 // we can match to VEXTRACTF128.
99 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
101 // This is the index of the first element of the 128-bit chunk
103 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
106 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
107 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
116 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
117 /// sets things up to match to an AVX VINSERTF128 instruction or a
118 /// simple superregister reference. Idx is an index in the 128 bits
119 /// we want. It need not be aligned to a 128-bit bounday. That makes
120 /// lowering INSERT_VECTOR_ELT operations easier.
121 static SDValue Insert128BitVector(SDValue Result,
126 if (isa<ConstantSDNode>(Idx)) {
127 EVT VT = Vec.getValueType();
128 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
130 EVT ElVT = VT.getVectorElementType();
131 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
132 EVT ResultVT = Result.getValueType();
134 // Insert the relevant 128 bits.
135 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
137 // This is the index of the first element of the 128-bit chunk
139 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
142 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
143 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
151 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
152 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
153 bool is64Bit = Subtarget->is64Bit();
155 if (Subtarget->isTargetEnvMacho()) {
157 return new X8664_MachoTargetObjectFile();
158 return new TargetLoweringObjectFileMachO();
161 if (Subtarget->isTargetELF())
162 return new TargetLoweringObjectFileELF();
163 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
164 return new TargetLoweringObjectFileCOFF();
165 llvm_unreachable("unknown subtarget type");
168 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
169 : TargetLowering(TM, createTLOF(TM)) {
170 Subtarget = &TM.getSubtarget<X86Subtarget>();
171 X86ScalarSSEf64 = Subtarget->hasXMMInt() || Subtarget->hasAVX();
172 X86ScalarSSEf32 = Subtarget->hasXMM() || Subtarget->hasAVX();
173 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
175 RegInfo = TM.getRegisterInfo();
176 TD = getTargetData();
178 // Set up the TargetLowering object.
179 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
181 // X86 is weird, it always uses i8 for shift amounts and setcc results.
182 setBooleanContents(ZeroOrOneBooleanContent);
184 // For 64-bit since we have so many registers use the ILP scheduler, for
185 // 32-bit code use the register pressure specific scheduling.
186 if (Subtarget->is64Bit())
187 setSchedulingPreference(Sched::ILP);
189 setSchedulingPreference(Sched::RegPressure);
190 setStackPointerRegisterToSaveRestore(X86StackPtr);
192 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
193 // Setup Windows compiler runtime calls.
194 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
195 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
196 setLibcallName(RTLIB::SREM_I64, "_allrem");
197 setLibcallName(RTLIB::UREM_I64, "_aullrem");
198 setLibcallName(RTLIB::MUL_I64, "_allmul");
199 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
200 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
201 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
202 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
203 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
204 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
205 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
206 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
207 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
210 if (Subtarget->isTargetDarwin()) {
211 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
212 setUseUnderscoreSetJmp(false);
213 setUseUnderscoreLongJmp(false);
214 } else if (Subtarget->isTargetMingw()) {
215 // MS runtime is weird: it exports _setjmp, but longjmp!
216 setUseUnderscoreSetJmp(true);
217 setUseUnderscoreLongJmp(false);
219 setUseUnderscoreSetJmp(true);
220 setUseUnderscoreLongJmp(true);
223 // Set up the register classes.
224 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
225 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
226 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
227 if (Subtarget->is64Bit())
228 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
230 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
232 // We don't accept any truncstore of integer registers.
233 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
234 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
235 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
236 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
237 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
238 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
240 // SETOEQ and SETUNE require checking two conditions.
241 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
242 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
243 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
244 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
245 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
246 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
248 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
250 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
251 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
252 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
254 if (Subtarget->is64Bit()) {
255 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
256 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
257 } else if (!UseSoftFloat) {
258 // We have an algorithm for SSE2->double, and we turn this into a
259 // 64-bit FILD followed by conditional FADD for other targets.
260 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
261 // We have an algorithm for SSE2, and we turn this into a 64-bit
262 // FILD for other targets.
263 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
266 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
268 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
269 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
272 // SSE has no i16 to fp conversion, only i32
273 if (X86ScalarSSEf32) {
274 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
275 // f32 and f64 cases are Legal, f80 case is not
276 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
278 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
279 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
282 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
283 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
286 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
287 // are Legal, f80 is custom lowered.
288 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
289 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
291 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
293 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
294 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
296 if (X86ScalarSSEf32) {
297 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
298 // f32 and f64 cases are Legal, f80 case is not
299 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
301 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
302 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
305 // Handle FP_TO_UINT by promoting the destination to a larger signed
307 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
308 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
309 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
311 if (Subtarget->is64Bit()) {
312 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
313 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
314 } else if (!UseSoftFloat) {
315 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
316 // Expand FP_TO_UINT into a select.
317 // FIXME: We would like to use a Custom expander here eventually to do
318 // the optimal thing for SSE vs. the default expansion in the legalizer.
319 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
321 // With SSE3 we can use fisttpll to convert to a signed i64; without
322 // SSE, we're stuck with a fistpll.
323 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
326 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
327 if (!X86ScalarSSEf64) {
328 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
329 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
330 if (Subtarget->is64Bit()) {
331 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
332 // Without SSE, i64->f64 goes through memory.
333 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
337 // Scalar integer divide and remainder are lowered to use operations that
338 // produce two results, to match the available instructions. This exposes
339 // the two-result form to trivial CSE, which is able to combine x/y and x%y
340 // into a single instruction.
342 // Scalar integer multiply-high is also lowered to use two-result
343 // operations, to match the available instructions. However, plain multiply
344 // (low) operations are left as Legal, as there are single-result
345 // instructions for this in x86. Using the two-result multiply instructions
346 // when both high and low results are needed must be arranged by dagcombine.
347 for (unsigned i = 0, e = 4; i != e; ++i) {
349 setOperationAction(ISD::MULHS, VT, Expand);
350 setOperationAction(ISD::MULHU, VT, Expand);
351 setOperationAction(ISD::SDIV, VT, Expand);
352 setOperationAction(ISD::UDIV, VT, Expand);
353 setOperationAction(ISD::SREM, VT, Expand);
354 setOperationAction(ISD::UREM, VT, Expand);
356 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
357 setOperationAction(ISD::ADDC, VT, Custom);
358 setOperationAction(ISD::ADDE, VT, Custom);
359 setOperationAction(ISD::SUBC, VT, Custom);
360 setOperationAction(ISD::SUBE, VT, Custom);
363 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
364 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
365 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
366 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
367 if (Subtarget->is64Bit())
368 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
369 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
370 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
371 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
372 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
373 setOperationAction(ISD::FREM , MVT::f32 , Expand);
374 setOperationAction(ISD::FREM , MVT::f64 , Expand);
375 setOperationAction(ISD::FREM , MVT::f80 , Expand);
376 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
378 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
379 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
380 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
381 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
382 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
383 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
384 if (Subtarget->is64Bit()) {
385 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
386 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
389 if (Subtarget->hasPOPCNT()) {
390 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
392 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
393 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
394 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
395 if (Subtarget->is64Bit())
396 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
399 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
400 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
402 // These should be promoted to a larger select which is supported.
403 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
404 // X86 wants to expand cmov itself.
405 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
406 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
407 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
408 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
409 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
410 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
411 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
412 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
413 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
414 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
415 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
416 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
417 if (Subtarget->is64Bit()) {
418 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
419 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
421 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
424 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
425 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
426 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
427 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
428 if (Subtarget->is64Bit())
429 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
430 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
431 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
432 if (Subtarget->is64Bit()) {
433 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
434 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
435 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
436 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
437 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
439 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
440 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
441 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
442 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
443 if (Subtarget->is64Bit()) {
444 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
445 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
446 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
449 if (Subtarget->hasXMM())
450 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
452 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
453 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
455 // On X86 and X86-64, atomic operations are lowered to locked instructions.
456 // Locked instructions, in turn, have implicit fence semantics (all memory
457 // operations are flushed before issuing the locked instruction, and they
458 // are not buffered), so we can fold away the common pattern of
459 // fence-atomic-fence.
460 setShouldFoldAtomicFences(true);
462 // Expand certain atomics
463 for (unsigned i = 0, e = 4; i != e; ++i) {
465 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
466 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
467 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
470 if (!Subtarget->is64Bit()) {
471 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
472 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
473 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
474 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
475 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
476 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
477 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
478 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
481 // FIXME - use subtarget debug flags
482 if (!Subtarget->isTargetDarwin() &&
483 !Subtarget->isTargetELF() &&
484 !Subtarget->isTargetCygMing()) {
485 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
488 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
489 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
490 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
491 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
492 if (Subtarget->is64Bit()) {
493 setExceptionPointerRegister(X86::RAX);
494 setExceptionSelectorRegister(X86::RDX);
496 setExceptionPointerRegister(X86::EAX);
497 setExceptionSelectorRegister(X86::EDX);
499 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
500 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
502 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
504 setOperationAction(ISD::TRAP, MVT::Other, Legal);
506 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
507 setOperationAction(ISD::VASTART , MVT::Other, Custom);
508 setOperationAction(ISD::VAEND , MVT::Other, Expand);
509 if (Subtarget->is64Bit()) {
510 setOperationAction(ISD::VAARG , MVT::Other, Custom);
511 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
513 setOperationAction(ISD::VAARG , MVT::Other, Expand);
514 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
517 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
518 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
519 setOperationAction(ISD::DYNAMIC_STACKALLOC,
520 (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
521 (Subtarget->isTargetCOFF()
522 && !Subtarget->isTargetEnvMacho()
525 if (!UseSoftFloat && X86ScalarSSEf64) {
526 // f32 and f64 use SSE.
527 // Set up the FP register classes.
528 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
529 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
531 // Use ANDPD to simulate FABS.
532 setOperationAction(ISD::FABS , MVT::f64, Custom);
533 setOperationAction(ISD::FABS , MVT::f32, Custom);
535 // Use XORP to simulate FNEG.
536 setOperationAction(ISD::FNEG , MVT::f64, Custom);
537 setOperationAction(ISD::FNEG , MVT::f32, Custom);
539 // Use ANDPD and ORPD to simulate FCOPYSIGN.
540 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
541 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
543 // Lower this to FGETSIGNx86 plus an AND.
544 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
545 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
547 // We don't support sin/cos/fmod
548 setOperationAction(ISD::FSIN , MVT::f64, Expand);
549 setOperationAction(ISD::FCOS , MVT::f64, Expand);
550 setOperationAction(ISD::FSIN , MVT::f32, Expand);
551 setOperationAction(ISD::FCOS , MVT::f32, Expand);
553 // Expand FP immediates into loads from the stack, except for the special
555 addLegalFPImmediate(APFloat(+0.0)); // xorpd
556 addLegalFPImmediate(APFloat(+0.0f)); // xorps
557 } else if (!UseSoftFloat && X86ScalarSSEf32) {
558 // Use SSE for f32, x87 for f64.
559 // Set up the FP register classes.
560 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
561 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
563 // Use ANDPS to simulate FABS.
564 setOperationAction(ISD::FABS , MVT::f32, Custom);
566 // Use XORP to simulate FNEG.
567 setOperationAction(ISD::FNEG , MVT::f32, Custom);
569 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
571 // Use ANDPS and ORPS to simulate FCOPYSIGN.
572 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
573 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
575 // We don't support sin/cos/fmod
576 setOperationAction(ISD::FSIN , MVT::f32, Expand);
577 setOperationAction(ISD::FCOS , MVT::f32, Expand);
579 // Special cases we handle for FP constants.
580 addLegalFPImmediate(APFloat(+0.0f)); // xorps
581 addLegalFPImmediate(APFloat(+0.0)); // FLD0
582 addLegalFPImmediate(APFloat(+1.0)); // FLD1
583 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
584 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
587 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
588 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
590 } else if (!UseSoftFloat) {
591 // f32 and f64 in x87.
592 // Set up the FP register classes.
593 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
594 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
596 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
597 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
598 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
599 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
602 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
603 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
605 addLegalFPImmediate(APFloat(+0.0)); // FLD0
606 addLegalFPImmediate(APFloat(+1.0)); // FLD1
607 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
608 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
609 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
610 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
611 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
612 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
615 // We don't support FMA.
616 setOperationAction(ISD::FMA, MVT::f64, Expand);
617 setOperationAction(ISD::FMA, MVT::f32, Expand);
619 // Long double always uses X87.
621 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
622 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
623 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
625 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
626 addLegalFPImmediate(TmpFlt); // FLD0
628 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
631 APFloat TmpFlt2(+1.0);
632 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
634 addLegalFPImmediate(TmpFlt2); // FLD1
635 TmpFlt2.changeSign();
636 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
640 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
641 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
644 setOperationAction(ISD::FMA, MVT::f80, Expand);
647 // Always use a library call for pow.
648 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
649 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
650 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
652 setOperationAction(ISD::FLOG, MVT::f80, Expand);
653 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
654 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
655 setOperationAction(ISD::FEXP, MVT::f80, Expand);
656 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
658 // First set operation action for all vector types to either promote
659 // (for widening) or expand (for scalarization). Then we will selectively
660 // turn on ones that can be effectively codegen'd.
661 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
662 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
663 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
664 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
665 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
666 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
667 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
668 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
669 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
670 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
671 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
672 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
673 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
674 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
675 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
676 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
677 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
678 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
679 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
680 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
681 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
682 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
683 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
684 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
685 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
686 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
687 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
688 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
689 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
690 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
691 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
692 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
693 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
694 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
695 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
696 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
698 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
699 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
700 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
701 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
702 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
703 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
704 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
705 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
713 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
717 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
718 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
719 setTruncStoreAction((MVT::SimpleValueType)VT,
720 (MVT::SimpleValueType)InnerVT, Expand);
721 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
722 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
723 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
726 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
727 // with -msoft-float, disable use of MMX as well.
728 if (!UseSoftFloat && Subtarget->hasMMX()) {
729 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
730 // No operations on x86mmx supported, everything uses intrinsics.
733 // MMX-sized vectors (other than x86mmx) are expected to be expanded
734 // into smaller operations.
735 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
736 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
737 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
738 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
739 setOperationAction(ISD::AND, MVT::v8i8, Expand);
740 setOperationAction(ISD::AND, MVT::v4i16, Expand);
741 setOperationAction(ISD::AND, MVT::v2i32, Expand);
742 setOperationAction(ISD::AND, MVT::v1i64, Expand);
743 setOperationAction(ISD::OR, MVT::v8i8, Expand);
744 setOperationAction(ISD::OR, MVT::v4i16, Expand);
745 setOperationAction(ISD::OR, MVT::v2i32, Expand);
746 setOperationAction(ISD::OR, MVT::v1i64, Expand);
747 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
748 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
749 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
750 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
751 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
752 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
753 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
754 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
755 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
756 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
757 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
758 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
759 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
760 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
761 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
762 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
763 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
765 if (!UseSoftFloat && Subtarget->hasXMM()) {
766 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
768 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
769 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
770 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
771 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
772 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
773 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
774 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
775 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
776 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
777 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
778 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
779 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
782 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
783 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
785 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
786 // registers cannot be used even for integer operations.
787 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
788 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
789 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
790 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
792 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
793 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
794 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
795 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
796 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
797 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
798 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
799 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
800 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
801 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
802 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
803 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
804 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
805 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
806 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
807 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
809 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
810 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
811 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
812 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
814 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
815 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
816 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
817 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
818 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
820 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
821 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
822 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
823 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
824 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
826 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
827 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
828 EVT VT = (MVT::SimpleValueType)i;
829 // Do not attempt to custom lower non-power-of-2 vectors
830 if (!isPowerOf2_32(VT.getVectorNumElements()))
832 // Do not attempt to custom lower non-128-bit vectors
833 if (!VT.is128BitVector())
835 setOperationAction(ISD::BUILD_VECTOR,
836 VT.getSimpleVT().SimpleTy, Custom);
837 setOperationAction(ISD::VECTOR_SHUFFLE,
838 VT.getSimpleVT().SimpleTy, Custom);
839 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
840 VT.getSimpleVT().SimpleTy, Custom);
843 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
844 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
845 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
846 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
847 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
848 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
850 if (Subtarget->is64Bit()) {
851 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
852 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
855 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
856 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
857 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
860 // Do not attempt to promote non-128-bit vectors
861 if (!VT.is128BitVector())
864 setOperationAction(ISD::AND, SVT, Promote);
865 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
866 setOperationAction(ISD::OR, SVT, Promote);
867 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
868 setOperationAction(ISD::XOR, SVT, Promote);
869 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
870 setOperationAction(ISD::LOAD, SVT, Promote);
871 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
872 setOperationAction(ISD::SELECT, SVT, Promote);
873 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
876 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
878 // Custom lower v2i64 and v2f64 selects.
879 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
880 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
881 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
882 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
884 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
885 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
888 if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
889 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
890 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
891 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
892 setOperationAction(ISD::FRINT, MVT::f32, Legal);
893 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
894 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
895 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
896 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
897 setOperationAction(ISD::FRINT, MVT::f64, Legal);
898 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
900 // FIXME: Do we need to handle scalar-to-vector here?
901 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
903 // Can turn SHL into an integer multiply.
904 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
905 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
907 // i8 and i16 vectors are custom , because the source register and source
908 // source memory operand types are not the same width. f32 vectors are
909 // custom since the immediate controlling the insert encodes additional
911 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
912 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
913 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
914 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
916 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
917 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
918 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
919 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
921 if (Subtarget->is64Bit()) {
922 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
923 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
927 if (Subtarget->hasSSE2() || Subtarget->hasAVX()) {
928 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
929 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
930 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
931 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
933 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
934 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
935 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
937 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
938 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
941 if (Subtarget->hasSSE42() || Subtarget->hasAVX())
942 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
944 if (!UseSoftFloat && Subtarget->hasAVX()) {
945 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
946 addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
947 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
948 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
949 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
950 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
952 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
953 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
954 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
956 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
957 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
958 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
959 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
960 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
961 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
963 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
964 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
965 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
966 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
967 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
968 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
970 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
971 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
972 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
974 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom);
975 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom);
976 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
977 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
978 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom);
979 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom);
981 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
982 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
983 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
984 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
986 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
987 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
988 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
989 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
991 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
992 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
994 setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
995 setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
996 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
997 setOperationAction(ISD::VSETCC, MVT::v4i64, Custom);
999 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1000 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1001 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1003 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1004 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1005 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1006 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1008 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1009 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1010 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1011 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1013 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1014 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1015 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1016 // Don't lower v32i8 because there is no 128-bit byte mul
1018 // Custom lower several nodes for 256-bit types.
1019 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1020 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1021 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1024 // Extract subvector is special because the value type
1025 // (result) is 128-bit but the source is 256-bit wide.
1026 if (VT.is128BitVector())
1027 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1029 // Do not attempt to custom lower other non-256-bit vectors
1030 if (!VT.is256BitVector())
1033 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1034 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1035 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1036 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1037 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1038 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1041 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1042 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1043 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1046 // Do not attempt to promote non-256-bit vectors
1047 if (!VT.is256BitVector())
1050 setOperationAction(ISD::AND, SVT, Promote);
1051 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1052 setOperationAction(ISD::OR, SVT, Promote);
1053 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1054 setOperationAction(ISD::XOR, SVT, Promote);
1055 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1056 setOperationAction(ISD::LOAD, SVT, Promote);
1057 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1058 setOperationAction(ISD::SELECT, SVT, Promote);
1059 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1063 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1064 // of this type with custom code.
1065 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1066 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1067 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1070 // We want to custom lower some of our intrinsics.
1071 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1074 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1075 // handle type legalization for these operations here.
1077 // FIXME: We really should do custom legalization for addition and
1078 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1079 // than generic legalization for 64-bit multiplication-with-overflow, though.
1080 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1081 // Add/Sub/Mul with overflow operations are custom lowered.
1083 setOperationAction(ISD::SADDO, VT, Custom);
1084 setOperationAction(ISD::UADDO, VT, Custom);
1085 setOperationAction(ISD::SSUBO, VT, Custom);
1086 setOperationAction(ISD::USUBO, VT, Custom);
1087 setOperationAction(ISD::SMULO, VT, Custom);
1088 setOperationAction(ISD::UMULO, VT, Custom);
1091 // There are no 8-bit 3-address imul/mul instructions
1092 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1093 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1095 if (!Subtarget->is64Bit()) {
1096 // These libcalls are not available in 32-bit.
1097 setLibcallName(RTLIB::SHL_I128, 0);
1098 setLibcallName(RTLIB::SRL_I128, 0);
1099 setLibcallName(RTLIB::SRA_I128, 0);
1102 // We have target-specific dag combine patterns for the following nodes:
1103 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1104 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1105 setTargetDAGCombine(ISD::BUILD_VECTOR);
1106 setTargetDAGCombine(ISD::SELECT);
1107 setTargetDAGCombine(ISD::SHL);
1108 setTargetDAGCombine(ISD::SRA);
1109 setTargetDAGCombine(ISD::SRL);
1110 setTargetDAGCombine(ISD::OR);
1111 setTargetDAGCombine(ISD::AND);
1112 setTargetDAGCombine(ISD::ADD);
1113 setTargetDAGCombine(ISD::SUB);
1114 setTargetDAGCombine(ISD::STORE);
1115 setTargetDAGCombine(ISD::ZERO_EXTEND);
1116 setTargetDAGCombine(ISD::SINT_TO_FP);
1117 if (Subtarget->is64Bit())
1118 setTargetDAGCombine(ISD::MUL);
1120 computeRegisterProperties();
1122 // On Darwin, -Os means optimize for size without hurting performance,
1123 // do not reduce the limit.
1124 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1125 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1126 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1127 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1128 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1129 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1130 setPrefLoopAlignment(16);
1131 benefitFromCodePlacementOpt = true;
1133 setPrefFunctionAlignment(4);
1137 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1142 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1143 /// the desired ByVal argument alignment.
1144 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1147 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1148 if (VTy->getBitWidth() == 128)
1150 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1151 unsigned EltAlign = 0;
1152 getMaxByValAlign(ATy->getElementType(), EltAlign);
1153 if (EltAlign > MaxAlign)
1154 MaxAlign = EltAlign;
1155 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1156 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1157 unsigned EltAlign = 0;
1158 getMaxByValAlign(STy->getElementType(i), EltAlign);
1159 if (EltAlign > MaxAlign)
1160 MaxAlign = EltAlign;
1168 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1169 /// function arguments in the caller parameter area. For X86, aggregates
1170 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1171 /// are at 4-byte boundaries.
1172 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1173 if (Subtarget->is64Bit()) {
1174 // Max of 8 and alignment of type.
1175 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1182 if (Subtarget->hasXMM())
1183 getMaxByValAlign(Ty, Align);
1187 /// getOptimalMemOpType - Returns the target specific optimal type for load
1188 /// and store operations as a result of memset, memcpy, and memmove
1189 /// lowering. If DstAlign is zero that means it's safe to destination
1190 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1191 /// means there isn't a need to check it against alignment requirement,
1192 /// probably because the source does not need to be loaded. If
1193 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1194 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1195 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1196 /// constant so it does not need to be loaded.
1197 /// It returns EVT::Other if the type should be determined using generic
1198 /// target-independent logic.
1200 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1201 unsigned DstAlign, unsigned SrcAlign,
1202 bool NonScalarIntSafe,
1204 MachineFunction &MF) const {
1205 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1206 // linux. This is because the stack realignment code can't handle certain
1207 // cases like PR2962. This should be removed when PR2962 is fixed.
1208 const Function *F = MF.getFunction();
1209 if (NonScalarIntSafe &&
1210 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1212 (Subtarget->isUnalignedMemAccessFast() ||
1213 ((DstAlign == 0 || DstAlign >= 16) &&
1214 (SrcAlign == 0 || SrcAlign >= 16))) &&
1215 Subtarget->getStackAlignment() >= 16) {
1216 if (Subtarget->hasSSE2())
1218 if (Subtarget->hasSSE1())
1220 } else if (!MemcpyStrSrc && Size >= 8 &&
1221 !Subtarget->is64Bit() &&
1222 Subtarget->getStackAlignment() >= 8 &&
1223 Subtarget->hasXMMInt()) {
1224 // Do not use f64 to lower memcpy if source is string constant. It's
1225 // better to use i32 to avoid the loads.
1229 if (Subtarget->is64Bit() && Size >= 8)
1234 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1235 /// current function. The returned value is a member of the
1236 /// MachineJumpTableInfo::JTEntryKind enum.
1237 unsigned X86TargetLowering::getJumpTableEncoding() const {
1238 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1240 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1241 Subtarget->isPICStyleGOT())
1242 return MachineJumpTableInfo::EK_Custom32;
1244 // Otherwise, use the normal jump table encoding heuristics.
1245 return TargetLowering::getJumpTableEncoding();
1249 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1250 const MachineBasicBlock *MBB,
1251 unsigned uid,MCContext &Ctx) const{
1252 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1253 Subtarget->isPICStyleGOT());
1254 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1256 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1257 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1260 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1262 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1263 SelectionDAG &DAG) const {
1264 if (!Subtarget->is64Bit())
1265 // This doesn't have DebugLoc associated with it, but is not really the
1266 // same as a Register.
1267 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1271 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1272 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1274 const MCExpr *X86TargetLowering::
1275 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1276 MCContext &Ctx) const {
1277 // X86-64 uses RIP relative addressing based on the jump table label.
1278 if (Subtarget->isPICStyleRIPRel())
1279 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1281 // Otherwise, the reference is relative to the PIC base.
1282 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1285 // FIXME: Why this routine is here? Move to RegInfo!
1286 std::pair<const TargetRegisterClass*, uint8_t>
1287 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1288 const TargetRegisterClass *RRC = 0;
1290 switch (VT.getSimpleVT().SimpleTy) {
1292 return TargetLowering::findRepresentativeClass(VT);
1293 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1294 RRC = (Subtarget->is64Bit()
1295 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1298 RRC = X86::VR64RegisterClass;
1300 case MVT::f32: case MVT::f64:
1301 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1302 case MVT::v4f32: case MVT::v2f64:
1303 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1305 RRC = X86::VR128RegisterClass;
1308 return std::make_pair(RRC, Cost);
1311 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1312 unsigned &Offset) const {
1313 if (!Subtarget->isTargetLinux())
1316 if (Subtarget->is64Bit()) {
1317 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1319 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1332 //===----------------------------------------------------------------------===//
1333 // Return Value Calling Convention Implementation
1334 //===----------------------------------------------------------------------===//
1336 #include "X86GenCallingConv.inc"
1339 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1340 MachineFunction &MF, bool isVarArg,
1341 const SmallVectorImpl<ISD::OutputArg> &Outs,
1342 LLVMContext &Context) const {
1343 SmallVector<CCValAssign, 16> RVLocs;
1344 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1346 return CCInfo.CheckReturn(Outs, RetCC_X86);
1350 X86TargetLowering::LowerReturn(SDValue Chain,
1351 CallingConv::ID CallConv, bool isVarArg,
1352 const SmallVectorImpl<ISD::OutputArg> &Outs,
1353 const SmallVectorImpl<SDValue> &OutVals,
1354 DebugLoc dl, SelectionDAG &DAG) const {
1355 MachineFunction &MF = DAG.getMachineFunction();
1356 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1358 SmallVector<CCValAssign, 16> RVLocs;
1359 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1360 RVLocs, *DAG.getContext());
1361 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1363 // Add the regs to the liveout set for the function.
1364 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1365 for (unsigned i = 0; i != RVLocs.size(); ++i)
1366 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1367 MRI.addLiveOut(RVLocs[i].getLocReg());
1371 SmallVector<SDValue, 6> RetOps;
1372 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1373 // Operand #1 = Bytes To Pop
1374 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1377 // Copy the result values into the output registers.
1378 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1379 CCValAssign &VA = RVLocs[i];
1380 assert(VA.isRegLoc() && "Can only return in registers!");
1381 SDValue ValToCopy = OutVals[i];
1382 EVT ValVT = ValToCopy.getValueType();
1384 // If this is x86-64, and we disabled SSE, we can't return FP values,
1385 // or SSE or MMX vectors.
1386 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1387 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1388 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1389 report_fatal_error("SSE register return with SSE disabled");
1391 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1392 // llvm-gcc has never done it right and no one has noticed, so this
1393 // should be OK for now.
1394 if (ValVT == MVT::f64 &&
1395 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1396 report_fatal_error("SSE2 register return with SSE2 disabled");
1398 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1399 // the RET instruction and handled by the FP Stackifier.
1400 if (VA.getLocReg() == X86::ST0 ||
1401 VA.getLocReg() == X86::ST1) {
1402 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1403 // change the value to the FP stack register class.
1404 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1405 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1406 RetOps.push_back(ValToCopy);
1407 // Don't emit a copytoreg.
1411 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1412 // which is returned in RAX / RDX.
1413 if (Subtarget->is64Bit()) {
1414 if (ValVT == MVT::x86mmx) {
1415 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1416 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1417 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1419 // If we don't have SSE2 available, convert to v4f32 so the generated
1420 // register is legal.
1421 if (!Subtarget->hasSSE2())
1422 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1427 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1428 Flag = Chain.getValue(1);
1431 // The x86-64 ABI for returning structs by value requires that we copy
1432 // the sret argument into %rax for the return. We saved the argument into
1433 // a virtual register in the entry block, so now we copy the value out
1435 if (Subtarget->is64Bit() &&
1436 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1437 MachineFunction &MF = DAG.getMachineFunction();
1438 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1439 unsigned Reg = FuncInfo->getSRetReturnReg();
1441 "SRetReturnReg should have been set in LowerFormalArguments().");
1442 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1444 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1445 Flag = Chain.getValue(1);
1447 // RAX now acts like a return value.
1448 MRI.addLiveOut(X86::RAX);
1451 RetOps[0] = Chain; // Update chain.
1453 // Add the flag if we have it.
1455 RetOps.push_back(Flag);
1457 return DAG.getNode(X86ISD::RET_FLAG, dl,
1458 MVT::Other, &RetOps[0], RetOps.size());
1461 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1462 if (N->getNumValues() != 1)
1464 if (!N->hasNUsesOfValue(1, 0))
1467 SDNode *Copy = *N->use_begin();
1468 if (Copy->getOpcode() != ISD::CopyToReg &&
1469 Copy->getOpcode() != ISD::FP_EXTEND)
1472 bool HasRet = false;
1473 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1475 if (UI->getOpcode() != X86ISD::RET_FLAG)
1484 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1485 ISD::NodeType ExtendKind) const {
1487 // TODO: Is this also valid on 32-bit?
1488 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1489 ReturnMVT = MVT::i8;
1491 ReturnMVT = MVT::i32;
1493 EVT MinVT = getRegisterType(Context, ReturnMVT);
1494 return VT.bitsLT(MinVT) ? MinVT : VT;
1497 /// LowerCallResult - Lower the result values of a call into the
1498 /// appropriate copies out of appropriate physical registers.
1501 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1502 CallingConv::ID CallConv, bool isVarArg,
1503 const SmallVectorImpl<ISD::InputArg> &Ins,
1504 DebugLoc dl, SelectionDAG &DAG,
1505 SmallVectorImpl<SDValue> &InVals) const {
1507 // Assign locations to each value returned by this call.
1508 SmallVector<CCValAssign, 16> RVLocs;
1509 bool Is64Bit = Subtarget->is64Bit();
1510 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1511 getTargetMachine(), RVLocs, *DAG.getContext());
1512 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1514 // Copy all of the result registers out of their specified physreg.
1515 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1516 CCValAssign &VA = RVLocs[i];
1517 EVT CopyVT = VA.getValVT();
1519 // If this is x86-64, and we disabled SSE, we can't return FP values
1520 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1521 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1522 report_fatal_error("SSE register return with SSE disabled");
1527 // If this is a call to a function that returns an fp value on the floating
1528 // point stack, we must guarantee the the value is popped from the stack, so
1529 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1530 // if the return value is not used. We use the FpPOP_RETVAL instruction
1532 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1533 // If we prefer to use the value in xmm registers, copy it out as f80 and
1534 // use a truncate to move it from fp stack reg to xmm reg.
1535 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1536 SDValue Ops[] = { Chain, InFlag };
1537 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1538 MVT::Other, MVT::Glue, Ops, 2), 1);
1539 Val = Chain.getValue(0);
1541 // Round the f80 to the right size, which also moves it to the appropriate
1543 if (CopyVT != VA.getValVT())
1544 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1545 // This truncation won't change the value.
1546 DAG.getIntPtrConstant(1));
1548 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1549 CopyVT, InFlag).getValue(1);
1550 Val = Chain.getValue(0);
1552 InFlag = Chain.getValue(2);
1553 InVals.push_back(Val);
1560 //===----------------------------------------------------------------------===//
1561 // C & StdCall & Fast Calling Convention implementation
1562 //===----------------------------------------------------------------------===//
1563 // StdCall calling convention seems to be standard for many Windows' API
1564 // routines and around. It differs from C calling convention just a little:
1565 // callee should clean up the stack, not caller. Symbols should be also
1566 // decorated in some fancy way :) It doesn't support any vector arguments.
1567 // For info on fast calling convention see Fast Calling Convention (tail call)
1568 // implementation LowerX86_32FastCCCallTo.
1570 /// CallIsStructReturn - Determines whether a call uses struct return
1572 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1576 return Outs[0].Flags.isSRet();
1579 /// ArgsAreStructReturn - Determines whether a function uses struct
1580 /// return semantics.
1582 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1586 return Ins[0].Flags.isSRet();
1589 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1590 /// by "Src" to address "Dst" with size and alignment information specified by
1591 /// the specific parameter attribute. The copy will be passed as a byval
1592 /// function parameter.
1594 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1595 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1597 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1599 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1600 /*isVolatile*/false, /*AlwaysInline=*/true,
1601 MachinePointerInfo(), MachinePointerInfo());
1604 /// IsTailCallConvention - Return true if the calling convention is one that
1605 /// supports tail call optimization.
1606 static bool IsTailCallConvention(CallingConv::ID CC) {
1607 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1610 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1611 if (!CI->isTailCall())
1615 CallingConv::ID CalleeCC = CS.getCallingConv();
1616 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1622 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1623 /// a tailcall target by changing its ABI.
1624 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1625 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1629 X86TargetLowering::LowerMemArgument(SDValue Chain,
1630 CallingConv::ID CallConv,
1631 const SmallVectorImpl<ISD::InputArg> &Ins,
1632 DebugLoc dl, SelectionDAG &DAG,
1633 const CCValAssign &VA,
1634 MachineFrameInfo *MFI,
1636 // Create the nodes corresponding to a load from this parameter slot.
1637 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1638 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1639 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1642 // If value is passed by pointer we have address passed instead of the value
1644 if (VA.getLocInfo() == CCValAssign::Indirect)
1645 ValVT = VA.getLocVT();
1647 ValVT = VA.getValVT();
1649 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1650 // changed with more analysis.
1651 // In case of tail call optimization mark all arguments mutable. Since they
1652 // could be overwritten by lowering of arguments in case of a tail call.
1653 if (Flags.isByVal()) {
1654 unsigned Bytes = Flags.getByValSize();
1655 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1656 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1657 return DAG.getFrameIndex(FI, getPointerTy());
1659 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1660 VA.getLocMemOffset(), isImmutable);
1661 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1662 return DAG.getLoad(ValVT, dl, Chain, FIN,
1663 MachinePointerInfo::getFixedStack(FI),
1669 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1670 CallingConv::ID CallConv,
1672 const SmallVectorImpl<ISD::InputArg> &Ins,
1675 SmallVectorImpl<SDValue> &InVals)
1677 MachineFunction &MF = DAG.getMachineFunction();
1678 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1680 const Function* Fn = MF.getFunction();
1681 if (Fn->hasExternalLinkage() &&
1682 Subtarget->isTargetCygMing() &&
1683 Fn->getName() == "main")
1684 FuncInfo->setForceFramePointer(true);
1686 MachineFrameInfo *MFI = MF.getFrameInfo();
1687 bool Is64Bit = Subtarget->is64Bit();
1688 bool IsWin64 = Subtarget->isTargetWin64();
1690 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1691 "Var args not supported with calling convention fastcc or ghc");
1693 // Assign locations to all of the incoming arguments.
1694 SmallVector<CCValAssign, 16> ArgLocs;
1695 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1696 ArgLocs, *DAG.getContext());
1698 // Allocate shadow area for Win64
1700 CCInfo.AllocateStack(32, 8);
1703 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1705 unsigned LastVal = ~0U;
1707 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1708 CCValAssign &VA = ArgLocs[i];
1709 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1711 assert(VA.getValNo() != LastVal &&
1712 "Don't support value assigned to multiple locs yet");
1713 LastVal = VA.getValNo();
1715 if (VA.isRegLoc()) {
1716 EVT RegVT = VA.getLocVT();
1717 TargetRegisterClass *RC = NULL;
1718 if (RegVT == MVT::i32)
1719 RC = X86::GR32RegisterClass;
1720 else if (Is64Bit && RegVT == MVT::i64)
1721 RC = X86::GR64RegisterClass;
1722 else if (RegVT == MVT::f32)
1723 RC = X86::FR32RegisterClass;
1724 else if (RegVT == MVT::f64)
1725 RC = X86::FR64RegisterClass;
1726 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1727 RC = X86::VR256RegisterClass;
1728 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1729 RC = X86::VR128RegisterClass;
1730 else if (RegVT == MVT::x86mmx)
1731 RC = X86::VR64RegisterClass;
1733 llvm_unreachable("Unknown argument type!");
1735 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1736 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1738 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1739 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1741 if (VA.getLocInfo() == CCValAssign::SExt)
1742 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1743 DAG.getValueType(VA.getValVT()));
1744 else if (VA.getLocInfo() == CCValAssign::ZExt)
1745 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1746 DAG.getValueType(VA.getValVT()));
1747 else if (VA.getLocInfo() == CCValAssign::BCvt)
1748 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1750 if (VA.isExtInLoc()) {
1751 // Handle MMX values passed in XMM regs.
1752 if (RegVT.isVector()) {
1753 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1756 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1759 assert(VA.isMemLoc());
1760 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1763 // If value is passed via pointer - do a load.
1764 if (VA.getLocInfo() == CCValAssign::Indirect)
1765 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1766 MachinePointerInfo(), false, false, 0);
1768 InVals.push_back(ArgValue);
1771 // The x86-64 ABI for returning structs by value requires that we copy
1772 // the sret argument into %rax for the return. Save the argument into
1773 // a virtual register so that we can access it from the return points.
1774 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1775 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1776 unsigned Reg = FuncInfo->getSRetReturnReg();
1778 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1779 FuncInfo->setSRetReturnReg(Reg);
1781 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1782 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1785 unsigned StackSize = CCInfo.getNextStackOffset();
1786 // Align stack specially for tail calls.
1787 if (FuncIsMadeTailCallSafe(CallConv))
1788 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1790 // If the function takes variable number of arguments, make a frame index for
1791 // the start of the first vararg value... for expansion of llvm.va_start.
1793 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1794 CallConv != CallingConv::X86_ThisCall)) {
1795 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1798 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1800 // FIXME: We should really autogenerate these arrays
1801 static const unsigned GPR64ArgRegsWin64[] = {
1802 X86::RCX, X86::RDX, X86::R8, X86::R9
1804 static const unsigned GPR64ArgRegs64Bit[] = {
1805 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1807 static const unsigned XMMArgRegs64Bit[] = {
1808 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1809 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1811 const unsigned *GPR64ArgRegs;
1812 unsigned NumXMMRegs = 0;
1815 // The XMM registers which might contain var arg parameters are shadowed
1816 // in their paired GPR. So we only need to save the GPR to their home
1818 TotalNumIntRegs = 4;
1819 GPR64ArgRegs = GPR64ArgRegsWin64;
1821 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1822 GPR64ArgRegs = GPR64ArgRegs64Bit;
1824 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1826 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1829 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1830 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1831 "SSE register cannot be used when SSE is disabled!");
1832 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1833 "SSE register cannot be used when SSE is disabled!");
1834 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1835 // Kernel mode asks for SSE to be disabled, so don't push them
1837 TotalNumXMMRegs = 0;
1840 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1841 // Get to the caller-allocated home save location. Add 8 to account
1842 // for the return address.
1843 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1844 FuncInfo->setRegSaveFrameIndex(
1845 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1846 // Fixup to set vararg frame on shadow area (4 x i64).
1848 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1850 // For X86-64, if there are vararg parameters that are passed via
1851 // registers, then we must store them to their spots on the stack so they
1852 // may be loaded by deferencing the result of va_next.
1853 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1854 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1855 FuncInfo->setRegSaveFrameIndex(
1856 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1860 // Store the integer parameter registers.
1861 SmallVector<SDValue, 8> MemOps;
1862 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1864 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1865 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1866 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1867 DAG.getIntPtrConstant(Offset));
1868 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1869 X86::GR64RegisterClass);
1870 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1872 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1873 MachinePointerInfo::getFixedStack(
1874 FuncInfo->getRegSaveFrameIndex(), Offset),
1876 MemOps.push_back(Store);
1880 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1881 // Now store the XMM (fp + vector) parameter registers.
1882 SmallVector<SDValue, 11> SaveXMMOps;
1883 SaveXMMOps.push_back(Chain);
1885 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1886 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1887 SaveXMMOps.push_back(ALVal);
1889 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1890 FuncInfo->getRegSaveFrameIndex()));
1891 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1892 FuncInfo->getVarArgsFPOffset()));
1894 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1895 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1896 X86::VR128RegisterClass);
1897 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1898 SaveXMMOps.push_back(Val);
1900 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1902 &SaveXMMOps[0], SaveXMMOps.size()));
1905 if (!MemOps.empty())
1906 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1907 &MemOps[0], MemOps.size());
1911 // Some CCs need callee pop.
1912 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1913 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1915 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1916 // If this is an sret function, the return should pop the hidden pointer.
1917 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1918 FuncInfo->setBytesToPopOnReturn(4);
1922 // RegSaveFrameIndex is X86-64 only.
1923 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1924 if (CallConv == CallingConv::X86_FastCall ||
1925 CallConv == CallingConv::X86_ThisCall)
1926 // fastcc functions can't have varargs.
1927 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1934 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1935 SDValue StackPtr, SDValue Arg,
1936 DebugLoc dl, SelectionDAG &DAG,
1937 const CCValAssign &VA,
1938 ISD::ArgFlagsTy Flags) const {
1939 unsigned LocMemOffset = VA.getLocMemOffset();
1940 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1941 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1942 if (Flags.isByVal())
1943 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1945 return DAG.getStore(Chain, dl, Arg, PtrOff,
1946 MachinePointerInfo::getStack(LocMemOffset),
1950 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1951 /// optimization is performed and it is required.
1953 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1954 SDValue &OutRetAddr, SDValue Chain,
1955 bool IsTailCall, bool Is64Bit,
1956 int FPDiff, DebugLoc dl) const {
1957 // Adjust the Return address stack slot.
1958 EVT VT = getPointerTy();
1959 OutRetAddr = getReturnAddressFrameIndex(DAG);
1961 // Load the "old" Return address.
1962 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1964 return SDValue(OutRetAddr.getNode(), 1);
1967 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1968 /// optimization is performed and it is required (FPDiff!=0).
1970 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1971 SDValue Chain, SDValue RetAddrFrIdx,
1972 bool Is64Bit, int FPDiff, DebugLoc dl) {
1973 // Store the return address to the appropriate stack slot.
1974 if (!FPDiff) return Chain;
1975 // Calculate the new stack slot for the return address.
1976 int SlotSize = Is64Bit ? 8 : 4;
1977 int NewReturnAddrFI =
1978 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1979 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1980 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1981 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1982 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1988 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1989 CallingConv::ID CallConv, bool isVarArg,
1991 const SmallVectorImpl<ISD::OutputArg> &Outs,
1992 const SmallVectorImpl<SDValue> &OutVals,
1993 const SmallVectorImpl<ISD::InputArg> &Ins,
1994 DebugLoc dl, SelectionDAG &DAG,
1995 SmallVectorImpl<SDValue> &InVals) const {
1996 MachineFunction &MF = DAG.getMachineFunction();
1997 bool Is64Bit = Subtarget->is64Bit();
1998 bool IsWin64 = Subtarget->isTargetWin64();
1999 bool IsStructRet = CallIsStructReturn(Outs);
2000 bool IsSibcall = false;
2003 // Check if it's really possible to do a tail call.
2004 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2005 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2006 Outs, OutVals, Ins, DAG);
2008 // Sibcalls are automatically detected tailcalls which do not require
2010 if (!GuaranteedTailCallOpt && isTailCall)
2017 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2018 "Var args not supported with calling convention fastcc or ghc");
2020 // Analyze operands of the call, assigning locations to each operand.
2021 SmallVector<CCValAssign, 16> ArgLocs;
2022 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2023 ArgLocs, *DAG.getContext());
2025 // Allocate shadow area for Win64
2027 CCInfo.AllocateStack(32, 8);
2030 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2032 // Get a count of how many bytes are to be pushed on the stack.
2033 unsigned NumBytes = CCInfo.getNextStackOffset();
2035 // This is a sibcall. The memory operands are available in caller's
2036 // own caller's stack.
2038 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2039 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2042 if (isTailCall && !IsSibcall) {
2043 // Lower arguments at fp - stackoffset + fpdiff.
2044 unsigned NumBytesCallerPushed =
2045 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2046 FPDiff = NumBytesCallerPushed - NumBytes;
2048 // Set the delta of movement of the returnaddr stackslot.
2049 // But only set if delta is greater than previous delta.
2050 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2051 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2055 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2057 SDValue RetAddrFrIdx;
2058 // Load return address for tail calls.
2059 if (isTailCall && FPDiff)
2060 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2061 Is64Bit, FPDiff, dl);
2063 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2064 SmallVector<SDValue, 8> MemOpChains;
2067 // Walk the register/memloc assignments, inserting copies/loads. In the case
2068 // of tail call optimization arguments are handle later.
2069 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2070 CCValAssign &VA = ArgLocs[i];
2071 EVT RegVT = VA.getLocVT();
2072 SDValue Arg = OutVals[i];
2073 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2074 bool isByVal = Flags.isByVal();
2076 // Promote the value if needed.
2077 switch (VA.getLocInfo()) {
2078 default: llvm_unreachable("Unknown loc info!");
2079 case CCValAssign::Full: break;
2080 case CCValAssign::SExt:
2081 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2083 case CCValAssign::ZExt:
2084 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2086 case CCValAssign::AExt:
2087 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2088 // Special case: passing MMX values in XMM registers.
2089 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2090 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2091 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2093 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2095 case CCValAssign::BCvt:
2096 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2098 case CCValAssign::Indirect: {
2099 // Store the argument.
2100 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2101 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2102 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2103 MachinePointerInfo::getFixedStack(FI),
2110 if (VA.isRegLoc()) {
2111 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2112 if (isVarArg && IsWin64) {
2113 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2114 // shadow reg if callee is a varargs function.
2115 unsigned ShadowReg = 0;
2116 switch (VA.getLocReg()) {
2117 case X86::XMM0: ShadowReg = X86::RCX; break;
2118 case X86::XMM1: ShadowReg = X86::RDX; break;
2119 case X86::XMM2: ShadowReg = X86::R8; break;
2120 case X86::XMM3: ShadowReg = X86::R9; break;
2123 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2125 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2126 assert(VA.isMemLoc());
2127 if (StackPtr.getNode() == 0)
2128 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2129 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2130 dl, DAG, VA, Flags));
2134 if (!MemOpChains.empty())
2135 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2136 &MemOpChains[0], MemOpChains.size());
2138 // Build a sequence of copy-to-reg nodes chained together with token chain
2139 // and flag operands which copy the outgoing args into registers.
2141 // Tail call byval lowering might overwrite argument registers so in case of
2142 // tail call optimization the copies to registers are lowered later.
2144 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2145 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2146 RegsToPass[i].second, InFlag);
2147 InFlag = Chain.getValue(1);
2150 if (Subtarget->isPICStyleGOT()) {
2151 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2154 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2155 DAG.getNode(X86ISD::GlobalBaseReg,
2156 DebugLoc(), getPointerTy()),
2158 InFlag = Chain.getValue(1);
2160 // If we are tail calling and generating PIC/GOT style code load the
2161 // address of the callee into ECX. The value in ecx is used as target of
2162 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2163 // for tail calls on PIC/GOT architectures. Normally we would just put the
2164 // address of GOT into ebx and then call target@PLT. But for tail calls
2165 // ebx would be restored (since ebx is callee saved) before jumping to the
2168 // Note: The actual moving to ECX is done further down.
2169 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2170 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2171 !G->getGlobal()->hasProtectedVisibility())
2172 Callee = LowerGlobalAddress(Callee, DAG);
2173 else if (isa<ExternalSymbolSDNode>(Callee))
2174 Callee = LowerExternalSymbol(Callee, DAG);
2178 if (Is64Bit && isVarArg && !IsWin64) {
2179 // From AMD64 ABI document:
2180 // For calls that may call functions that use varargs or stdargs
2181 // (prototype-less calls or calls to functions containing ellipsis (...) in
2182 // the declaration) %al is used as hidden argument to specify the number
2183 // of SSE registers used. The contents of %al do not need to match exactly
2184 // the number of registers, but must be an ubound on the number of SSE
2185 // registers used and is in the range 0 - 8 inclusive.
2187 // Count the number of XMM registers allocated.
2188 static const unsigned XMMArgRegs[] = {
2189 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2190 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2192 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2193 assert((Subtarget->hasXMM() || !NumXMMRegs)
2194 && "SSE registers cannot be used when SSE is disabled");
2196 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2197 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2198 InFlag = Chain.getValue(1);
2202 // For tail calls lower the arguments to the 'real' stack slot.
2204 // Force all the incoming stack arguments to be loaded from the stack
2205 // before any new outgoing arguments are stored to the stack, because the
2206 // outgoing stack slots may alias the incoming argument stack slots, and
2207 // the alias isn't otherwise explicit. This is slightly more conservative
2208 // than necessary, because it means that each store effectively depends
2209 // on every argument instead of just those arguments it would clobber.
2210 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2212 SmallVector<SDValue, 8> MemOpChains2;
2215 // Do not flag preceding copytoreg stuff together with the following stuff.
2217 if (GuaranteedTailCallOpt) {
2218 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2219 CCValAssign &VA = ArgLocs[i];
2222 assert(VA.isMemLoc());
2223 SDValue Arg = OutVals[i];
2224 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2225 // Create frame index.
2226 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2227 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2228 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2229 FIN = DAG.getFrameIndex(FI, getPointerTy());
2231 if (Flags.isByVal()) {
2232 // Copy relative to framepointer.
2233 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2234 if (StackPtr.getNode() == 0)
2235 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2237 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2239 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2243 // Store relative to framepointer.
2244 MemOpChains2.push_back(
2245 DAG.getStore(ArgChain, dl, Arg, FIN,
2246 MachinePointerInfo::getFixedStack(FI),
2252 if (!MemOpChains2.empty())
2253 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2254 &MemOpChains2[0], MemOpChains2.size());
2256 // Copy arguments to their registers.
2257 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2258 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2259 RegsToPass[i].second, InFlag);
2260 InFlag = Chain.getValue(1);
2264 // Store the return address to the appropriate stack slot.
2265 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2269 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2270 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2271 // In the 64-bit large code model, we have to make all calls
2272 // through a register, since the call instruction's 32-bit
2273 // pc-relative offset may not be large enough to hold the whole
2275 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2276 // If the callee is a GlobalAddress node (quite common, every direct call
2277 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2280 // We should use extra load for direct calls to dllimported functions in
2282 const GlobalValue *GV = G->getGlobal();
2283 if (!GV->hasDLLImportLinkage()) {
2284 unsigned char OpFlags = 0;
2285 bool ExtraLoad = false;
2286 unsigned WrapperKind = ISD::DELETED_NODE;
2288 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2289 // external symbols most go through the PLT in PIC mode. If the symbol
2290 // has hidden or protected visibility, or if it is static or local, then
2291 // we don't need to use the PLT - we can directly call it.
2292 if (Subtarget->isTargetELF() &&
2293 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2294 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2295 OpFlags = X86II::MO_PLT;
2296 } else if (Subtarget->isPICStyleStubAny() &&
2297 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2298 (!Subtarget->getTargetTriple().isMacOSX() ||
2299 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2300 // PC-relative references to external symbols should go through $stub,
2301 // unless we're building with the leopard linker or later, which
2302 // automatically synthesizes these stubs.
2303 OpFlags = X86II::MO_DARWIN_STUB;
2304 } else if (Subtarget->isPICStyleRIPRel() &&
2305 isa<Function>(GV) &&
2306 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2307 // If the function is marked as non-lazy, generate an indirect call
2308 // which loads from the GOT directly. This avoids runtime overhead
2309 // at the cost of eager binding (and one extra byte of encoding).
2310 OpFlags = X86II::MO_GOTPCREL;
2311 WrapperKind = X86ISD::WrapperRIP;
2315 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2316 G->getOffset(), OpFlags);
2318 // Add a wrapper if needed.
2319 if (WrapperKind != ISD::DELETED_NODE)
2320 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2321 // Add extra indirection if needed.
2323 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2324 MachinePointerInfo::getGOT(),
2327 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2328 unsigned char OpFlags = 0;
2330 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2331 // external symbols should go through the PLT.
2332 if (Subtarget->isTargetELF() &&
2333 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2334 OpFlags = X86II::MO_PLT;
2335 } else if (Subtarget->isPICStyleStubAny() &&
2336 (!Subtarget->getTargetTriple().isMacOSX() ||
2337 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2338 // PC-relative references to external symbols should go through $stub,
2339 // unless we're building with the leopard linker or later, which
2340 // automatically synthesizes these stubs.
2341 OpFlags = X86II::MO_DARWIN_STUB;
2344 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2348 // Returns a chain & a flag for retval copy to use.
2349 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2350 SmallVector<SDValue, 8> Ops;
2352 if (!IsSibcall && isTailCall) {
2353 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2354 DAG.getIntPtrConstant(0, true), InFlag);
2355 InFlag = Chain.getValue(1);
2358 Ops.push_back(Chain);
2359 Ops.push_back(Callee);
2362 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2364 // Add argument registers to the end of the list so that they are known live
2366 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2367 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2368 RegsToPass[i].second.getValueType()));
2370 // Add an implicit use GOT pointer in EBX.
2371 if (!isTailCall && Subtarget->isPICStyleGOT())
2372 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2374 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2375 if (Is64Bit && isVarArg && !IsWin64)
2376 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2378 if (InFlag.getNode())
2379 Ops.push_back(InFlag);
2383 //// If this is the first return lowered for this function, add the regs
2384 //// to the liveout set for the function.
2385 // This isn't right, although it's probably harmless on x86; liveouts
2386 // should be computed from returns not tail calls. Consider a void
2387 // function making a tail call to a function returning int.
2388 return DAG.getNode(X86ISD::TC_RETURN, dl,
2389 NodeTys, &Ops[0], Ops.size());
2392 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2393 InFlag = Chain.getValue(1);
2395 // Create the CALLSEQ_END node.
2396 unsigned NumBytesForCalleeToPush;
2397 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2398 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2399 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2400 // If this is a call to a struct-return function, the callee
2401 // pops the hidden struct pointer, so we have to push it back.
2402 // This is common for Darwin/X86, Linux & Mingw32 targets.
2403 NumBytesForCalleeToPush = 4;
2405 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2407 // Returns a flag for retval copy to use.
2409 Chain = DAG.getCALLSEQ_END(Chain,
2410 DAG.getIntPtrConstant(NumBytes, true),
2411 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2414 InFlag = Chain.getValue(1);
2417 // Handle result values, copying them out of physregs into vregs that we
2419 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2420 Ins, dl, DAG, InVals);
2424 //===----------------------------------------------------------------------===//
2425 // Fast Calling Convention (tail call) implementation
2426 //===----------------------------------------------------------------------===//
2428 // Like std call, callee cleans arguments, convention except that ECX is
2429 // reserved for storing the tail called function address. Only 2 registers are
2430 // free for argument passing (inreg). Tail call optimization is performed
2432 // * tailcallopt is enabled
2433 // * caller/callee are fastcc
2434 // On X86_64 architecture with GOT-style position independent code only local
2435 // (within module) calls are supported at the moment.
2436 // To keep the stack aligned according to platform abi the function
2437 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2438 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2439 // If a tail called function callee has more arguments than the caller the
2440 // caller needs to make sure that there is room to move the RETADDR to. This is
2441 // achieved by reserving an area the size of the argument delta right after the
2442 // original REtADDR, but before the saved framepointer or the spilled registers
2443 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2455 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2456 /// for a 16 byte align requirement.
2458 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2459 SelectionDAG& DAG) const {
2460 MachineFunction &MF = DAG.getMachineFunction();
2461 const TargetMachine &TM = MF.getTarget();
2462 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2463 unsigned StackAlignment = TFI.getStackAlignment();
2464 uint64_t AlignMask = StackAlignment - 1;
2465 int64_t Offset = StackSize;
2466 uint64_t SlotSize = TD->getPointerSize();
2467 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2468 // Number smaller than 12 so just add the difference.
2469 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2471 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2472 Offset = ((~AlignMask) & Offset) + StackAlignment +
2473 (StackAlignment-SlotSize);
2478 /// MatchingStackOffset - Return true if the given stack call argument is
2479 /// already available in the same position (relatively) of the caller's
2480 /// incoming argument stack.
2482 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2483 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2484 const X86InstrInfo *TII) {
2485 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2487 if (Arg.getOpcode() == ISD::CopyFromReg) {
2488 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2489 if (!TargetRegisterInfo::isVirtualRegister(VR))
2491 MachineInstr *Def = MRI->getVRegDef(VR);
2494 if (!Flags.isByVal()) {
2495 if (!TII->isLoadFromStackSlot(Def, FI))
2498 unsigned Opcode = Def->getOpcode();
2499 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2500 Def->getOperand(1).isFI()) {
2501 FI = Def->getOperand(1).getIndex();
2502 Bytes = Flags.getByValSize();
2506 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2507 if (Flags.isByVal())
2508 // ByVal argument is passed in as a pointer but it's now being
2509 // dereferenced. e.g.
2510 // define @foo(%struct.X* %A) {
2511 // tail call @bar(%struct.X* byval %A)
2514 SDValue Ptr = Ld->getBasePtr();
2515 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2518 FI = FINode->getIndex();
2519 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2520 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2521 FI = FINode->getIndex();
2522 Bytes = Flags.getByValSize();
2526 assert(FI != INT_MAX);
2527 if (!MFI->isFixedObjectIndex(FI))
2529 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2532 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2533 /// for tail call optimization. Targets which want to do tail call
2534 /// optimization should implement this function.
2536 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2537 CallingConv::ID CalleeCC,
2539 bool isCalleeStructRet,
2540 bool isCallerStructRet,
2541 const SmallVectorImpl<ISD::OutputArg> &Outs,
2542 const SmallVectorImpl<SDValue> &OutVals,
2543 const SmallVectorImpl<ISD::InputArg> &Ins,
2544 SelectionDAG& DAG) const {
2545 if (!IsTailCallConvention(CalleeCC) &&
2546 CalleeCC != CallingConv::C)
2549 // If -tailcallopt is specified, make fastcc functions tail-callable.
2550 const MachineFunction &MF = DAG.getMachineFunction();
2551 const Function *CallerF = DAG.getMachineFunction().getFunction();
2552 CallingConv::ID CallerCC = CallerF->getCallingConv();
2553 bool CCMatch = CallerCC == CalleeCC;
2555 if (GuaranteedTailCallOpt) {
2556 if (IsTailCallConvention(CalleeCC) && CCMatch)
2561 // Look for obvious safe cases to perform tail call optimization that do not
2562 // require ABI changes. This is what gcc calls sibcall.
2564 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2565 // emit a special epilogue.
2566 if (RegInfo->needsStackRealignment(MF))
2569 // Also avoid sibcall optimization if either caller or callee uses struct
2570 // return semantics.
2571 if (isCalleeStructRet || isCallerStructRet)
2574 // An stdcall caller is expected to clean up its arguments; the callee
2575 // isn't going to do that.
2576 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2579 // Do not sibcall optimize vararg calls unless all arguments are passed via
2581 if (isVarArg && !Outs.empty()) {
2583 // Optimizing for varargs on Win64 is unlikely to be safe without
2584 // additional testing.
2585 if (Subtarget->isTargetWin64())
2588 SmallVector<CCValAssign, 16> ArgLocs;
2589 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2590 getTargetMachine(), ArgLocs, *DAG.getContext());
2592 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2593 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2594 if (!ArgLocs[i].isRegLoc())
2598 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2599 // Therefore if it's not used by the call it is not safe to optimize this into
2601 bool Unused = false;
2602 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2609 SmallVector<CCValAssign, 16> RVLocs;
2610 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2611 getTargetMachine(), RVLocs, *DAG.getContext());
2612 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2613 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2614 CCValAssign &VA = RVLocs[i];
2615 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2620 // If the calling conventions do not match, then we'd better make sure the
2621 // results are returned in the same way as what the caller expects.
2623 SmallVector<CCValAssign, 16> RVLocs1;
2624 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2625 getTargetMachine(), RVLocs1, *DAG.getContext());
2626 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2628 SmallVector<CCValAssign, 16> RVLocs2;
2629 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2630 getTargetMachine(), RVLocs2, *DAG.getContext());
2631 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2633 if (RVLocs1.size() != RVLocs2.size())
2635 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2636 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2638 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2640 if (RVLocs1[i].isRegLoc()) {
2641 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2644 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2650 // If the callee takes no arguments then go on to check the results of the
2652 if (!Outs.empty()) {
2653 // Check if stack adjustment is needed. For now, do not do this if any
2654 // argument is passed on the stack.
2655 SmallVector<CCValAssign, 16> ArgLocs;
2656 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2657 getTargetMachine(), ArgLocs, *DAG.getContext());
2659 // Allocate shadow area for Win64
2660 if (Subtarget->isTargetWin64()) {
2661 CCInfo.AllocateStack(32, 8);
2664 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2665 if (CCInfo.getNextStackOffset()) {
2666 MachineFunction &MF = DAG.getMachineFunction();
2667 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2670 // Check if the arguments are already laid out in the right way as
2671 // the caller's fixed stack objects.
2672 MachineFrameInfo *MFI = MF.getFrameInfo();
2673 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2674 const X86InstrInfo *TII =
2675 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2676 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2677 CCValAssign &VA = ArgLocs[i];
2678 SDValue Arg = OutVals[i];
2679 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2680 if (VA.getLocInfo() == CCValAssign::Indirect)
2682 if (!VA.isRegLoc()) {
2683 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2690 // If the tailcall address may be in a register, then make sure it's
2691 // possible to register allocate for it. In 32-bit, the call address can
2692 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2693 // callee-saved registers are restored. These happen to be the same
2694 // registers used to pass 'inreg' arguments so watch out for those.
2695 if (!Subtarget->is64Bit() &&
2696 !isa<GlobalAddressSDNode>(Callee) &&
2697 !isa<ExternalSymbolSDNode>(Callee)) {
2698 unsigned NumInRegs = 0;
2699 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2700 CCValAssign &VA = ArgLocs[i];
2703 unsigned Reg = VA.getLocReg();
2706 case X86::EAX: case X86::EDX: case X86::ECX:
2707 if (++NumInRegs == 3)
2719 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2720 return X86::createFastISel(funcInfo);
2724 //===----------------------------------------------------------------------===//
2725 // Other Lowering Hooks
2726 //===----------------------------------------------------------------------===//
2728 static bool MayFoldLoad(SDValue Op) {
2729 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2732 static bool MayFoldIntoStore(SDValue Op) {
2733 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2736 static bool isTargetShuffle(unsigned Opcode) {
2738 default: return false;
2739 case X86ISD::PSHUFD:
2740 case X86ISD::PSHUFHW:
2741 case X86ISD::PSHUFLW:
2742 case X86ISD::SHUFPD:
2743 case X86ISD::PALIGN:
2744 case X86ISD::SHUFPS:
2745 case X86ISD::MOVLHPS:
2746 case X86ISD::MOVLHPD:
2747 case X86ISD::MOVHLPS:
2748 case X86ISD::MOVLPS:
2749 case X86ISD::MOVLPD:
2750 case X86ISD::MOVSHDUP:
2751 case X86ISD::MOVSLDUP:
2752 case X86ISD::MOVDDUP:
2755 case X86ISD::UNPCKLPS:
2756 case X86ISD::UNPCKLPD:
2757 case X86ISD::VUNPCKLPSY:
2758 case X86ISD::VUNPCKLPDY:
2759 case X86ISD::PUNPCKLWD:
2760 case X86ISD::PUNPCKLBW:
2761 case X86ISD::PUNPCKLDQ:
2762 case X86ISD::PUNPCKLQDQ:
2763 case X86ISD::UNPCKHPS:
2764 case X86ISD::UNPCKHPD:
2765 case X86ISD::VUNPCKHPSY:
2766 case X86ISD::VUNPCKHPDY:
2767 case X86ISD::PUNPCKHWD:
2768 case X86ISD::PUNPCKHBW:
2769 case X86ISD::PUNPCKHDQ:
2770 case X86ISD::PUNPCKHQDQ:
2771 case X86ISD::VPERMILPS:
2772 case X86ISD::VPERMILPSY:
2773 case X86ISD::VPERMILPD:
2774 case X86ISD::VPERMILPDY:
2775 case X86ISD::VPERM2F128:
2781 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2782 SDValue V1, SelectionDAG &DAG) {
2784 default: llvm_unreachable("Unknown x86 shuffle node");
2785 case X86ISD::MOVSHDUP:
2786 case X86ISD::MOVSLDUP:
2787 case X86ISD::MOVDDUP:
2788 return DAG.getNode(Opc, dl, VT, V1);
2794 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2795 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2797 default: llvm_unreachable("Unknown x86 shuffle node");
2798 case X86ISD::PSHUFD:
2799 case X86ISD::PSHUFHW:
2800 case X86ISD::PSHUFLW:
2801 case X86ISD::VPERMILPS:
2802 case X86ISD::VPERMILPSY:
2803 case X86ISD::VPERMILPD:
2804 case X86ISD::VPERMILPDY:
2805 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2811 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2812 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2814 default: llvm_unreachable("Unknown x86 shuffle node");
2815 case X86ISD::PALIGN:
2816 case X86ISD::SHUFPD:
2817 case X86ISD::SHUFPS:
2818 case X86ISD::VPERM2F128:
2819 return DAG.getNode(Opc, dl, VT, V1, V2,
2820 DAG.getConstant(TargetMask, MVT::i8));
2825 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2826 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2828 default: llvm_unreachable("Unknown x86 shuffle node");
2829 case X86ISD::MOVLHPS:
2830 case X86ISD::MOVLHPD:
2831 case X86ISD::MOVHLPS:
2832 case X86ISD::MOVLPS:
2833 case X86ISD::MOVLPD:
2836 case X86ISD::UNPCKLPS:
2837 case X86ISD::UNPCKLPD:
2838 case X86ISD::VUNPCKLPSY:
2839 case X86ISD::VUNPCKLPDY:
2840 case X86ISD::PUNPCKLWD:
2841 case X86ISD::PUNPCKLBW:
2842 case X86ISD::PUNPCKLDQ:
2843 case X86ISD::PUNPCKLQDQ:
2844 case X86ISD::UNPCKHPS:
2845 case X86ISD::UNPCKHPD:
2846 case X86ISD::VUNPCKHPSY:
2847 case X86ISD::VUNPCKHPDY:
2848 case X86ISD::PUNPCKHWD:
2849 case X86ISD::PUNPCKHBW:
2850 case X86ISD::PUNPCKHDQ:
2851 case X86ISD::PUNPCKHQDQ:
2852 return DAG.getNode(Opc, dl, VT, V1, V2);
2857 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2858 MachineFunction &MF = DAG.getMachineFunction();
2859 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2860 int ReturnAddrIndex = FuncInfo->getRAIndex();
2862 if (ReturnAddrIndex == 0) {
2863 // Set up a frame object for the return address.
2864 uint64_t SlotSize = TD->getPointerSize();
2865 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2867 FuncInfo->setRAIndex(ReturnAddrIndex);
2870 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2874 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2875 bool hasSymbolicDisplacement) {
2876 // Offset should fit into 32 bit immediate field.
2877 if (!isInt<32>(Offset))
2880 // If we don't have a symbolic displacement - we don't have any extra
2882 if (!hasSymbolicDisplacement)
2885 // FIXME: Some tweaks might be needed for medium code model.
2886 if (M != CodeModel::Small && M != CodeModel::Kernel)
2889 // For small code model we assume that latest object is 16MB before end of 31
2890 // bits boundary. We may also accept pretty large negative constants knowing
2891 // that all objects are in the positive half of address space.
2892 if (M == CodeModel::Small && Offset < 16*1024*1024)
2895 // For kernel code model we know that all object resist in the negative half
2896 // of 32bits address space. We may not accept negative offsets, since they may
2897 // be just off and we may accept pretty large positive ones.
2898 if (M == CodeModel::Kernel && Offset > 0)
2904 /// isCalleePop - Determines whether the callee is required to pop its
2905 /// own arguments. Callee pop is necessary to support tail calls.
2906 bool X86::isCalleePop(CallingConv::ID CallingConv,
2907 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2911 switch (CallingConv) {
2914 case CallingConv::X86_StdCall:
2916 case CallingConv::X86_FastCall:
2918 case CallingConv::X86_ThisCall:
2920 case CallingConv::Fast:
2922 case CallingConv::GHC:
2927 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2928 /// specific condition code, returning the condition code and the LHS/RHS of the
2929 /// comparison to make.
2930 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2931 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2933 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2934 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2935 // X > -1 -> X == 0, jump !sign.
2936 RHS = DAG.getConstant(0, RHS.getValueType());
2937 return X86::COND_NS;
2938 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2939 // X < 0 -> X == 0, jump on sign.
2941 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2943 RHS = DAG.getConstant(0, RHS.getValueType());
2944 return X86::COND_LE;
2948 switch (SetCCOpcode) {
2949 default: llvm_unreachable("Invalid integer condition!");
2950 case ISD::SETEQ: return X86::COND_E;
2951 case ISD::SETGT: return X86::COND_G;
2952 case ISD::SETGE: return X86::COND_GE;
2953 case ISD::SETLT: return X86::COND_L;
2954 case ISD::SETLE: return X86::COND_LE;
2955 case ISD::SETNE: return X86::COND_NE;
2956 case ISD::SETULT: return X86::COND_B;
2957 case ISD::SETUGT: return X86::COND_A;
2958 case ISD::SETULE: return X86::COND_BE;
2959 case ISD::SETUGE: return X86::COND_AE;
2963 // First determine if it is required or is profitable to flip the operands.
2965 // If LHS is a foldable load, but RHS is not, flip the condition.
2966 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2967 !ISD::isNON_EXTLoad(RHS.getNode())) {
2968 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2969 std::swap(LHS, RHS);
2972 switch (SetCCOpcode) {
2978 std::swap(LHS, RHS);
2982 // On a floating point condition, the flags are set as follows:
2984 // 0 | 0 | 0 | X > Y
2985 // 0 | 0 | 1 | X < Y
2986 // 1 | 0 | 0 | X == Y
2987 // 1 | 1 | 1 | unordered
2988 switch (SetCCOpcode) {
2989 default: llvm_unreachable("Condcode should be pre-legalized away");
2991 case ISD::SETEQ: return X86::COND_E;
2992 case ISD::SETOLT: // flipped
2994 case ISD::SETGT: return X86::COND_A;
2995 case ISD::SETOLE: // flipped
2997 case ISD::SETGE: return X86::COND_AE;
2998 case ISD::SETUGT: // flipped
3000 case ISD::SETLT: return X86::COND_B;
3001 case ISD::SETUGE: // flipped
3003 case ISD::SETLE: return X86::COND_BE;
3005 case ISD::SETNE: return X86::COND_NE;
3006 case ISD::SETUO: return X86::COND_P;
3007 case ISD::SETO: return X86::COND_NP;
3009 case ISD::SETUNE: return X86::COND_INVALID;
3013 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3014 /// code. Current x86 isa includes the following FP cmov instructions:
3015 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3016 static bool hasFPCMov(unsigned X86CC) {
3032 /// isFPImmLegal - Returns true if the target can instruction select the
3033 /// specified FP immediate natively. If false, the legalizer will
3034 /// materialize the FP immediate as a load from a constant pool.
3035 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3036 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3037 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3043 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3044 /// the specified range (L, H].
3045 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3046 return (Val < 0) || (Val >= Low && Val < Hi);
3049 /// isUndefOrInRange - Return true if every element in Mask, begining
3050 /// from position Pos and ending in Pos+Size, falls within the specified
3051 /// range (L, L+Pos]. or is undef.
3052 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3053 int Pos, int Size, int Low, int Hi) {
3054 for (int i = Pos, e = Pos+Size; i != e; ++i)
3055 if (!isUndefOrInRange(Mask[i], Low, Hi))
3060 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3061 /// specified value.
3062 static bool isUndefOrEqual(int Val, int CmpVal) {
3063 if (Val < 0 || Val == CmpVal)
3068 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3069 /// from position Pos and ending in Pos+Size, falls within the specified
3070 /// sequential range (L, L+Pos]. or is undef.
3071 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3072 int Pos, int Size, int Low) {
3073 for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3074 if (!isUndefOrEqual(Mask[i], Low))
3079 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3080 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3081 /// the second operand.
3082 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3083 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3084 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3085 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3086 return (Mask[0] < 2 && Mask[1] < 2);
3090 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3091 SmallVector<int, 8> M;
3093 return ::isPSHUFDMask(M, N->getValueType(0));
3096 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3097 /// is suitable for input to PSHUFHW.
3098 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3099 if (VT != MVT::v8i16)
3102 // Lower quadword copied in order or undef.
3103 for (int i = 0; i != 4; ++i)
3104 if (Mask[i] >= 0 && Mask[i] != i)
3107 // Upper quadword shuffled.
3108 for (int i = 4; i != 8; ++i)
3109 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3115 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3116 SmallVector<int, 8> M;
3118 return ::isPSHUFHWMask(M, N->getValueType(0));
3121 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3122 /// is suitable for input to PSHUFLW.
3123 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3124 if (VT != MVT::v8i16)
3127 // Upper quadword copied in order.
3128 for (int i = 4; i != 8; ++i)
3129 if (Mask[i] >= 0 && Mask[i] != i)
3132 // Lower quadword shuffled.
3133 for (int i = 0; i != 4; ++i)
3140 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3141 SmallVector<int, 8> M;
3143 return ::isPSHUFLWMask(M, N->getValueType(0));
3146 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3147 /// is suitable for input to PALIGNR.
3148 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3150 int i, e = VT.getVectorNumElements();
3151 if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3154 // Do not handle v2i64 / v2f64 shuffles with palignr.
3155 if (e < 4 || !hasSSSE3)
3158 for (i = 0; i != e; ++i)
3162 // All undef, not a palignr.
3166 // Make sure we're shifting in the right direction.
3170 int s = Mask[i] - i;
3172 // Check the rest of the elements to see if they are consecutive.
3173 for (++i; i != e; ++i) {
3175 if (m >= 0 && m != s+i)
3181 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3182 /// specifies a shuffle of elements that is suitable for input to 128-bit
3183 /// SHUFPS and SHUFPD.
3184 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3185 int NumElems = VT.getVectorNumElements();
3187 if (VT.getSizeInBits() != 128)
3190 if (NumElems != 2 && NumElems != 4)
3193 int Half = NumElems / 2;
3194 for (int i = 0; i < Half; ++i)
3195 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3197 for (int i = Half; i < NumElems; ++i)
3198 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3204 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3205 SmallVector<int, 8> M;
3207 return ::isSHUFPMask(M, N->getValueType(0));
3210 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3211 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3212 /// half elements to come from vector 1 (which would equal the dest.) and
3213 /// the upper half to come from vector 2.
3214 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3215 int NumElems = VT.getVectorNumElements();
3217 if (NumElems != 2 && NumElems != 4)
3220 int Half = NumElems / 2;
3221 for (int i = 0; i < Half; ++i)
3222 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3224 for (int i = Half; i < NumElems; ++i)
3225 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3230 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3231 SmallVector<int, 8> M;
3233 return isCommutedSHUFPMask(M, N->getValueType(0));
3236 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3237 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3238 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3239 EVT VT = N->getValueType(0);
3240 unsigned NumElems = VT.getVectorNumElements();
3242 if (VT.getSizeInBits() != 128)
3248 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3249 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3250 isUndefOrEqual(N->getMaskElt(1), 7) &&
3251 isUndefOrEqual(N->getMaskElt(2), 2) &&
3252 isUndefOrEqual(N->getMaskElt(3), 3);
3255 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3256 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3258 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3259 EVT VT = N->getValueType(0);
3260 unsigned NumElems = VT.getVectorNumElements();
3262 if (VT.getSizeInBits() != 128)
3268 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3269 isUndefOrEqual(N->getMaskElt(1), 3) &&
3270 isUndefOrEqual(N->getMaskElt(2), 2) &&
3271 isUndefOrEqual(N->getMaskElt(3), 3);
3274 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3275 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3276 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3277 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3279 if (NumElems != 2 && NumElems != 4)
3282 for (unsigned i = 0; i < NumElems/2; ++i)
3283 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3286 for (unsigned i = NumElems/2; i < NumElems; ++i)
3287 if (!isUndefOrEqual(N->getMaskElt(i), i))
3293 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3294 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3295 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3296 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3298 if ((NumElems != 2 && NumElems != 4)
3299 || N->getValueType(0).getSizeInBits() > 128)
3302 for (unsigned i = 0; i < NumElems/2; ++i)
3303 if (!isUndefOrEqual(N->getMaskElt(i), i))
3306 for (unsigned i = 0; i < NumElems/2; ++i)
3307 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3313 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3314 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3315 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3316 bool V2IsSplat = false) {
3317 int NumElts = VT.getVectorNumElements();
3319 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3320 "Unsupported vector type for unpckh");
3322 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3325 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3326 // independently on 128-bit lanes.
3327 unsigned NumLanes = VT.getSizeInBits()/128;
3328 unsigned NumLaneElts = NumElts/NumLanes;
3331 unsigned End = NumLaneElts;
3332 for (unsigned s = 0; s < NumLanes; ++s) {
3333 for (unsigned i = Start, j = s * NumLaneElts;
3337 int BitI1 = Mask[i+1];
3338 if (!isUndefOrEqual(BitI, j))
3341 if (!isUndefOrEqual(BitI1, NumElts))
3344 if (!isUndefOrEqual(BitI1, j + NumElts))
3348 // Process the next 128 bits.
3349 Start += NumLaneElts;
3356 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3357 SmallVector<int, 8> M;
3359 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3362 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3363 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3364 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3365 bool V2IsSplat = false) {
3366 int NumElts = VT.getVectorNumElements();
3368 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3369 "Unsupported vector type for unpckh");
3371 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3374 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3375 // independently on 128-bit lanes.
3376 unsigned NumLanes = VT.getSizeInBits()/128;
3377 unsigned NumLaneElts = NumElts/NumLanes;
3380 unsigned End = NumLaneElts;
3381 for (unsigned l = 0; l != NumLanes; ++l) {
3382 for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3383 i != End; i += 2, ++j) {
3385 int BitI1 = Mask[i+1];
3386 if (!isUndefOrEqual(BitI, j))
3389 if (isUndefOrEqual(BitI1, NumElts))
3392 if (!isUndefOrEqual(BitI1, j+NumElts))
3396 // Process the next 128 bits.
3397 Start += NumLaneElts;
3403 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3404 SmallVector<int, 8> M;
3406 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3409 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3410 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3412 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3413 int NumElems = VT.getVectorNumElements();
3414 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3417 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3418 // independently on 128-bit lanes.
3419 unsigned NumLanes = VT.getSizeInBits() / 128;
3420 unsigned NumLaneElts = NumElems / NumLanes;
3422 for (unsigned s = 0; s < NumLanes; ++s) {
3423 for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3424 i != NumLaneElts * (s + 1);
3427 int BitI1 = Mask[i+1];
3429 if (!isUndefOrEqual(BitI, j))
3431 if (!isUndefOrEqual(BitI1, j))
3439 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3440 SmallVector<int, 8> M;
3442 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3445 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3446 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3448 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3449 int NumElems = VT.getVectorNumElements();
3450 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3453 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3455 int BitI1 = Mask[i+1];
3456 if (!isUndefOrEqual(BitI, j))
3458 if (!isUndefOrEqual(BitI1, j))
3464 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3465 SmallVector<int, 8> M;
3467 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3470 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3471 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3472 /// MOVSD, and MOVD, i.e. setting the lowest element.
3473 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3474 if (VT.getVectorElementType().getSizeInBits() < 32)
3477 int NumElts = VT.getVectorNumElements();
3479 if (!isUndefOrEqual(Mask[0], NumElts))
3482 for (int i = 1; i < NumElts; ++i)
3483 if (!isUndefOrEqual(Mask[i], i))
3489 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3490 SmallVector<int, 8> M;
3492 return ::isMOVLMask(M, N->getValueType(0));
3495 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3496 /// as permutations between 128-bit chunks or halves. As an example: this
3498 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3499 /// The first half comes from the second half of V1 and the second half from the
3500 /// the second half of V2.
3501 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3502 const X86Subtarget *Subtarget) {
3503 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3506 // The shuffle result is divided into half A and half B. In total the two
3507 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3508 // B must come from C, D, E or F.
3509 int HalfSize = VT.getVectorNumElements()/2;
3510 bool MatchA = false, MatchB = false;
3512 // Check if A comes from one of C, D, E, F.
3513 for (int Half = 0; Half < 4; ++Half) {
3514 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3520 // Check if B comes from one of C, D, E, F.
3521 for (int Half = 0; Half < 4; ++Half) {
3522 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3528 return MatchA && MatchB;
3531 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3532 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3533 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3534 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3535 EVT VT = SVOp->getValueType(0);
3537 int HalfSize = VT.getVectorNumElements()/2;
3539 int FstHalf = 0, SndHalf = 0;
3540 for (int i = 0; i < HalfSize; ++i) {
3541 if (SVOp->getMaskElt(i) > 0) {
3542 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3546 for (int i = HalfSize; i < HalfSize*2; ++i) {
3547 if (SVOp->getMaskElt(i) > 0) {
3548 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3553 return (FstHalf | (SndHalf << 4));
3556 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3557 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3558 /// Note that VPERMIL mask matching is different depending whether theunderlying
3559 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3560 /// to the same elements of the low, but to the higher half of the source.
3561 /// In VPERMILPD the two lanes could be shuffled independently of each other
3562 /// with the same restriction that lanes can't be crossed.
3563 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3564 const X86Subtarget *Subtarget) {
3565 int NumElts = VT.getVectorNumElements();
3566 int NumLanes = VT.getSizeInBits()/128;
3568 if (!Subtarget->hasAVX())
3571 // Match any permutation of 128-bit vector with 64-bit types
3572 if (NumLanes == 1 && NumElts != 2)
3575 // Only match 256-bit with 32 types
3576 if (VT.getSizeInBits() == 256 && NumElts != 4)
3579 // The mask on the high lane is independent of the low. Both can match
3580 // any element in inside its own lane, but can't cross.
3581 int LaneSize = NumElts/NumLanes;
3582 for (int l = 0; l < NumLanes; ++l)
3583 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3584 int LaneStart = l*LaneSize;
3585 if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3592 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3593 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3594 /// Note that VPERMIL mask matching is different depending whether theunderlying
3595 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3596 /// to the same elements of the low, but to the higher half of the source.
3597 /// In VPERMILPD the two lanes could be shuffled independently of each other
3598 /// with the same restriction that lanes can't be crossed.
3599 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3600 const X86Subtarget *Subtarget) {
3601 unsigned NumElts = VT.getVectorNumElements();
3602 unsigned NumLanes = VT.getSizeInBits()/128;
3604 if (!Subtarget->hasAVX())
3607 // Match any permutation of 128-bit vector with 32-bit types
3608 if (NumLanes == 1 && NumElts != 4)
3611 // Only match 256-bit with 32 types
3612 if (VT.getSizeInBits() == 256 && NumElts != 8)
3615 // The mask on the high lane should be the same as the low. Actually,
3616 // they can differ if any of the corresponding index in a lane is undef
3617 // and the other stays in range.
3618 int LaneSize = NumElts/NumLanes;
3619 for (int i = 0; i < LaneSize; ++i) {
3620 int HighElt = i+LaneSize;
3621 bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3622 bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3624 if (!HighValid || !LowValid)
3626 if (Mask[i] < 0 || Mask[HighElt] < 0)
3628 if (Mask[HighElt]-Mask[i] != LaneSize)
3635 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3636 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3637 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3638 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3639 EVT VT = SVOp->getValueType(0);
3641 int NumElts = VT.getVectorNumElements();
3642 int NumLanes = VT.getSizeInBits()/128;
3643 int LaneSize = NumElts/NumLanes;
3645 // Although the mask is equal for both lanes do it twice to get the cases
3646 // where a mask will match because the same mask element is undef on the
3647 // first half but valid on the second. This would get pathological cases
3648 // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3650 for (int l = 0; l < NumLanes; ++l) {
3651 for (int i = 0; i < LaneSize; ++i) {
3652 int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3655 if (MaskElt >= LaneSize)
3656 MaskElt -= LaneSize;
3657 Mask |= MaskElt << (i*2);
3664 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3665 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3666 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3667 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3668 EVT VT = SVOp->getValueType(0);
3670 int NumElts = VT.getVectorNumElements();
3671 int NumLanes = VT.getSizeInBits()/128;
3674 int LaneSize = NumElts/NumLanes;
3675 for (int l = 0; l < NumLanes; ++l)
3676 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3677 int MaskElt = SVOp->getMaskElt(i);
3680 Mask |= (MaskElt-l*LaneSize) << i;
3686 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3687 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3688 /// element of vector 2 and the other elements to come from vector 1 in order.
3689 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3690 bool V2IsSplat = false, bool V2IsUndef = false) {
3691 int NumOps = VT.getVectorNumElements();
3692 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3695 if (!isUndefOrEqual(Mask[0], 0))
3698 for (int i = 1; i < NumOps; ++i)
3699 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3700 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3701 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3707 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3708 bool V2IsUndef = false) {
3709 SmallVector<int, 8> M;
3711 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3714 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3715 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3716 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3717 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3718 const X86Subtarget *Subtarget) {
3719 if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3722 // The second vector must be undef
3723 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3726 EVT VT = N->getValueType(0);
3727 unsigned NumElems = VT.getVectorNumElements();
3729 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3730 (VT.getSizeInBits() == 256 && NumElems != 8))
3733 // "i+1" is the value the indexed mask element must have
3734 for (unsigned i = 0; i < NumElems; i += 2)
3735 if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3736 !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3742 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3743 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3744 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3745 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3746 const X86Subtarget *Subtarget) {
3747 if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3750 // The second vector must be undef
3751 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3754 EVT VT = N->getValueType(0);
3755 unsigned NumElems = VT.getVectorNumElements();
3757 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3758 (VT.getSizeInBits() == 256 && NumElems != 8))
3761 // "i" is the value the indexed mask element must have
3762 for (unsigned i = 0; i < NumElems; i += 2)
3763 if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3764 !isUndefOrEqual(N->getMaskElt(i+1), i))
3770 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3771 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3772 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3773 int e = N->getValueType(0).getVectorNumElements() / 2;
3775 for (int i = 0; i < e; ++i)
3776 if (!isUndefOrEqual(N->getMaskElt(i), i))
3778 for (int i = 0; i < e; ++i)
3779 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3784 /// isVEXTRACTF128Index - Return true if the specified
3785 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3786 /// suitable for input to VEXTRACTF128.
3787 bool X86::isVEXTRACTF128Index(SDNode *N) {
3788 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3791 // The index should be aligned on a 128-bit boundary.
3793 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3795 unsigned VL = N->getValueType(0).getVectorNumElements();
3796 unsigned VBits = N->getValueType(0).getSizeInBits();
3797 unsigned ElSize = VBits / VL;
3798 bool Result = (Index * ElSize) % 128 == 0;
3803 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3804 /// operand specifies a subvector insert that is suitable for input to
3806 bool X86::isVINSERTF128Index(SDNode *N) {
3807 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3810 // The index should be aligned on a 128-bit boundary.
3812 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3814 unsigned VL = N->getValueType(0).getVectorNumElements();
3815 unsigned VBits = N->getValueType(0).getSizeInBits();
3816 unsigned ElSize = VBits / VL;
3817 bool Result = (Index * ElSize) % 128 == 0;
3822 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3823 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3824 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3825 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3826 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3828 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3830 for (int i = 0; i < NumOperands; ++i) {
3831 int Val = SVOp->getMaskElt(NumOperands-i-1);
3832 if (Val < 0) Val = 0;
3833 if (Val >= NumOperands) Val -= NumOperands;
3835 if (i != NumOperands - 1)
3841 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3842 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3843 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3844 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3846 // 8 nodes, but we only care about the last 4.
3847 for (unsigned i = 7; i >= 4; --i) {
3848 int Val = SVOp->getMaskElt(i);
3857 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3858 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3859 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3860 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3862 // 8 nodes, but we only care about the first 4.
3863 for (int i = 3; i >= 0; --i) {
3864 int Val = SVOp->getMaskElt(i);
3873 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3874 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3875 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3876 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3877 EVT VVT = N->getValueType(0);
3878 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3882 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3883 Val = SVOp->getMaskElt(i);
3887 assert(Val - i > 0 && "PALIGNR imm should be positive");
3888 return (Val - i) * EltSize;
3891 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3892 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3894 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3895 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3896 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3899 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3901 EVT VecVT = N->getOperand(0).getValueType();
3902 EVT ElVT = VecVT.getVectorElementType();
3904 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3905 return Index / NumElemsPerChunk;
3908 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3909 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3911 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3912 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3913 llvm_unreachable("Illegal insert subvector for VINSERTF128");
3916 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3918 EVT VecVT = N->getValueType(0);
3919 EVT ElVT = VecVT.getVectorElementType();
3921 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3922 return Index / NumElemsPerChunk;
3925 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3927 bool X86::isZeroNode(SDValue Elt) {
3928 return ((isa<ConstantSDNode>(Elt) &&
3929 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3930 (isa<ConstantFPSDNode>(Elt) &&
3931 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3934 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3935 /// their permute mask.
3936 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3937 SelectionDAG &DAG) {
3938 EVT VT = SVOp->getValueType(0);
3939 unsigned NumElems = VT.getVectorNumElements();
3940 SmallVector<int, 8> MaskVec;
3942 for (unsigned i = 0; i != NumElems; ++i) {
3943 int idx = SVOp->getMaskElt(i);
3945 MaskVec.push_back(idx);
3946 else if (idx < (int)NumElems)
3947 MaskVec.push_back(idx + NumElems);
3949 MaskVec.push_back(idx - NumElems);
3951 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3952 SVOp->getOperand(0), &MaskVec[0]);
3955 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3956 /// the two vector operands have swapped position.
3957 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3958 unsigned NumElems = VT.getVectorNumElements();
3959 for (unsigned i = 0; i != NumElems; ++i) {
3963 else if (idx < (int)NumElems)
3964 Mask[i] = idx + NumElems;
3966 Mask[i] = idx - NumElems;
3970 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3971 /// match movhlps. The lower half elements should come from upper half of
3972 /// V1 (and in order), and the upper half elements should come from the upper
3973 /// half of V2 (and in order).
3974 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3975 EVT VT = Op->getValueType(0);
3976 if (VT.getSizeInBits() != 128)
3978 if (VT.getVectorNumElements() != 4)
3980 for (unsigned i = 0, e = 2; i != e; ++i)
3981 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3983 for (unsigned i = 2; i != 4; ++i)
3984 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3989 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3990 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3992 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3993 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3995 N = N->getOperand(0).getNode();
3996 if (!ISD::isNON_EXTLoad(N))
3999 *LD = cast<LoadSDNode>(N);
4003 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4004 /// match movlp{s|d}. The lower half elements should come from lower half of
4005 /// V1 (and in order), and the upper half elements should come from the upper
4006 /// half of V2 (and in order). And since V1 will become the source of the
4007 /// MOVLP, it must be either a vector load or a scalar load to vector.
4008 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4009 ShuffleVectorSDNode *Op) {
4010 EVT VT = Op->getValueType(0);
4011 if (VT.getSizeInBits() != 128)
4014 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4016 // Is V2 is a vector load, don't do this transformation. We will try to use
4017 // load folding shufps op.
4018 if (ISD::isNON_EXTLoad(V2))
4021 unsigned NumElems = VT.getVectorNumElements();
4023 if (NumElems != 2 && NumElems != 4)
4025 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4026 if (!isUndefOrEqual(Op->getMaskElt(i), i))
4028 for (unsigned i = NumElems/2; i != NumElems; ++i)
4029 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4034 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4036 static bool isSplatVector(SDNode *N) {
4037 if (N->getOpcode() != ISD::BUILD_VECTOR)
4040 SDValue SplatValue = N->getOperand(0);
4041 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4042 if (N->getOperand(i) != SplatValue)
4047 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4048 /// to an zero vector.
4049 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4050 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4051 SDValue V1 = N->getOperand(0);
4052 SDValue V2 = N->getOperand(1);
4053 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4054 for (unsigned i = 0; i != NumElems; ++i) {
4055 int Idx = N->getMaskElt(i);
4056 if (Idx >= (int)NumElems) {
4057 unsigned Opc = V2.getOpcode();
4058 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4060 if (Opc != ISD::BUILD_VECTOR ||
4061 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4063 } else if (Idx >= 0) {
4064 unsigned Opc = V1.getOpcode();
4065 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4067 if (Opc != ISD::BUILD_VECTOR ||
4068 !X86::isZeroNode(V1.getOperand(Idx)))
4075 /// getZeroVector - Returns a vector of specified type with all zero elements.
4077 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
4079 assert(VT.isVector() && "Expected a vector type");
4081 // Always build SSE zero vectors as <4 x i32> bitcasted
4082 // to their dest type. This ensures they get CSE'd.
4084 if (VT.getSizeInBits() == 128) { // SSE
4085 if (HasSSE2) { // SSE2
4086 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4087 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4089 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4090 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4092 } else if (VT.getSizeInBits() == 256) { // AVX
4093 // 256-bit logic and arithmetic instructions in AVX are
4094 // all floating-point, no support for integer ops. Default
4095 // to emitting fp zeroed vectors then.
4096 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4097 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4098 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4100 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4103 /// getOnesVector - Returns a vector of specified type with all bits set.
4104 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4105 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4106 /// original type, ensuring they get CSE'd.
4107 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4108 assert(VT.isVector() && "Expected a vector type");
4109 assert((VT.is128BitVector() || VT.is256BitVector())
4110 && "Expected a 128-bit or 256-bit vector type");
4112 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4113 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4114 Cst, Cst, Cst, Cst);
4116 if (VT.is256BitVector()) {
4117 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4118 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4119 Vec = Insert128BitVector(InsV, Vec,
4120 DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4123 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4126 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4127 /// that point to V2 points to its first element.
4128 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4129 EVT VT = SVOp->getValueType(0);
4130 unsigned NumElems = VT.getVectorNumElements();
4132 bool Changed = false;
4133 SmallVector<int, 8> MaskVec;
4134 SVOp->getMask(MaskVec);
4136 for (unsigned i = 0; i != NumElems; ++i) {
4137 if (MaskVec[i] > (int)NumElems) {
4138 MaskVec[i] = NumElems;
4143 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4144 SVOp->getOperand(1), &MaskVec[0]);
4145 return SDValue(SVOp, 0);
4148 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4149 /// operation of specified width.
4150 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4152 unsigned NumElems = VT.getVectorNumElements();
4153 SmallVector<int, 8> Mask;
4154 Mask.push_back(NumElems);
4155 for (unsigned i = 1; i != NumElems; ++i)
4157 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4160 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4161 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4163 unsigned NumElems = VT.getVectorNumElements();
4164 SmallVector<int, 8> Mask;
4165 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4167 Mask.push_back(i + NumElems);
4169 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4172 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4173 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4175 unsigned NumElems = VT.getVectorNumElements();
4176 unsigned Half = NumElems/2;
4177 SmallVector<int, 8> Mask;
4178 for (unsigned i = 0; i != Half; ++i) {
4179 Mask.push_back(i + Half);
4180 Mask.push_back(i + NumElems + Half);
4182 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4185 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4186 // a generic shuffle instruction because the target has no such instructions.
4187 // Generate shuffles which repeat i16 and i8 several times until they can be
4188 // represented by v4f32 and then be manipulated by target suported shuffles.
4189 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4190 EVT VT = V.getValueType();
4191 int NumElems = VT.getVectorNumElements();
4192 DebugLoc dl = V.getDebugLoc();
4194 while (NumElems > 4) {
4195 if (EltNo < NumElems/2) {
4196 V = getUnpackl(DAG, dl, VT, V, V);
4198 V = getUnpackh(DAG, dl, VT, V, V);
4199 EltNo -= NumElems/2;
4206 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4207 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4208 EVT VT = V.getValueType();
4209 DebugLoc dl = V.getDebugLoc();
4210 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4211 && "Vector size not supported");
4213 if (VT.getSizeInBits() == 128) {
4214 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4215 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4216 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4219 // To use VPERMILPS to splat scalars, the second half of indicies must
4220 // refer to the higher part, which is a duplication of the lower one,
4221 // because VPERMILPS can only handle in-lane permutations.
4222 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4223 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4225 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4226 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4230 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4233 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4234 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4235 EVT SrcVT = SV->getValueType(0);
4236 SDValue V1 = SV->getOperand(0);
4237 DebugLoc dl = SV->getDebugLoc();
4239 int EltNo = SV->getSplatIndex();
4240 int NumElems = SrcVT.getVectorNumElements();
4241 unsigned Size = SrcVT.getSizeInBits();
4243 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4244 "Unknown how to promote splat for type");
4246 // Extract the 128-bit part containing the splat element and update
4247 // the splat element index when it refers to the higher register.
4249 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4250 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4252 EltNo -= NumElems/2;
4255 // All i16 and i8 vector types can't be used directly by a generic shuffle
4256 // instruction because the target has no such instruction. Generate shuffles
4257 // which repeat i16 and i8 several times until they fit in i32, and then can
4258 // be manipulated by target suported shuffles.
4259 EVT EltVT = SrcVT.getVectorElementType();
4260 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4261 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4263 // Recreate the 256-bit vector and place the same 128-bit vector
4264 // into the low and high part. This is necessary because we want
4265 // to use VPERM* to shuffle the vectors
4267 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4268 DAG.getConstant(0, MVT::i32), DAG, dl);
4269 V1 = Insert128BitVector(InsV, V1,
4270 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4273 return getLegalSplat(DAG, V1, EltNo);
4276 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4277 /// vector of zero or undef vector. This produces a shuffle where the low
4278 /// element of V2 is swizzled into the zero/undef vector, landing at element
4279 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4280 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4281 bool isZero, bool HasSSE2,
4282 SelectionDAG &DAG) {
4283 EVT VT = V2.getValueType();
4285 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4286 unsigned NumElems = VT.getVectorNumElements();
4287 SmallVector<int, 16> MaskVec;
4288 for (unsigned i = 0; i != NumElems; ++i)
4289 // If this is the insertion idx, put the low elt of V2 here.
4290 MaskVec.push_back(i == Idx ? NumElems : i);
4291 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4294 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4295 /// element of the result of the vector shuffle.
4296 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4299 return SDValue(); // Limit search depth.
4301 SDValue V = SDValue(N, 0);
4302 EVT VT = V.getValueType();
4303 unsigned Opcode = V.getOpcode();
4305 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4306 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4307 Index = SV->getMaskElt(Index);
4310 return DAG.getUNDEF(VT.getVectorElementType());
4312 int NumElems = VT.getVectorNumElements();
4313 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4314 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4317 // Recurse into target specific vector shuffles to find scalars.
4318 if (isTargetShuffle(Opcode)) {
4319 int NumElems = VT.getVectorNumElements();
4320 SmallVector<unsigned, 16> ShuffleMask;
4324 case X86ISD::SHUFPS:
4325 case X86ISD::SHUFPD:
4326 ImmN = N->getOperand(N->getNumOperands()-1);
4327 DecodeSHUFPSMask(NumElems,
4328 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4331 case X86ISD::PUNPCKHBW:
4332 case X86ISD::PUNPCKHWD:
4333 case X86ISD::PUNPCKHDQ:
4334 case X86ISD::PUNPCKHQDQ:
4335 DecodePUNPCKHMask(NumElems, ShuffleMask);
4337 case X86ISD::UNPCKHPS:
4338 case X86ISD::UNPCKHPD:
4339 case X86ISD::VUNPCKHPSY:
4340 case X86ISD::VUNPCKHPDY:
4341 DecodeUNPCKHPMask(NumElems, ShuffleMask);
4343 case X86ISD::PUNPCKLBW:
4344 case X86ISD::PUNPCKLWD:
4345 case X86ISD::PUNPCKLDQ:
4346 case X86ISD::PUNPCKLQDQ:
4347 DecodePUNPCKLMask(VT, ShuffleMask);
4349 case X86ISD::UNPCKLPS:
4350 case X86ISD::UNPCKLPD:
4351 case X86ISD::VUNPCKLPSY:
4352 case X86ISD::VUNPCKLPDY:
4353 DecodeUNPCKLPMask(VT, ShuffleMask);
4355 case X86ISD::MOVHLPS:
4356 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4358 case X86ISD::MOVLHPS:
4359 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4361 case X86ISD::PSHUFD:
4362 ImmN = N->getOperand(N->getNumOperands()-1);
4363 DecodePSHUFMask(NumElems,
4364 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4367 case X86ISD::PSHUFHW:
4368 ImmN = N->getOperand(N->getNumOperands()-1);
4369 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4372 case X86ISD::PSHUFLW:
4373 ImmN = N->getOperand(N->getNumOperands()-1);
4374 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4378 case X86ISD::MOVSD: {
4379 // The index 0 always comes from the first element of the second source,
4380 // this is why MOVSS and MOVSD are used in the first place. The other
4381 // elements come from the other positions of the first source vector.
4382 unsigned OpNum = (Index == 0) ? 1 : 0;
4383 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4386 case X86ISD::VPERMILPS:
4387 ImmN = N->getOperand(N->getNumOperands()-1);
4388 DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4391 case X86ISD::VPERMILPSY:
4392 ImmN = N->getOperand(N->getNumOperands()-1);
4393 DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4396 case X86ISD::VPERMILPD:
4397 ImmN = N->getOperand(N->getNumOperands()-1);
4398 DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4401 case X86ISD::VPERMILPDY:
4402 ImmN = N->getOperand(N->getNumOperands()-1);
4403 DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4406 case X86ISD::VPERM2F128:
4407 ImmN = N->getOperand(N->getNumOperands()-1);
4408 DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4412 assert("not implemented for target shuffle node");
4416 Index = ShuffleMask[Index];
4418 return DAG.getUNDEF(VT.getVectorElementType());
4420 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4421 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4425 // Actual nodes that may contain scalar elements
4426 if (Opcode == ISD::BITCAST) {
4427 V = V.getOperand(0);
4428 EVT SrcVT = V.getValueType();
4429 unsigned NumElems = VT.getVectorNumElements();
4431 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4435 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4436 return (Index == 0) ? V.getOperand(0)
4437 : DAG.getUNDEF(VT.getVectorElementType());
4439 if (V.getOpcode() == ISD::BUILD_VECTOR)
4440 return V.getOperand(Index);
4445 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4446 /// shuffle operation which come from a consecutively from a zero. The
4447 /// search can start in two different directions, from left or right.
4449 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4450 bool ZerosFromLeft, SelectionDAG &DAG) {
4453 while (i < NumElems) {
4454 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4455 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4456 if (!(Elt.getNode() &&
4457 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4465 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4466 /// MaskE correspond consecutively to elements from one of the vector operands,
4467 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4469 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4470 int OpIdx, int NumElems, unsigned &OpNum) {
4471 bool SeenV1 = false;
4472 bool SeenV2 = false;
4474 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4475 int Idx = SVOp->getMaskElt(i);
4476 // Ignore undef indicies
4485 // Only accept consecutive elements from the same vector
4486 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4490 OpNum = SeenV1 ? 0 : 1;
4494 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4495 /// logical left shift of a vector.
4496 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4497 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4498 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4499 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4500 false /* check zeros from right */, DAG);
4506 // Considering the elements in the mask that are not consecutive zeros,
4507 // check if they consecutively come from only one of the source vectors.
4509 // V1 = {X, A, B, C} 0
4511 // vector_shuffle V1, V2 <1, 2, 3, X>
4513 if (!isShuffleMaskConsecutive(SVOp,
4514 0, // Mask Start Index
4515 NumElems-NumZeros-1, // Mask End Index
4516 NumZeros, // Where to start looking in the src vector
4517 NumElems, // Number of elements in vector
4518 OpSrc)) // Which source operand ?
4523 ShVal = SVOp->getOperand(OpSrc);
4527 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4528 /// logical left shift of a vector.
4529 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4530 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4531 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4532 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4533 true /* check zeros from left */, DAG);
4539 // Considering the elements in the mask that are not consecutive zeros,
4540 // check if they consecutively come from only one of the source vectors.
4542 // 0 { A, B, X, X } = V2
4544 // vector_shuffle V1, V2 <X, X, 4, 5>
4546 if (!isShuffleMaskConsecutive(SVOp,
4547 NumZeros, // Mask Start Index
4548 NumElems-1, // Mask End Index
4549 0, // Where to start looking in the src vector
4550 NumElems, // Number of elements in vector
4551 OpSrc)) // Which source operand ?
4556 ShVal = SVOp->getOperand(OpSrc);
4560 /// isVectorShift - Returns true if the shuffle can be implemented as a
4561 /// logical left or right shift of a vector.
4562 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4563 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4564 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4565 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4571 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4573 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4574 unsigned NumNonZero, unsigned NumZero,
4576 const TargetLowering &TLI) {
4580 DebugLoc dl = Op.getDebugLoc();
4583 for (unsigned i = 0; i < 16; ++i) {
4584 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4585 if (ThisIsNonZero && First) {
4587 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4589 V = DAG.getUNDEF(MVT::v8i16);
4594 SDValue ThisElt(0, 0), LastElt(0, 0);
4595 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4596 if (LastIsNonZero) {
4597 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4598 MVT::i16, Op.getOperand(i-1));
4600 if (ThisIsNonZero) {
4601 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4602 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4603 ThisElt, DAG.getConstant(8, MVT::i8));
4605 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4609 if (ThisElt.getNode())
4610 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4611 DAG.getIntPtrConstant(i/2));
4615 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4618 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4620 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4621 unsigned NumNonZero, unsigned NumZero,
4623 const TargetLowering &TLI) {
4627 DebugLoc dl = Op.getDebugLoc();
4630 for (unsigned i = 0; i < 8; ++i) {
4631 bool isNonZero = (NonZeros & (1 << i)) != 0;
4635 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4637 V = DAG.getUNDEF(MVT::v8i16);
4640 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4641 MVT::v8i16, V, Op.getOperand(i),
4642 DAG.getIntPtrConstant(i));
4649 /// getVShift - Return a vector logical shift node.
4651 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4652 unsigned NumBits, SelectionDAG &DAG,
4653 const TargetLowering &TLI, DebugLoc dl) {
4654 EVT ShVT = MVT::v2i64;
4655 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4656 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4657 return DAG.getNode(ISD::BITCAST, dl, VT,
4658 DAG.getNode(Opc, dl, ShVT, SrcOp,
4659 DAG.getConstant(NumBits,
4660 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4664 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4665 SelectionDAG &DAG) const {
4667 // Check if the scalar load can be widened into a vector load. And if
4668 // the address is "base + cst" see if the cst can be "absorbed" into
4669 // the shuffle mask.
4670 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4671 SDValue Ptr = LD->getBasePtr();
4672 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4674 EVT PVT = LD->getValueType(0);
4675 if (PVT != MVT::i32 && PVT != MVT::f32)
4680 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4681 FI = FINode->getIndex();
4683 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4684 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4685 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4686 Offset = Ptr.getConstantOperandVal(1);
4687 Ptr = Ptr.getOperand(0);
4692 // FIXME: 256-bit vector instructions don't require a strict alignment,
4693 // improve this code to support it better.
4694 unsigned RequiredAlign = VT.getSizeInBits()/8;
4695 SDValue Chain = LD->getChain();
4696 // Make sure the stack object alignment is at least 16 or 32.
4697 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4698 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4699 if (MFI->isFixedObjectIndex(FI)) {
4700 // Can't change the alignment. FIXME: It's possible to compute
4701 // the exact stack offset and reference FI + adjust offset instead.
4702 // If someone *really* cares about this. That's the way to implement it.
4705 MFI->setObjectAlignment(FI, RequiredAlign);
4709 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4710 // Ptr + (Offset & ~15).
4713 if ((Offset % RequiredAlign) & 3)
4715 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4717 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4718 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4720 int EltNo = (Offset - StartOffset) >> 2;
4721 int NumElems = VT.getVectorNumElements();
4723 EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4724 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4725 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4726 LD->getPointerInfo().getWithOffset(StartOffset),
4729 // Canonicalize it to a v4i32 or v8i32 shuffle.
4730 SmallVector<int, 8> Mask;
4731 for (int i = 0; i < NumElems; ++i)
4732 Mask.push_back(EltNo);
4734 V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4735 return DAG.getNode(ISD::BITCAST, dl, NVT,
4736 DAG.getVectorShuffle(CanonVT, dl, V1,
4737 DAG.getUNDEF(CanonVT),&Mask[0]));
4743 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4744 /// vector of type 'VT', see if the elements can be replaced by a single large
4745 /// load which has the same value as a build_vector whose operands are 'elts'.
4747 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4749 /// FIXME: we'd also like to handle the case where the last elements are zero
4750 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4751 /// There's even a handy isZeroNode for that purpose.
4752 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4753 DebugLoc &DL, SelectionDAG &DAG) {
4754 EVT EltVT = VT.getVectorElementType();
4755 unsigned NumElems = Elts.size();
4757 LoadSDNode *LDBase = NULL;
4758 unsigned LastLoadedElt = -1U;
4760 // For each element in the initializer, see if we've found a load or an undef.
4761 // If we don't find an initial load element, or later load elements are
4762 // non-consecutive, bail out.
4763 for (unsigned i = 0; i < NumElems; ++i) {
4764 SDValue Elt = Elts[i];
4766 if (!Elt.getNode() ||
4767 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4770 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4772 LDBase = cast<LoadSDNode>(Elt.getNode());
4776 if (Elt.getOpcode() == ISD::UNDEF)
4779 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4780 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4785 // If we have found an entire vector of loads and undefs, then return a large
4786 // load of the entire vector width starting at the base pointer. If we found
4787 // consecutive loads for the low half, generate a vzext_load node.
4788 if (LastLoadedElt == NumElems - 1) {
4789 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4790 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4791 LDBase->getPointerInfo(),
4792 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4793 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4794 LDBase->getPointerInfo(),
4795 LDBase->isVolatile(), LDBase->isNonTemporal(),
4796 LDBase->getAlignment());
4797 } else if (NumElems == 4 && LastLoadedElt == 1 &&
4798 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4799 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4800 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4801 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4803 LDBase->getMemOperand());
4804 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4810 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4811 DebugLoc dl = Op.getDebugLoc();
4813 EVT VT = Op.getValueType();
4814 EVT ExtVT = VT.getVectorElementType();
4815 unsigned NumElems = Op.getNumOperands();
4817 // Vectors containing all zeros can be matched by pxor and xorps later
4818 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
4819 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
4820 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
4821 if (Op.getValueType() == MVT::v4i32 ||
4822 Op.getValueType() == MVT::v8i32)
4825 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4828 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
4829 // vectors or broken into v4i32 operations on 256-bit vectors.
4830 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
4831 if (Op.getValueType() == MVT::v4i32)
4834 return getOnesVector(Op.getValueType(), DAG, dl);
4837 unsigned EVTBits = ExtVT.getSizeInBits();
4839 unsigned NumZero = 0;
4840 unsigned NumNonZero = 0;
4841 unsigned NonZeros = 0;
4842 bool IsAllConstants = true;
4843 SmallSet<SDValue, 8> Values;
4844 for (unsigned i = 0; i < NumElems; ++i) {
4845 SDValue Elt = Op.getOperand(i);
4846 if (Elt.getOpcode() == ISD::UNDEF)
4849 if (Elt.getOpcode() != ISD::Constant &&
4850 Elt.getOpcode() != ISD::ConstantFP)
4851 IsAllConstants = false;
4852 if (X86::isZeroNode(Elt))
4855 NonZeros |= (1 << i);
4860 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4861 if (NumNonZero == 0)
4862 return DAG.getUNDEF(VT);
4864 // Special case for single non-zero, non-undef, element.
4865 if (NumNonZero == 1) {
4866 unsigned Idx = CountTrailingZeros_32(NonZeros);
4867 SDValue Item = Op.getOperand(Idx);
4869 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4870 // the value are obviously zero, truncate the value to i32 and do the
4871 // insertion that way. Only do this if the value is non-constant or if the
4872 // value is a constant being inserted into element 0. It is cheaper to do
4873 // a constant pool load than it is to do a movd + shuffle.
4874 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4875 (!IsAllConstants || Idx == 0)) {
4876 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4878 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4879 EVT VecVT = MVT::v4i32;
4880 unsigned VecElts = 4;
4882 // Truncate the value (which may itself be a constant) to i32, and
4883 // convert it to a vector with movd (S2V+shuffle to zero extend).
4884 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4885 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4886 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4887 Subtarget->hasSSE2(), DAG);
4889 // Now we have our 32-bit value zero extended in the low element of
4890 // a vector. If Idx != 0, swizzle it into place.
4892 SmallVector<int, 4> Mask;
4893 Mask.push_back(Idx);
4894 for (unsigned i = 1; i != VecElts; ++i)
4896 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4897 DAG.getUNDEF(Item.getValueType()),
4900 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4904 // If we have a constant or non-constant insertion into the low element of
4905 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4906 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4907 // depending on what the source datatype is.
4910 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4911 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4912 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4913 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4914 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4915 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4917 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4918 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4919 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4920 EVT MiddleVT = MVT::v4i32;
4921 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4922 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4923 Subtarget->hasSSE2(), DAG);
4924 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4928 // Is it a vector logical left shift?
4929 if (NumElems == 2 && Idx == 1 &&
4930 X86::isZeroNode(Op.getOperand(0)) &&
4931 !X86::isZeroNode(Op.getOperand(1))) {
4932 unsigned NumBits = VT.getSizeInBits();
4933 return getVShift(true, VT,
4934 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4935 VT, Op.getOperand(1)),
4936 NumBits/2, DAG, *this, dl);
4939 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4942 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4943 // is a non-constant being inserted into an element other than the low one,
4944 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4945 // movd/movss) to move this into the low element, then shuffle it into
4947 if (EVTBits == 32) {
4948 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4950 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4951 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4952 Subtarget->hasSSE2(), DAG);
4953 SmallVector<int, 8> MaskVec;
4954 for (unsigned i = 0; i < NumElems; i++)
4955 MaskVec.push_back(i == Idx ? 0 : 1);
4956 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4960 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4961 if (Values.size() == 1) {
4962 if (EVTBits == 32) {
4963 // Instead of a shuffle like this:
4964 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4965 // Check if it's possible to issue this instead.
4966 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4967 unsigned Idx = CountTrailingZeros_32(NonZeros);
4968 SDValue Item = Op.getOperand(Idx);
4969 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4970 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4975 // A vector full of immediates; various special cases are already
4976 // handled, so this is best done with a single constant-pool load.
4980 // For AVX-length vectors, build the individual 128-bit pieces and use
4981 // shuffles to put them in place.
4982 if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
4983 SmallVector<SDValue, 32> V;
4984 for (unsigned i = 0; i < NumElems; ++i)
4985 V.push_back(Op.getOperand(i));
4987 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4989 // Build both the lower and upper subvector.
4990 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4991 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4994 // Recreate the wider vector with the lower and upper part.
4995 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
4996 DAG.getConstant(0, MVT::i32), DAG, dl);
4997 return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5001 // Let legalizer expand 2-wide build_vectors.
5002 if (EVTBits == 64) {
5003 if (NumNonZero == 1) {
5004 // One half is zero or undef.
5005 unsigned Idx = CountTrailingZeros_32(NonZeros);
5006 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5007 Op.getOperand(Idx));
5008 return getShuffleVectorZeroOrUndef(V2, Idx, true,
5009 Subtarget->hasSSE2(), DAG);
5014 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5015 if (EVTBits == 8 && NumElems == 16) {
5016 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5018 if (V.getNode()) return V;
5021 if (EVTBits == 16 && NumElems == 8) {
5022 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5024 if (V.getNode()) return V;
5027 // If element VT is == 32 bits, turn it into a number of shuffles.
5028 SmallVector<SDValue, 8> V;
5030 if (NumElems == 4 && NumZero > 0) {
5031 for (unsigned i = 0; i < 4; ++i) {
5032 bool isZero = !(NonZeros & (1 << i));
5034 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5036 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5039 for (unsigned i = 0; i < 2; ++i) {
5040 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5043 V[i] = V[i*2]; // Must be a zero vector.
5046 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5049 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5052 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5057 SmallVector<int, 8> MaskVec;
5058 bool Reverse = (NonZeros & 0x3) == 2;
5059 for (unsigned i = 0; i < 2; ++i)
5060 MaskVec.push_back(Reverse ? 1-i : i);
5061 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5062 for (unsigned i = 0; i < 2; ++i)
5063 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5064 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5067 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5068 // Check for a build vector of consecutive loads.
5069 for (unsigned i = 0; i < NumElems; ++i)
5070 V[i] = Op.getOperand(i);
5072 // Check for elements which are consecutive loads.
5073 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5077 // For SSE 4.1, use insertps to put the high elements into the low element.
5078 if (getSubtarget()->hasSSE41()) {
5080 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5081 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5083 Result = DAG.getUNDEF(VT);
5085 for (unsigned i = 1; i < NumElems; ++i) {
5086 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5087 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5088 Op.getOperand(i), DAG.getIntPtrConstant(i));
5093 // Otherwise, expand into a number of unpckl*, start by extending each of
5094 // our (non-undef) elements to the full vector width with the element in the
5095 // bottom slot of the vector (which generates no code for SSE).
5096 for (unsigned i = 0; i < NumElems; ++i) {
5097 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5098 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5100 V[i] = DAG.getUNDEF(VT);
5103 // Next, we iteratively mix elements, e.g. for v4f32:
5104 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5105 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5106 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5107 unsigned EltStride = NumElems >> 1;
5108 while (EltStride != 0) {
5109 for (unsigned i = 0; i < EltStride; ++i) {
5110 // If V[i+EltStride] is undef and this is the first round of mixing,
5111 // then it is safe to just drop this shuffle: V[i] is already in the
5112 // right place, the one element (since it's the first round) being
5113 // inserted as undef can be dropped. This isn't safe for successive
5114 // rounds because they will permute elements within both vectors.
5115 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5116 EltStride == NumElems/2)
5119 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5128 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5129 // them in a MMX register. This is better than doing a stack convert.
5130 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5131 DebugLoc dl = Op.getDebugLoc();
5132 EVT ResVT = Op.getValueType();
5134 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5135 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5137 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5138 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5139 InVec = Op.getOperand(1);
5140 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5141 unsigned NumElts = ResVT.getVectorNumElements();
5142 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5143 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5144 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5146 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5147 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5148 Mask[0] = 0; Mask[1] = 2;
5149 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5151 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5154 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5155 // to create 256-bit vectors from two other 128-bit ones.
5156 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5157 DebugLoc dl = Op.getDebugLoc();
5158 EVT ResVT = Op.getValueType();
5160 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5162 SDValue V1 = Op.getOperand(0);
5163 SDValue V2 = Op.getOperand(1);
5164 unsigned NumElems = ResVT.getVectorNumElements();
5166 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5167 DAG.getConstant(0, MVT::i32), DAG, dl);
5168 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5173 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5174 EVT ResVT = Op.getValueType();
5176 assert(Op.getNumOperands() == 2);
5177 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5178 "Unsupported CONCAT_VECTORS for value type");
5180 // We support concatenate two MMX registers and place them in a MMX register.
5181 // This is better than doing a stack convert.
5182 if (ResVT.is128BitVector())
5183 return LowerMMXCONCAT_VECTORS(Op, DAG);
5185 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5186 // from two other 128-bit ones.
5187 return LowerAVXCONCAT_VECTORS(Op, DAG);
5190 // v8i16 shuffles - Prefer shuffles in the following order:
5191 // 1. [all] pshuflw, pshufhw, optional move
5192 // 2. [ssse3] 1 x pshufb
5193 // 3. [ssse3] 2 x pshufb + 1 x por
5194 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5196 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5197 SelectionDAG &DAG) const {
5198 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5199 SDValue V1 = SVOp->getOperand(0);
5200 SDValue V2 = SVOp->getOperand(1);
5201 DebugLoc dl = SVOp->getDebugLoc();
5202 SmallVector<int, 8> MaskVals;
5204 // Determine if more than 1 of the words in each of the low and high quadwords
5205 // of the result come from the same quadword of one of the two inputs. Undef
5206 // mask values count as coming from any quadword, for better codegen.
5207 SmallVector<unsigned, 4> LoQuad(4);
5208 SmallVector<unsigned, 4> HiQuad(4);
5209 BitVector InputQuads(4);
5210 for (unsigned i = 0; i < 8; ++i) {
5211 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
5212 int EltIdx = SVOp->getMaskElt(i);
5213 MaskVals.push_back(EltIdx);
5222 InputQuads.set(EltIdx / 4);
5225 int BestLoQuad = -1;
5226 unsigned MaxQuad = 1;
5227 for (unsigned i = 0; i < 4; ++i) {
5228 if (LoQuad[i] > MaxQuad) {
5230 MaxQuad = LoQuad[i];
5234 int BestHiQuad = -1;
5236 for (unsigned i = 0; i < 4; ++i) {
5237 if (HiQuad[i] > MaxQuad) {
5239 MaxQuad = HiQuad[i];
5243 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5244 // of the two input vectors, shuffle them into one input vector so only a
5245 // single pshufb instruction is necessary. If There are more than 2 input
5246 // quads, disable the next transformation since it does not help SSSE3.
5247 bool V1Used = InputQuads[0] || InputQuads[1];
5248 bool V2Used = InputQuads[2] || InputQuads[3];
5249 if (Subtarget->hasSSSE3()) {
5250 if (InputQuads.count() == 2 && V1Used && V2Used) {
5251 BestLoQuad = InputQuads.find_first();
5252 BestHiQuad = InputQuads.find_next(BestLoQuad);
5254 if (InputQuads.count() > 2) {
5260 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5261 // the shuffle mask. If a quad is scored as -1, that means that it contains
5262 // words from all 4 input quadwords.
5264 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5265 SmallVector<int, 8> MaskV;
5266 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5267 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5268 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5269 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5270 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5271 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5273 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5274 // source words for the shuffle, to aid later transformations.
5275 bool AllWordsInNewV = true;
5276 bool InOrder[2] = { true, true };
5277 for (unsigned i = 0; i != 8; ++i) {
5278 int idx = MaskVals[i];
5280 InOrder[i/4] = false;
5281 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5283 AllWordsInNewV = false;
5287 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5288 if (AllWordsInNewV) {
5289 for (int i = 0; i != 8; ++i) {
5290 int idx = MaskVals[i];
5293 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5294 if ((idx != i) && idx < 4)
5296 if ((idx != i) && idx > 3)
5305 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5306 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5307 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5308 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5309 unsigned TargetMask = 0;
5310 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5311 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5312 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5313 X86::getShufflePSHUFLWImmediate(NewV.getNode());
5314 V1 = NewV.getOperand(0);
5315 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5319 // If we have SSSE3, and all words of the result are from 1 input vector,
5320 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5321 // is present, fall back to case 4.
5322 if (Subtarget->hasSSSE3()) {
5323 SmallVector<SDValue,16> pshufbMask;
5325 // If we have elements from both input vectors, set the high bit of the
5326 // shuffle mask element to zero out elements that come from V2 in the V1
5327 // mask, and elements that come from V1 in the V2 mask, so that the two
5328 // results can be OR'd together.
5329 bool TwoInputs = V1Used && V2Used;
5330 for (unsigned i = 0; i != 8; ++i) {
5331 int EltIdx = MaskVals[i] * 2;
5332 if (TwoInputs && (EltIdx >= 16)) {
5333 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5334 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5337 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5338 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5340 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5341 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5342 DAG.getNode(ISD::BUILD_VECTOR, dl,
5343 MVT::v16i8, &pshufbMask[0], 16));
5345 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5347 // Calculate the shuffle mask for the second input, shuffle it, and
5348 // OR it with the first shuffled input.
5350 for (unsigned i = 0; i != 8; ++i) {
5351 int EltIdx = MaskVals[i] * 2;
5353 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5354 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5357 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5358 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5360 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5361 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5362 DAG.getNode(ISD::BUILD_VECTOR, dl,
5363 MVT::v16i8, &pshufbMask[0], 16));
5364 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5365 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5368 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5369 // and update MaskVals with new element order.
5370 BitVector InOrder(8);
5371 if (BestLoQuad >= 0) {
5372 SmallVector<int, 8> MaskV;
5373 for (int i = 0; i != 4; ++i) {
5374 int idx = MaskVals[i];
5376 MaskV.push_back(-1);
5378 } else if ((idx / 4) == BestLoQuad) {
5379 MaskV.push_back(idx & 3);
5382 MaskV.push_back(-1);
5385 for (unsigned i = 4; i != 8; ++i)
5387 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5390 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5391 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5393 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5397 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5398 // and update MaskVals with the new element order.
5399 if (BestHiQuad >= 0) {
5400 SmallVector<int, 8> MaskV;
5401 for (unsigned i = 0; i != 4; ++i)
5403 for (unsigned i = 4; i != 8; ++i) {
5404 int idx = MaskVals[i];
5406 MaskV.push_back(-1);
5408 } else if ((idx / 4) == BestHiQuad) {
5409 MaskV.push_back((idx & 3) + 4);
5412 MaskV.push_back(-1);
5415 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5418 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5419 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5421 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5425 // In case BestHi & BestLo were both -1, which means each quadword has a word
5426 // from each of the four input quadwords, calculate the InOrder bitvector now
5427 // before falling through to the insert/extract cleanup.
5428 if (BestLoQuad == -1 && BestHiQuad == -1) {
5430 for (int i = 0; i != 8; ++i)
5431 if (MaskVals[i] < 0 || MaskVals[i] == i)
5435 // The other elements are put in the right place using pextrw and pinsrw.
5436 for (unsigned i = 0; i != 8; ++i) {
5439 int EltIdx = MaskVals[i];
5442 SDValue ExtOp = (EltIdx < 8)
5443 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5444 DAG.getIntPtrConstant(EltIdx))
5445 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5446 DAG.getIntPtrConstant(EltIdx - 8));
5447 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5448 DAG.getIntPtrConstant(i));
5453 // v16i8 shuffles - Prefer shuffles in the following order:
5454 // 1. [ssse3] 1 x pshufb
5455 // 2. [ssse3] 2 x pshufb + 1 x por
5456 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5458 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5460 const X86TargetLowering &TLI) {
5461 SDValue V1 = SVOp->getOperand(0);
5462 SDValue V2 = SVOp->getOperand(1);
5463 DebugLoc dl = SVOp->getDebugLoc();
5464 SmallVector<int, 16> MaskVals;
5465 SVOp->getMask(MaskVals);
5467 // If we have SSSE3, case 1 is generated when all result bytes come from
5468 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5469 // present, fall back to case 3.
5470 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5473 for (unsigned i = 0; i < 16; ++i) {
5474 int EltIdx = MaskVals[i];
5483 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5484 if (TLI.getSubtarget()->hasSSSE3()) {
5485 SmallVector<SDValue,16> pshufbMask;
5487 // If all result elements are from one input vector, then only translate
5488 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5490 // Otherwise, we have elements from both input vectors, and must zero out
5491 // elements that come from V2 in the first mask, and V1 in the second mask
5492 // so that we can OR them together.
5493 bool TwoInputs = !(V1Only || V2Only);
5494 for (unsigned i = 0; i != 16; ++i) {
5495 int EltIdx = MaskVals[i];
5496 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5497 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5500 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5502 // If all the elements are from V2, assign it to V1 and return after
5503 // building the first pshufb.
5506 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5507 DAG.getNode(ISD::BUILD_VECTOR, dl,
5508 MVT::v16i8, &pshufbMask[0], 16));
5512 // Calculate the shuffle mask for the second input, shuffle it, and
5513 // OR it with the first shuffled input.
5515 for (unsigned i = 0; i != 16; ++i) {
5516 int EltIdx = MaskVals[i];
5518 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5521 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5523 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5524 DAG.getNode(ISD::BUILD_VECTOR, dl,
5525 MVT::v16i8, &pshufbMask[0], 16));
5526 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5529 // No SSSE3 - Calculate in place words and then fix all out of place words
5530 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5531 // the 16 different words that comprise the two doublequadword input vectors.
5532 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5533 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5534 SDValue NewV = V2Only ? V2 : V1;
5535 for (int i = 0; i != 8; ++i) {
5536 int Elt0 = MaskVals[i*2];
5537 int Elt1 = MaskVals[i*2+1];
5539 // This word of the result is all undef, skip it.
5540 if (Elt0 < 0 && Elt1 < 0)
5543 // This word of the result is already in the correct place, skip it.
5544 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5546 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5549 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5550 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5553 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5554 // using a single extract together, load it and store it.
5555 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5556 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5557 DAG.getIntPtrConstant(Elt1 / 2));
5558 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5559 DAG.getIntPtrConstant(i));
5563 // If Elt1 is defined, extract it from the appropriate source. If the
5564 // source byte is not also odd, shift the extracted word left 8 bits
5565 // otherwise clear the bottom 8 bits if we need to do an or.
5567 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5568 DAG.getIntPtrConstant(Elt1 / 2));
5569 if ((Elt1 & 1) == 0)
5570 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5572 TLI.getShiftAmountTy(InsElt.getValueType())));
5574 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5575 DAG.getConstant(0xFF00, MVT::i16));
5577 // If Elt0 is defined, extract it from the appropriate source. If the
5578 // source byte is not also even, shift the extracted word right 8 bits. If
5579 // Elt1 was also defined, OR the extracted values together before
5580 // inserting them in the result.
5582 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5583 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5584 if ((Elt0 & 1) != 0)
5585 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5587 TLI.getShiftAmountTy(InsElt0.getValueType())));
5589 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5590 DAG.getConstant(0x00FF, MVT::i16));
5591 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5594 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5595 DAG.getIntPtrConstant(i));
5597 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5600 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5601 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5602 /// done when every pair / quad of shuffle mask elements point to elements in
5603 /// the right sequence. e.g.
5604 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5606 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5607 SelectionDAG &DAG, DebugLoc dl) {
5608 EVT VT = SVOp->getValueType(0);
5609 SDValue V1 = SVOp->getOperand(0);
5610 SDValue V2 = SVOp->getOperand(1);
5611 unsigned NumElems = VT.getVectorNumElements();
5612 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5614 switch (VT.getSimpleVT().SimpleTy) {
5615 default: assert(false && "Unexpected!");
5616 case MVT::v4f32: NewVT = MVT::v2f64; break;
5617 case MVT::v4i32: NewVT = MVT::v2i64; break;
5618 case MVT::v8i16: NewVT = MVT::v4i32; break;
5619 case MVT::v16i8: NewVT = MVT::v4i32; break;
5622 int Scale = NumElems / NewWidth;
5623 SmallVector<int, 8> MaskVec;
5624 for (unsigned i = 0; i < NumElems; i += Scale) {
5626 for (int j = 0; j < Scale; ++j) {
5627 int EltIdx = SVOp->getMaskElt(i+j);
5631 StartIdx = EltIdx - (EltIdx % Scale);
5632 if (EltIdx != StartIdx + j)
5636 MaskVec.push_back(-1);
5638 MaskVec.push_back(StartIdx / Scale);
5641 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5642 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5643 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5646 /// getVZextMovL - Return a zero-extending vector move low node.
5648 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5649 SDValue SrcOp, SelectionDAG &DAG,
5650 const X86Subtarget *Subtarget, DebugLoc dl) {
5651 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5652 LoadSDNode *LD = NULL;
5653 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5654 LD = dyn_cast<LoadSDNode>(SrcOp);
5656 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5658 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5659 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5660 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5661 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5662 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5664 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5665 return DAG.getNode(ISD::BITCAST, dl, VT,
5666 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5667 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5675 return DAG.getNode(ISD::BITCAST, dl, VT,
5676 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5677 DAG.getNode(ISD::BITCAST, dl,
5681 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5682 /// shuffle node referes to only one lane in the sources.
5683 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5684 EVT VT = SVOp->getValueType(0);
5685 int NumElems = VT.getVectorNumElements();
5686 int HalfSize = NumElems/2;
5687 SmallVector<int, 16> M;
5689 bool MatchA = false, MatchB = false;
5691 for (int l = 0; l < NumElems*2; l += HalfSize) {
5692 if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5698 for (int l = 0; l < NumElems*2; l += HalfSize) {
5699 if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5705 return MatchA && MatchB;
5708 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5709 /// which could not be matched by any known target speficic shuffle
5711 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5712 if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5713 // If each half of a vector shuffle node referes to only one lane in the
5714 // source vectors, extract each used 128-bit lane and shuffle them using
5715 // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5716 // the work to the legalizer.
5717 DebugLoc dl = SVOp->getDebugLoc();
5718 EVT VT = SVOp->getValueType(0);
5719 int NumElems = VT.getVectorNumElements();
5720 int HalfSize = NumElems/2;
5722 // Extract the reference for each half
5723 int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5724 int FstVecOpNum = 0, SndVecOpNum = 0;
5725 for (int i = 0; i < HalfSize; ++i) {
5726 int Elt = SVOp->getMaskElt(i);
5727 if (SVOp->getMaskElt(i) < 0)
5729 FstVecOpNum = Elt/NumElems;
5730 FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5733 for (int i = HalfSize; i < NumElems; ++i) {
5734 int Elt = SVOp->getMaskElt(i);
5735 if (SVOp->getMaskElt(i) < 0)
5737 SndVecOpNum = Elt/NumElems;
5738 SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5742 // Extract the subvectors
5743 SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5744 DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5745 SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5746 DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5748 // Generate 128-bit shuffles
5749 SmallVector<int, 16> MaskV1, MaskV2;
5750 for (int i = 0; i < HalfSize; ++i) {
5751 int Elt = SVOp->getMaskElt(i);
5752 MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5754 for (int i = HalfSize; i < NumElems; ++i) {
5755 int Elt = SVOp->getMaskElt(i);
5756 MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5759 EVT NVT = V1.getValueType();
5760 V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5761 V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
5763 // Concatenate the result back
5764 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
5765 DAG.getConstant(0, MVT::i32), DAG, dl);
5766 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5773 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
5774 /// 4 elements, and match them with several different shuffle types.
5776 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5777 SDValue V1 = SVOp->getOperand(0);
5778 SDValue V2 = SVOp->getOperand(1);
5779 DebugLoc dl = SVOp->getDebugLoc();
5780 EVT VT = SVOp->getValueType(0);
5782 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
5784 SmallVector<std::pair<int, int>, 8> Locs;
5786 SmallVector<int, 8> Mask1(4U, -1);
5787 SmallVector<int, 8> PermMask;
5788 SVOp->getMask(PermMask);
5792 for (unsigned i = 0; i != 4; ++i) {
5793 int Idx = PermMask[i];
5795 Locs[i] = std::make_pair(-1, -1);
5797 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5799 Locs[i] = std::make_pair(0, NumLo);
5803 Locs[i] = std::make_pair(1, NumHi);
5805 Mask1[2+NumHi] = Idx;
5811 if (NumLo <= 2 && NumHi <= 2) {
5812 // If no more than two elements come from either vector. This can be
5813 // implemented with two shuffles. First shuffle gather the elements.
5814 // The second shuffle, which takes the first shuffle as both of its
5815 // vector operands, put the elements into the right order.
5816 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5818 SmallVector<int, 8> Mask2(4U, -1);
5820 for (unsigned i = 0; i != 4; ++i) {
5821 if (Locs[i].first == -1)
5824 unsigned Idx = (i < 2) ? 0 : 4;
5825 Idx += Locs[i].first * 2 + Locs[i].second;
5830 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5831 } else if (NumLo == 3 || NumHi == 3) {
5832 // Otherwise, we must have three elements from one vector, call it X, and
5833 // one element from the other, call it Y. First, use a shufps to build an
5834 // intermediate vector with the one element from Y and the element from X
5835 // that will be in the same half in the final destination (the indexes don't
5836 // matter). Then, use a shufps to build the final vector, taking the half
5837 // containing the element from Y from the intermediate, and the other half
5840 // Normalize it so the 3 elements come from V1.
5841 CommuteVectorShuffleMask(PermMask, VT);
5845 // Find the element from V2.
5847 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5848 int Val = PermMask[HiIndex];
5855 Mask1[0] = PermMask[HiIndex];
5857 Mask1[2] = PermMask[HiIndex^1];
5859 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5862 Mask1[0] = PermMask[0];
5863 Mask1[1] = PermMask[1];
5864 Mask1[2] = HiIndex & 1 ? 6 : 4;
5865 Mask1[3] = HiIndex & 1 ? 4 : 6;
5866 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5868 Mask1[0] = HiIndex & 1 ? 2 : 0;
5869 Mask1[1] = HiIndex & 1 ? 0 : 2;
5870 Mask1[2] = PermMask[2];
5871 Mask1[3] = PermMask[3];
5876 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5880 // Break it into (shuffle shuffle_hi, shuffle_lo).
5883 SmallVector<int,8> LoMask(4U, -1);
5884 SmallVector<int,8> HiMask(4U, -1);
5886 SmallVector<int,8> *MaskPtr = &LoMask;
5887 unsigned MaskIdx = 0;
5890 for (unsigned i = 0; i != 4; ++i) {
5897 int Idx = PermMask[i];
5899 Locs[i] = std::make_pair(-1, -1);
5900 } else if (Idx < 4) {
5901 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5902 (*MaskPtr)[LoIdx] = Idx;
5905 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5906 (*MaskPtr)[HiIdx] = Idx;
5911 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5912 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5913 SmallVector<int, 8> MaskOps;
5914 for (unsigned i = 0; i != 4; ++i) {
5915 if (Locs[i].first == -1) {
5916 MaskOps.push_back(-1);
5918 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5919 MaskOps.push_back(Idx);
5922 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5925 static bool MayFoldVectorLoad(SDValue V) {
5926 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5927 V = V.getOperand(0);
5928 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5929 V = V.getOperand(0);
5935 // FIXME: the version above should always be used. Since there's
5936 // a bug where several vector shuffles can't be folded because the
5937 // DAG is not updated during lowering and a node claims to have two
5938 // uses while it only has one, use this version, and let isel match
5939 // another instruction if the load really happens to have more than
5940 // one use. Remove this version after this bug get fixed.
5941 // rdar://8434668, PR8156
5942 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5943 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5944 V = V.getOperand(0);
5945 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5946 V = V.getOperand(0);
5947 if (ISD::isNormalLoad(V.getNode()))
5952 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5953 /// a vector extract, and if both can be later optimized into a single load.
5954 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5955 /// here because otherwise a target specific shuffle node is going to be
5956 /// emitted for this shuffle, and the optimization not done.
5957 /// FIXME: This is probably not the best approach, but fix the problem
5958 /// until the right path is decided.
5960 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5961 const TargetLowering &TLI) {
5962 EVT VT = V.getValueType();
5963 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5965 // Be sure that the vector shuffle is present in a pattern like this:
5966 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5970 SDNode *N = *V.getNode()->use_begin();
5971 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5974 SDValue EltNo = N->getOperand(1);
5975 if (!isa<ConstantSDNode>(EltNo))
5978 // If the bit convert changed the number of elements, it is unsafe
5979 // to examine the mask.
5980 bool HasShuffleIntoBitcast = false;
5981 if (V.getOpcode() == ISD::BITCAST) {
5982 EVT SrcVT = V.getOperand(0).getValueType();
5983 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5985 V = V.getOperand(0);
5986 HasShuffleIntoBitcast = true;
5989 // Select the input vector, guarding against out of range extract vector.
5990 unsigned NumElems = VT.getVectorNumElements();
5991 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5992 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5993 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5995 // Skip one more bit_convert if necessary
5996 if (V.getOpcode() == ISD::BITCAST)
5997 V = V.getOperand(0);
5999 if (ISD::isNormalLoad(V.getNode())) {
6000 // Is the original load suitable?
6001 LoadSDNode *LN0 = cast<LoadSDNode>(V);
6003 // FIXME: avoid the multi-use bug that is preventing lots of
6004 // of foldings to be detected, this is still wrong of course, but
6005 // give the temporary desired behavior, and if it happens that
6006 // the load has real more uses, during isel it will not fold, and
6007 // will generate poor code.
6008 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6011 if (!HasShuffleIntoBitcast)
6014 // If there's a bitcast before the shuffle, check if the load type and
6015 // alignment is valid.
6016 unsigned Align = LN0->getAlignment();
6018 TLI.getTargetData()->getABITypeAlignment(
6019 VT.getTypeForEVT(*DAG.getContext()));
6021 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6029 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6030 EVT VT = Op.getValueType();
6032 // Canonizalize to v2f64.
6033 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6034 return DAG.getNode(ISD::BITCAST, dl, VT,
6035 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6040 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6042 SDValue V1 = Op.getOperand(0);
6043 SDValue V2 = Op.getOperand(1);
6044 EVT VT = Op.getValueType();
6046 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6048 if (HasSSE2 && VT == MVT::v2f64)
6049 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6052 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
6056 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6057 SDValue V1 = Op.getOperand(0);
6058 SDValue V2 = Op.getOperand(1);
6059 EVT VT = Op.getValueType();
6061 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6062 "unsupported shuffle type");
6064 if (V2.getOpcode() == ISD::UNDEF)
6068 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6072 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6073 SDValue V1 = Op.getOperand(0);
6074 SDValue V2 = Op.getOperand(1);
6075 EVT VT = Op.getValueType();
6076 unsigned NumElems = VT.getVectorNumElements();
6078 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6079 // operand of these instructions is only memory, so check if there's a
6080 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6082 bool CanFoldLoad = false;
6084 // Trivial case, when V2 comes from a load.
6085 if (MayFoldVectorLoad(V2))
6088 // When V1 is a load, it can be folded later into a store in isel, example:
6089 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6091 // (MOVLPSmr addr:$src1, VR128:$src2)
6092 // So, recognize this potential and also use MOVLPS or MOVLPD
6093 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6096 // Both of them can't be memory operations though.
6097 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
6098 CanFoldLoad = false;
6101 if (HasSSE2 && NumElems == 2)
6102 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6105 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6108 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6109 // movl and movlp will both match v2i64, but v2i64 is never matched by
6110 // movl earlier because we make it strict to avoid messing with the movlp load
6111 // folding logic (see the code above getMOVLP call). Match it here then,
6112 // this is horrible, but will stay like this until we move all shuffle
6113 // matching to x86 specific nodes. Note that for the 1st condition all
6114 // types are matched with movsd.
6115 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
6116 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6118 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6121 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6123 // Invert the operand order and use SHUFPS to match it.
6124 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
6125 X86::getShuffleSHUFImmediate(SVOp), DAG);
6128 static inline unsigned getUNPCKLOpcode(EVT VT) {
6129 switch(VT.getSimpleVT().SimpleTy) {
6130 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6131 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6132 case MVT::v4f32: return X86ISD::UNPCKLPS;
6133 case MVT::v2f64: return X86ISD::UNPCKLPD;
6134 case MVT::v8i32: // Use fp unit for int unpack.
6135 case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6136 case MVT::v4i64: // Use fp unit for int unpack.
6137 case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6138 case MVT::v16i8: return X86ISD::PUNPCKLBW;
6139 case MVT::v8i16: return X86ISD::PUNPCKLWD;
6141 llvm_unreachable("Unknown type for unpckl");
6146 static inline unsigned getUNPCKHOpcode(EVT VT) {
6147 switch(VT.getSimpleVT().SimpleTy) {
6148 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6149 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6150 case MVT::v4f32: return X86ISD::UNPCKHPS;
6151 case MVT::v2f64: return X86ISD::UNPCKHPD;
6152 case MVT::v8i32: // Use fp unit for int unpack.
6153 case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6154 case MVT::v4i64: // Use fp unit for int unpack.
6155 case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6156 case MVT::v16i8: return X86ISD::PUNPCKHBW;
6157 case MVT::v8i16: return X86ISD::PUNPCKHWD;
6159 llvm_unreachable("Unknown type for unpckh");
6164 static inline unsigned getVPERMILOpcode(EVT VT) {
6165 switch(VT.getSimpleVT().SimpleTy) {
6167 case MVT::v4f32: return X86ISD::VPERMILPS;
6169 case MVT::v2f64: return X86ISD::VPERMILPD;
6171 case MVT::v8f32: return X86ISD::VPERMILPSY;
6173 case MVT::v4f64: return X86ISD::VPERMILPDY;
6175 llvm_unreachable("Unknown type for vpermil");
6180 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
6181 /// a vbroadcast node. The nodes are suitable whenever we can fold a load coming
6182 /// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
6183 static bool isVectorBroadcast(SDValue &Op) {
6184 EVT VT = Op.getValueType();
6185 bool Is256 = VT.getSizeInBits() == 256;
6187 assert((VT.getSizeInBits() == 128 || Is256) &&
6188 "Unsupported type for vbroadcast node");
6191 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6192 V = V.getOperand(0);
6194 if (Is256 && !(V.hasOneUse() &&
6195 V.getOpcode() == ISD::INSERT_SUBVECTOR &&
6196 V.getOperand(0).getOpcode() == ISD::UNDEF))
6200 V = V.getOperand(1);
6201 if (V.hasOneUse() && V.getOpcode() != ISD::SCALAR_TO_VECTOR)
6204 // Check the source scalar_to_vector type. 256-bit broadcasts are
6205 // supported for 32/64-bit sizes, while 128-bit ones are only supported
6206 // for 32-bit scalars.
6207 unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits();
6208 if (ScalarSize != 32 && ScalarSize != 64)
6210 if (!Is256 && ScalarSize == 64)
6213 V = V.getOperand(0);
6214 if (!MayFoldLoad(V))
6217 // Return the load node
6223 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6224 const TargetLowering &TLI,
6225 const X86Subtarget *Subtarget) {
6226 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6227 EVT VT = Op.getValueType();
6228 DebugLoc dl = Op.getDebugLoc();
6229 SDValue V1 = Op.getOperand(0);
6230 SDValue V2 = Op.getOperand(1);
6232 if (isZeroShuffle(SVOp))
6233 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
6235 // Handle splat operations
6236 if (SVOp->isSplat()) {
6237 unsigned NumElem = VT.getVectorNumElements();
6238 int Size = VT.getSizeInBits();
6239 // Special case, this is the only place now where it's allowed to return
6240 // a vector_shuffle operation without using a target specific node, because
6241 // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6242 // this be moved to DAGCombine instead?
6243 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6246 // Use vbroadcast whenever the splat comes from a foldable load
6247 if (Subtarget->hasAVX() && isVectorBroadcast(V1))
6248 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
6250 // Handle splats by matching through known shuffle masks
6251 if ((Size == 128 && NumElem <= 4) ||
6252 (Size == 256 && NumElem < 8))
6255 // All remaning splats are promoted to target supported vector shuffles.
6256 return PromoteSplat(SVOp, DAG);
6259 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6261 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6262 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6263 if (NewOp.getNode())
6264 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6265 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6266 // FIXME: Figure out a cleaner way to do this.
6267 // Try to make use of movq to zero out the top part.
6268 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6269 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6270 if (NewOp.getNode()) {
6271 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6272 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6273 DAG, Subtarget, dl);
6275 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6276 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6277 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6278 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6279 DAG, Subtarget, dl);
6286 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6287 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6288 SDValue V1 = Op.getOperand(0);
6289 SDValue V2 = Op.getOperand(1);
6290 EVT VT = Op.getValueType();
6291 DebugLoc dl = Op.getDebugLoc();
6292 unsigned NumElems = VT.getVectorNumElements();
6293 bool isMMX = VT.getSizeInBits() == 64;
6294 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6295 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6296 bool V1IsSplat = false;
6297 bool V2IsSplat = false;
6298 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
6299 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
6300 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
6301 MachineFunction &MF = DAG.getMachineFunction();
6302 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6304 // Shuffle operations on MMX not supported.
6308 // Vector shuffle lowering takes 3 steps:
6310 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6311 // narrowing and commutation of operands should be handled.
6312 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6314 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6315 // so the shuffle can be broken into other shuffles and the legalizer can
6316 // try the lowering again.
6318 // The general ideia is that no vector_shuffle operation should be left to
6319 // be matched during isel, all of them must be converted to a target specific
6322 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6323 // narrowing and commutation of operands should be handled. The actual code
6324 // doesn't include all of those, work in progress...
6325 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6326 if (NewOp.getNode())
6329 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6330 // unpckh_undef). Only use pshufd if speed is more important than size.
6331 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6332 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6333 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6334 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6336 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
6337 RelaxedMayFoldVectorLoad(V1))
6338 return getMOVDDup(Op, dl, V1, DAG);
6340 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6341 return getMOVHighToLow(Op, dl, DAG);
6343 // Use to match splats
6344 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6345 (VT == MVT::v2f64 || VT == MVT::v2i64))
6346 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6348 if (X86::isPSHUFDMask(SVOp)) {
6349 // The actual implementation will match the mask in the if above and then
6350 // during isel it can match several different instructions, not only pshufd
6351 // as its name says, sad but true, emulate the behavior for now...
6352 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6353 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6355 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6357 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6358 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6360 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6361 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
6364 if (VT == MVT::v4f32)
6365 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
6369 // Check if this can be converted into a logical shift.
6370 bool isLeft = false;
6373 bool isShift = getSubtarget()->hasSSE2() &&
6374 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6375 if (isShift && ShVal.hasOneUse()) {
6376 // If the shifted value has multiple uses, it may be cheaper to use
6377 // v_set0 + movlhps or movhlps, etc.
6378 EVT EltVT = VT.getVectorElementType();
6379 ShAmt *= EltVT.getSizeInBits();
6380 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6383 if (X86::isMOVLMask(SVOp)) {
6386 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6387 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6388 if (!X86::isMOVLPMask(SVOp)) {
6389 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6390 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6392 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6393 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6397 // FIXME: fold these into legal mask.
6398 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6399 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6401 if (X86::isMOVHLPSMask(SVOp))
6402 return getMOVHighToLow(Op, dl, DAG);
6404 if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6405 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6407 if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6408 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6410 if (X86::isMOVLPMask(SVOp))
6411 return getMOVLP(Op, dl, DAG, HasSSE2);
6413 if (ShouldXformToMOVHLPS(SVOp) ||
6414 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6415 return CommuteVectorShuffle(SVOp, DAG);
6418 // No better options. Use a vshl / vsrl.
6419 EVT EltVT = VT.getVectorElementType();
6420 ShAmt *= EltVT.getSizeInBits();
6421 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6424 bool Commuted = false;
6425 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6426 // 1,1,1,1 -> v8i16 though.
6427 V1IsSplat = isSplatVector(V1.getNode());
6428 V2IsSplat = isSplatVector(V2.getNode());
6430 // Canonicalize the splat or undef, if present, to be on the RHS.
6431 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6432 Op = CommuteVectorShuffle(SVOp, DAG);
6433 SVOp = cast<ShuffleVectorSDNode>(Op);
6434 V1 = SVOp->getOperand(0);
6435 V2 = SVOp->getOperand(1);
6436 std::swap(V1IsSplat, V2IsSplat);
6437 std::swap(V1IsUndef, V2IsUndef);
6441 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6442 // Shuffling low element of v1 into undef, just return v1.
6445 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6446 // the instruction selector will not match, so get a canonical MOVL with
6447 // swapped operands to undo the commute.
6448 return getMOVL(DAG, dl, VT, V2, V1);
6451 if (X86::isUNPCKLMask(SVOp))
6452 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6454 if (X86::isUNPCKHMask(SVOp))
6455 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6458 // Normalize mask so all entries that point to V2 points to its first
6459 // element then try to match unpck{h|l} again. If match, return a
6460 // new vector_shuffle with the corrected mask.
6461 SDValue NewMask = NormalizeMask(SVOp, DAG);
6462 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6463 if (NSVOp != SVOp) {
6464 if (X86::isUNPCKLMask(NSVOp, true)) {
6466 } else if (X86::isUNPCKHMask(NSVOp, true)) {
6473 // Commute is back and try unpck* again.
6474 // FIXME: this seems wrong.
6475 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6476 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6478 if (X86::isUNPCKLMask(NewSVOp))
6479 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6481 if (X86::isUNPCKHMask(NewSVOp))
6482 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6485 // Normalize the node to match x86 shuffle ops if needed
6486 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6487 return CommuteVectorShuffle(SVOp, DAG);
6489 // The checks below are all present in isShuffleMaskLegal, but they are
6490 // inlined here right now to enable us to directly emit target specific
6491 // nodes, and remove one by one until they don't return Op anymore.
6492 SmallVector<int, 16> M;
6495 if (isPALIGNRMask(M, VT, HasSSSE3))
6496 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6497 X86::getShufflePALIGNRImmediate(SVOp),
6500 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6501 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6502 if (VT == MVT::v2f64)
6503 return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6504 if (VT == MVT::v2i64)
6505 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6508 if (isPSHUFHWMask(M, VT))
6509 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6510 X86::getShufflePSHUFHWImmediate(SVOp),
6513 if (isPSHUFLWMask(M, VT))
6514 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6515 X86::getShufflePSHUFLWImmediate(SVOp),
6518 if (isSHUFPMask(M, VT)) {
6519 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6520 if (VT == MVT::v4f32 || VT == MVT::v4i32)
6521 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
6523 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6524 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
6528 if (X86::isUNPCKL_v_undef_Mask(SVOp))
6529 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6530 if (X86::isUNPCKH_v_undef_Mask(SVOp))
6531 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6533 //===--------------------------------------------------------------------===//
6534 // Generate target specific nodes for 128 or 256-bit shuffles only
6535 // supported in the AVX instruction set.
6538 // Handle VPERMILPS* permutations
6539 if (isVPERMILPSMask(M, VT, Subtarget))
6540 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6541 getShuffleVPERMILPSImmediate(SVOp), DAG);
6543 // Handle VPERMILPD* permutations
6544 if (isVPERMILPDMask(M, VT, Subtarget))
6545 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6546 getShuffleVPERMILPDImmediate(SVOp), DAG);
6548 // Handle VPERM2F128 permutations
6549 if (isVPERM2F128Mask(M, VT, Subtarget))
6550 return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6551 getShuffleVPERM2F128Immediate(SVOp), DAG);
6553 //===--------------------------------------------------------------------===//
6554 // Since no target specific shuffle was selected for this generic one,
6555 // lower it into other known shuffles. FIXME: this isn't true yet, but
6556 // this is the plan.
6559 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6560 if (VT == MVT::v8i16) {
6561 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6562 if (NewOp.getNode())
6566 if (VT == MVT::v16i8) {
6567 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6568 if (NewOp.getNode())
6572 // Handle all 128-bit wide vectors with 4 elements, and match them with
6573 // several different shuffle types.
6574 if (NumElems == 4 && VT.getSizeInBits() == 128)
6575 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6577 // Handle general 256-bit shuffles
6578 if (VT.is256BitVector())
6579 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6585 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6586 SelectionDAG &DAG) const {
6587 EVT VT = Op.getValueType();
6588 DebugLoc dl = Op.getDebugLoc();
6590 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6593 if (VT.getSizeInBits() == 8) {
6594 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6595 Op.getOperand(0), Op.getOperand(1));
6596 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6597 DAG.getValueType(VT));
6598 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6599 } else if (VT.getSizeInBits() == 16) {
6600 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6601 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6603 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6604 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6605 DAG.getNode(ISD::BITCAST, dl,
6609 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6610 Op.getOperand(0), Op.getOperand(1));
6611 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6612 DAG.getValueType(VT));
6613 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6614 } else if (VT == MVT::f32) {
6615 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6616 // the result back to FR32 register. It's only worth matching if the
6617 // result has a single use which is a store or a bitcast to i32. And in
6618 // the case of a store, it's not worth it if the index is a constant 0,
6619 // because a MOVSSmr can be used instead, which is smaller and faster.
6620 if (!Op.hasOneUse())
6622 SDNode *User = *Op.getNode()->use_begin();
6623 if ((User->getOpcode() != ISD::STORE ||
6624 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6625 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6626 (User->getOpcode() != ISD::BITCAST ||
6627 User->getValueType(0) != MVT::i32))
6629 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6630 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6633 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6634 } else if (VT == MVT::i32) {
6635 // ExtractPS works with constant index.
6636 if (isa<ConstantSDNode>(Op.getOperand(1)))
6644 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6645 SelectionDAG &DAG) const {
6646 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6649 SDValue Vec = Op.getOperand(0);
6650 EVT VecVT = Vec.getValueType();
6652 // If this is a 256-bit vector result, first extract the 128-bit vector and
6653 // then extract the element from the 128-bit vector.
6654 if (VecVT.getSizeInBits() == 256) {
6655 DebugLoc dl = Op.getNode()->getDebugLoc();
6656 unsigned NumElems = VecVT.getVectorNumElements();
6657 SDValue Idx = Op.getOperand(1);
6658 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6660 // Get the 128-bit vector.
6661 bool Upper = IdxVal >= NumElems/2;
6662 Vec = Extract128BitVector(Vec,
6663 DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6665 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6666 Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6669 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6671 if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
6672 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6677 EVT VT = Op.getValueType();
6678 DebugLoc dl = Op.getDebugLoc();
6679 // TODO: handle v16i8.
6680 if (VT.getSizeInBits() == 16) {
6681 SDValue Vec = Op.getOperand(0);
6682 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6684 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6685 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6686 DAG.getNode(ISD::BITCAST, dl,
6689 // Transform it so it match pextrw which produces a 32-bit result.
6690 EVT EltVT = MVT::i32;
6691 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6692 Op.getOperand(0), Op.getOperand(1));
6693 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6694 DAG.getValueType(VT));
6695 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6696 } else if (VT.getSizeInBits() == 32) {
6697 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6701 // SHUFPS the element to the lowest double word, then movss.
6702 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6703 EVT VVT = Op.getOperand(0).getValueType();
6704 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6705 DAG.getUNDEF(VVT), Mask);
6706 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6707 DAG.getIntPtrConstant(0));
6708 } else if (VT.getSizeInBits() == 64) {
6709 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6710 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6711 // to match extract_elt for f64.
6712 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6716 // UNPCKHPD the element to the lowest double word, then movsd.
6717 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6718 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6719 int Mask[2] = { 1, -1 };
6720 EVT VVT = Op.getOperand(0).getValueType();
6721 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6722 DAG.getUNDEF(VVT), Mask);
6723 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6724 DAG.getIntPtrConstant(0));
6731 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6732 SelectionDAG &DAG) const {
6733 EVT VT = Op.getValueType();
6734 EVT EltVT = VT.getVectorElementType();
6735 DebugLoc dl = Op.getDebugLoc();
6737 SDValue N0 = Op.getOperand(0);
6738 SDValue N1 = Op.getOperand(1);
6739 SDValue N2 = Op.getOperand(2);
6741 if (VT.getSizeInBits() == 256)
6744 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6745 isa<ConstantSDNode>(N2)) {
6747 if (VT == MVT::v8i16)
6748 Opc = X86ISD::PINSRW;
6749 else if (VT == MVT::v16i8)
6750 Opc = X86ISD::PINSRB;
6752 Opc = X86ISD::PINSRB;
6754 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6756 if (N1.getValueType() != MVT::i32)
6757 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6758 if (N2.getValueType() != MVT::i32)
6759 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6760 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6761 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6762 // Bits [7:6] of the constant are the source select. This will always be
6763 // zero here. The DAG Combiner may combine an extract_elt index into these
6764 // bits. For example (insert (extract, 3), 2) could be matched by putting
6765 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6766 // Bits [5:4] of the constant are the destination select. This is the
6767 // value of the incoming immediate.
6768 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6769 // combine either bitwise AND or insert of float 0.0 to set these bits.
6770 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6771 // Create this as a scalar to vector..
6772 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6773 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6774 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6775 // PINSR* works with constant index.
6782 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6783 EVT VT = Op.getValueType();
6784 EVT EltVT = VT.getVectorElementType();
6786 DebugLoc dl = Op.getDebugLoc();
6787 SDValue N0 = Op.getOperand(0);
6788 SDValue N1 = Op.getOperand(1);
6789 SDValue N2 = Op.getOperand(2);
6791 // If this is a 256-bit vector result, first extract the 128-bit vector,
6792 // insert the element into the extracted half and then place it back.
6793 if (VT.getSizeInBits() == 256) {
6794 if (!isa<ConstantSDNode>(N2))
6797 // Get the desired 128-bit vector half.
6798 unsigned NumElems = VT.getVectorNumElements();
6799 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6800 bool Upper = IdxVal >= NumElems/2;
6801 SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
6802 SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
6804 // Insert the element into the desired half.
6805 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
6806 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
6808 // Insert the changed part back to the 256-bit vector
6809 return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
6812 if (Subtarget->hasSSE41() || Subtarget->hasAVX())
6813 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6815 if (EltVT == MVT::i8)
6818 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6819 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6820 // as its second argument.
6821 if (N1.getValueType() != MVT::i32)
6822 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6823 if (N2.getValueType() != MVT::i32)
6824 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6825 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6831 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6832 LLVMContext *Context = DAG.getContext();
6833 DebugLoc dl = Op.getDebugLoc();
6834 EVT OpVT = Op.getValueType();
6836 // If this is a 256-bit vector result, first insert into a 128-bit
6837 // vector and then insert into the 256-bit vector.
6838 if (OpVT.getSizeInBits() > 128) {
6839 // Insert into a 128-bit vector.
6840 EVT VT128 = EVT::getVectorVT(*Context,
6841 OpVT.getVectorElementType(),
6842 OpVT.getVectorNumElements() / 2);
6844 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6846 // Insert the 128-bit vector.
6847 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6848 DAG.getConstant(0, MVT::i32),
6852 if (Op.getValueType() == MVT::v1i64 &&
6853 Op.getOperand(0).getValueType() == MVT::i64)
6854 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6856 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6857 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6858 "Expected an SSE type!");
6859 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6860 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6863 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
6864 // a simple subregister reference or explicit instructions to grab
6865 // upper bits of a vector.
6867 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6868 if (Subtarget->hasAVX()) {
6869 DebugLoc dl = Op.getNode()->getDebugLoc();
6870 SDValue Vec = Op.getNode()->getOperand(0);
6871 SDValue Idx = Op.getNode()->getOperand(1);
6873 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6874 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6875 return Extract128BitVector(Vec, Idx, DAG, dl);
6881 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
6882 // simple superregister reference or explicit instructions to insert
6883 // the upper bits of a vector.
6885 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6886 if (Subtarget->hasAVX()) {
6887 DebugLoc dl = Op.getNode()->getDebugLoc();
6888 SDValue Vec = Op.getNode()->getOperand(0);
6889 SDValue SubVec = Op.getNode()->getOperand(1);
6890 SDValue Idx = Op.getNode()->getOperand(2);
6892 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6893 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6894 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6900 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6901 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6902 // one of the above mentioned nodes. It has to be wrapped because otherwise
6903 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6904 // be used to form addressing mode. These wrapped nodes will be selected
6907 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6908 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6910 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6912 unsigned char OpFlag = 0;
6913 unsigned WrapperKind = X86ISD::Wrapper;
6914 CodeModel::Model M = getTargetMachine().getCodeModel();
6916 if (Subtarget->isPICStyleRIPRel() &&
6917 (M == CodeModel::Small || M == CodeModel::Kernel))
6918 WrapperKind = X86ISD::WrapperRIP;
6919 else if (Subtarget->isPICStyleGOT())
6920 OpFlag = X86II::MO_GOTOFF;
6921 else if (Subtarget->isPICStyleStubPIC())
6922 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6924 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6926 CP->getOffset(), OpFlag);
6927 DebugLoc DL = CP->getDebugLoc();
6928 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6929 // With PIC, the address is actually $g + Offset.
6931 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6932 DAG.getNode(X86ISD::GlobalBaseReg,
6933 DebugLoc(), getPointerTy()),
6940 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6941 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6943 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6945 unsigned char OpFlag = 0;
6946 unsigned WrapperKind = X86ISD::Wrapper;
6947 CodeModel::Model M = getTargetMachine().getCodeModel();
6949 if (Subtarget->isPICStyleRIPRel() &&
6950 (M == CodeModel::Small || M == CodeModel::Kernel))
6951 WrapperKind = X86ISD::WrapperRIP;
6952 else if (Subtarget->isPICStyleGOT())
6953 OpFlag = X86II::MO_GOTOFF;
6954 else if (Subtarget->isPICStyleStubPIC())
6955 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6957 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6959 DebugLoc DL = JT->getDebugLoc();
6960 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6962 // With PIC, the address is actually $g + Offset.
6964 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6965 DAG.getNode(X86ISD::GlobalBaseReg,
6966 DebugLoc(), getPointerTy()),
6973 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6974 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6976 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6978 unsigned char OpFlag = 0;
6979 unsigned WrapperKind = X86ISD::Wrapper;
6980 CodeModel::Model M = getTargetMachine().getCodeModel();
6982 if (Subtarget->isPICStyleRIPRel() &&
6983 (M == CodeModel::Small || M == CodeModel::Kernel)) {
6984 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
6985 OpFlag = X86II::MO_GOTPCREL;
6986 WrapperKind = X86ISD::WrapperRIP;
6987 } else if (Subtarget->isPICStyleGOT()) {
6988 OpFlag = X86II::MO_GOT;
6989 } else if (Subtarget->isPICStyleStubPIC()) {
6990 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
6991 } else if (Subtarget->isPICStyleStubNoDynamic()) {
6992 OpFlag = X86II::MO_DARWIN_NONLAZY;
6995 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6997 DebugLoc DL = Op.getDebugLoc();
6998 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7001 // With PIC, the address is actually $g + Offset.
7002 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7003 !Subtarget->is64Bit()) {
7004 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7005 DAG.getNode(X86ISD::GlobalBaseReg,
7006 DebugLoc(), getPointerTy()),
7010 // For symbols that require a load from a stub to get the address, emit the
7012 if (isGlobalStubReference(OpFlag))
7013 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7014 MachinePointerInfo::getGOT(), false, false, 0);
7020 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7021 // Create the TargetBlockAddressAddress node.
7022 unsigned char OpFlags =
7023 Subtarget->ClassifyBlockAddressReference();
7024 CodeModel::Model M = getTargetMachine().getCodeModel();
7025 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7026 DebugLoc dl = Op.getDebugLoc();
7027 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7028 /*isTarget=*/true, OpFlags);
7030 if (Subtarget->isPICStyleRIPRel() &&
7031 (M == CodeModel::Small || M == CodeModel::Kernel))
7032 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7034 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7036 // With PIC, the address is actually $g + Offset.
7037 if (isGlobalRelativeToPICBase(OpFlags)) {
7038 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7039 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7047 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7049 SelectionDAG &DAG) const {
7050 // Create the TargetGlobalAddress node, folding in the constant
7051 // offset if it is legal.
7052 unsigned char OpFlags =
7053 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7054 CodeModel::Model M = getTargetMachine().getCodeModel();
7056 if (OpFlags == X86II::MO_NO_FLAG &&
7057 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7058 // A direct static reference to a global.
7059 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7062 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7065 if (Subtarget->isPICStyleRIPRel() &&
7066 (M == CodeModel::Small || M == CodeModel::Kernel))
7067 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7069 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7071 // With PIC, the address is actually $g + Offset.
7072 if (isGlobalRelativeToPICBase(OpFlags)) {
7073 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7074 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7078 // For globals that require a load from a stub to get the address, emit the
7080 if (isGlobalStubReference(OpFlags))
7081 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7082 MachinePointerInfo::getGOT(), false, false, 0);
7084 // If there was a non-zero offset that we didn't fold, create an explicit
7087 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7088 DAG.getConstant(Offset, getPointerTy()));
7094 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7095 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7096 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7097 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7101 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7102 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7103 unsigned char OperandFlags) {
7104 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7105 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7106 DebugLoc dl = GA->getDebugLoc();
7107 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7108 GA->getValueType(0),
7112 SDValue Ops[] = { Chain, TGA, *InFlag };
7113 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7115 SDValue Ops[] = { Chain, TGA };
7116 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7119 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7120 MFI->setAdjustsStack(true);
7122 SDValue Flag = Chain.getValue(1);
7123 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7126 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7128 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7131 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7132 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7133 DAG.getNode(X86ISD::GlobalBaseReg,
7134 DebugLoc(), PtrVT), InFlag);
7135 InFlag = Chain.getValue(1);
7137 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7140 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7142 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7144 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7145 X86::RAX, X86II::MO_TLSGD);
7148 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7149 // "local exec" model.
7150 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7151 const EVT PtrVT, TLSModel::Model model,
7153 DebugLoc dl = GA->getDebugLoc();
7155 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7156 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7157 is64Bit ? 257 : 256));
7159 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7160 DAG.getIntPtrConstant(0),
7161 MachinePointerInfo(Ptr), false, false, 0);
7163 unsigned char OperandFlags = 0;
7164 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7166 unsigned WrapperKind = X86ISD::Wrapper;
7167 if (model == TLSModel::LocalExec) {
7168 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7169 } else if (is64Bit) {
7170 assert(model == TLSModel::InitialExec);
7171 OperandFlags = X86II::MO_GOTTPOFF;
7172 WrapperKind = X86ISD::WrapperRIP;
7174 assert(model == TLSModel::InitialExec);
7175 OperandFlags = X86II::MO_INDNTPOFF;
7178 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7180 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7181 GA->getValueType(0),
7182 GA->getOffset(), OperandFlags);
7183 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7185 if (model == TLSModel::InitialExec)
7186 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7187 MachinePointerInfo::getGOT(), false, false, 0);
7189 // The address of the thread local variable is the add of the thread
7190 // pointer with the offset of the variable.
7191 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7195 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7197 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7198 const GlobalValue *GV = GA->getGlobal();
7200 if (Subtarget->isTargetELF()) {
7201 // TODO: implement the "local dynamic" model
7202 // TODO: implement the "initial exec"model for pic executables
7204 // If GV is an alias then use the aliasee for determining
7205 // thread-localness.
7206 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7207 GV = GA->resolveAliasedGlobal(false);
7209 TLSModel::Model model
7210 = getTLSModel(GV, getTargetMachine().getRelocationModel());
7213 case TLSModel::GeneralDynamic:
7214 case TLSModel::LocalDynamic: // not implemented
7215 if (Subtarget->is64Bit())
7216 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7217 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7219 case TLSModel::InitialExec:
7220 case TLSModel::LocalExec:
7221 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7222 Subtarget->is64Bit());
7224 } else if (Subtarget->isTargetDarwin()) {
7225 // Darwin only has one model of TLS. Lower to that.
7226 unsigned char OpFlag = 0;
7227 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7228 X86ISD::WrapperRIP : X86ISD::Wrapper;
7230 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7232 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7233 !Subtarget->is64Bit();
7235 OpFlag = X86II::MO_TLVP_PIC_BASE;
7237 OpFlag = X86II::MO_TLVP;
7238 DebugLoc DL = Op.getDebugLoc();
7239 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7240 GA->getValueType(0),
7241 GA->getOffset(), OpFlag);
7242 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7244 // With PIC32, the address is actually $g + Offset.
7246 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7247 DAG.getNode(X86ISD::GlobalBaseReg,
7248 DebugLoc(), getPointerTy()),
7251 // Lowering the machine isd will make sure everything is in the right
7253 SDValue Chain = DAG.getEntryNode();
7254 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7255 SDValue Args[] = { Chain, Offset };
7256 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7258 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7259 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7260 MFI->setAdjustsStack(true);
7262 // And our return value (tls address) is in the standard call return value
7264 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7265 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
7269 "TLS not implemented for this target.");
7271 llvm_unreachable("Unreachable");
7276 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7277 /// take a 2 x i32 value to shift plus a shift amount.
7278 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7279 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7280 EVT VT = Op.getValueType();
7281 unsigned VTBits = VT.getSizeInBits();
7282 DebugLoc dl = Op.getDebugLoc();
7283 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7284 SDValue ShOpLo = Op.getOperand(0);
7285 SDValue ShOpHi = Op.getOperand(1);
7286 SDValue ShAmt = Op.getOperand(2);
7287 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7288 DAG.getConstant(VTBits - 1, MVT::i8))
7289 : DAG.getConstant(0, VT);
7292 if (Op.getOpcode() == ISD::SHL_PARTS) {
7293 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7294 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7296 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7297 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7300 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7301 DAG.getConstant(VTBits, MVT::i8));
7302 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7303 AndNode, DAG.getConstant(0, MVT::i8));
7306 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7307 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7308 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7310 if (Op.getOpcode() == ISD::SHL_PARTS) {
7311 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7312 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7314 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7315 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7318 SDValue Ops[2] = { Lo, Hi };
7319 return DAG.getMergeValues(Ops, 2, dl);
7322 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7323 SelectionDAG &DAG) const {
7324 EVT SrcVT = Op.getOperand(0).getValueType();
7326 if (SrcVT.isVector())
7329 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7330 "Unknown SINT_TO_FP to lower!");
7332 // These are really Legal; return the operand so the caller accepts it as
7334 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7336 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7337 Subtarget->is64Bit()) {
7341 DebugLoc dl = Op.getDebugLoc();
7342 unsigned Size = SrcVT.getSizeInBits()/8;
7343 MachineFunction &MF = DAG.getMachineFunction();
7344 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7345 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7346 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7348 MachinePointerInfo::getFixedStack(SSFI),
7350 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7353 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7355 SelectionDAG &DAG) const {
7357 DebugLoc DL = Op.getDebugLoc();
7359 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7361 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7363 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7365 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7367 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7368 MachineMemOperand *MMO;
7370 int SSFI = FI->getIndex();
7372 DAG.getMachineFunction()
7373 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7374 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7376 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7377 StackSlot = StackSlot.getOperand(1);
7379 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7380 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7382 Tys, Ops, array_lengthof(Ops),
7386 Chain = Result.getValue(1);
7387 SDValue InFlag = Result.getValue(2);
7389 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7390 // shouldn't be necessary except that RFP cannot be live across
7391 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7392 MachineFunction &MF = DAG.getMachineFunction();
7393 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7394 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7395 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7396 Tys = DAG.getVTList(MVT::Other);
7398 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7400 MachineMemOperand *MMO =
7401 DAG.getMachineFunction()
7402 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7403 MachineMemOperand::MOStore, SSFISize, SSFISize);
7405 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7406 Ops, array_lengthof(Ops),
7407 Op.getValueType(), MMO);
7408 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7409 MachinePointerInfo::getFixedStack(SSFI),
7416 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7417 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7418 SelectionDAG &DAG) const {
7419 // This algorithm is not obvious. Here it is in C code, more or less:
7421 double uint64_to_double( uint32_t hi, uint32_t lo ) {
7422 static const __m128i exp = { 0x4330000045300000ULL, 0 };
7423 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7425 // Copy ints to xmm registers.
7426 __m128i xh = _mm_cvtsi32_si128( hi );
7427 __m128i xl = _mm_cvtsi32_si128( lo );
7429 // Combine into low half of a single xmm register.
7430 __m128i x = _mm_unpacklo_epi32( xh, xl );
7434 // Merge in appropriate exponents to give the integer bits the right
7436 x = _mm_unpacklo_epi32( x, exp );
7438 // Subtract away the biases to deal with the IEEE-754 double precision
7440 d = _mm_sub_pd( (__m128d) x, bias );
7442 // All conversions up to here are exact. The correctly rounded result is
7443 // calculated using the current rounding mode using the following
7445 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7446 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
7447 // store doesn't really need to be here (except
7448 // maybe to zero the other double)
7453 DebugLoc dl = Op.getDebugLoc();
7454 LLVMContext *Context = DAG.getContext();
7456 // Build some magic constants.
7457 std::vector<Constant*> CV0;
7458 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7459 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7460 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7461 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7462 Constant *C0 = ConstantVector::get(CV0);
7463 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7465 std::vector<Constant*> CV1;
7467 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7469 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7470 Constant *C1 = ConstantVector::get(CV1);
7471 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7473 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7474 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7476 DAG.getIntPtrConstant(1)));
7477 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7478 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7480 DAG.getIntPtrConstant(0)));
7481 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7482 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7483 MachinePointerInfo::getConstantPool(),
7485 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7486 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7487 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7488 MachinePointerInfo::getConstantPool(),
7490 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7492 // Add the halves; easiest way is to swap them into another reg first.
7493 int ShufMask[2] = { 1, -1 };
7494 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7495 DAG.getUNDEF(MVT::v2f64), ShufMask);
7496 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7497 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7498 DAG.getIntPtrConstant(0));
7501 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7502 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7503 SelectionDAG &DAG) const {
7504 DebugLoc dl = Op.getDebugLoc();
7505 // FP constant to bias correct the final result.
7506 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7509 // Load the 32-bit value into an XMM register.
7510 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7513 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7514 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7515 DAG.getIntPtrConstant(0));
7517 // Or the load with the bias.
7518 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7519 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7520 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7522 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7523 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7524 MVT::v2f64, Bias)));
7525 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7526 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7527 DAG.getIntPtrConstant(0));
7529 // Subtract the bias.
7530 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7532 // Handle final rounding.
7533 EVT DestVT = Op.getValueType();
7535 if (DestVT.bitsLT(MVT::f64)) {
7536 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7537 DAG.getIntPtrConstant(0));
7538 } else if (DestVT.bitsGT(MVT::f64)) {
7539 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7542 // Handle final rounding.
7546 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7547 SelectionDAG &DAG) const {
7548 SDValue N0 = Op.getOperand(0);
7549 DebugLoc dl = Op.getDebugLoc();
7551 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7552 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7553 // the optimization here.
7554 if (DAG.SignBitIsZero(N0))
7555 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7557 EVT SrcVT = N0.getValueType();
7558 EVT DstVT = Op.getValueType();
7559 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7560 return LowerUINT_TO_FP_i64(Op, DAG);
7561 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7562 return LowerUINT_TO_FP_i32(Op, DAG);
7564 // Make a 64-bit buffer, and use it to build an FILD.
7565 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7566 if (SrcVT == MVT::i32) {
7567 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7568 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7569 getPointerTy(), StackSlot, WordOff);
7570 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7571 StackSlot, MachinePointerInfo(),
7573 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7574 OffsetSlot, MachinePointerInfo(),
7576 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7580 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7581 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7582 StackSlot, MachinePointerInfo(),
7584 // For i64 source, we need to add the appropriate power of 2 if the input
7585 // was negative. This is the same as the optimization in
7586 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7587 // we must be careful to do the computation in x87 extended precision, not
7588 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7589 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7590 MachineMemOperand *MMO =
7591 DAG.getMachineFunction()
7592 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7593 MachineMemOperand::MOLoad, 8, 8);
7595 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7596 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7597 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7600 APInt FF(32, 0x5F800000ULL);
7602 // Check whether the sign bit is set.
7603 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7604 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7607 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7608 SDValue FudgePtr = DAG.getConstantPool(
7609 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7612 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7613 SDValue Zero = DAG.getIntPtrConstant(0);
7614 SDValue Four = DAG.getIntPtrConstant(4);
7615 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7617 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7619 // Load the value out, extending it from f32 to f80.
7620 // FIXME: Avoid the extend by constructing the right constant pool?
7621 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7622 FudgePtr, MachinePointerInfo::getConstantPool(),
7623 MVT::f32, false, false, 4);
7624 // Extend everything to 80 bits to force it to be done on x87.
7625 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7626 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7629 std::pair<SDValue,SDValue> X86TargetLowering::
7630 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7631 DebugLoc DL = Op.getDebugLoc();
7633 EVT DstTy = Op.getValueType();
7636 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7640 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7641 DstTy.getSimpleVT() >= MVT::i16 &&
7642 "Unknown FP_TO_SINT to lower!");
7644 // These are really Legal.
7645 if (DstTy == MVT::i32 &&
7646 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7647 return std::make_pair(SDValue(), SDValue());
7648 if (Subtarget->is64Bit() &&
7649 DstTy == MVT::i64 &&
7650 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7651 return std::make_pair(SDValue(), SDValue());
7653 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7655 MachineFunction &MF = DAG.getMachineFunction();
7656 unsigned MemSize = DstTy.getSizeInBits()/8;
7657 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7658 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7663 switch (DstTy.getSimpleVT().SimpleTy) {
7664 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7665 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7666 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7667 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7670 SDValue Chain = DAG.getEntryNode();
7671 SDValue Value = Op.getOperand(0);
7672 EVT TheVT = Op.getOperand(0).getValueType();
7673 if (isScalarFPTypeInSSEReg(TheVT)) {
7674 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7675 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7676 MachinePointerInfo::getFixedStack(SSFI),
7678 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7680 Chain, StackSlot, DAG.getValueType(TheVT)
7683 MachineMemOperand *MMO =
7684 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7685 MachineMemOperand::MOLoad, MemSize, MemSize);
7686 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7688 Chain = Value.getValue(1);
7689 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7690 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7693 MachineMemOperand *MMO =
7694 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7695 MachineMemOperand::MOStore, MemSize, MemSize);
7697 // Build the FP_TO_INT*_IN_MEM
7698 SDValue Ops[] = { Chain, Value, StackSlot };
7699 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7700 Ops, 3, DstTy, MMO);
7702 return std::make_pair(FIST, StackSlot);
7705 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7706 SelectionDAG &DAG) const {
7707 if (Op.getValueType().isVector())
7710 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7711 SDValue FIST = Vals.first, StackSlot = Vals.second;
7712 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7713 if (FIST.getNode() == 0) return Op;
7716 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7717 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7720 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7721 SelectionDAG &DAG) const {
7722 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7723 SDValue FIST = Vals.first, StackSlot = Vals.second;
7724 assert(FIST.getNode() && "Unexpected failure");
7727 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7728 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7731 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7732 SelectionDAG &DAG) const {
7733 LLVMContext *Context = DAG.getContext();
7734 DebugLoc dl = Op.getDebugLoc();
7735 EVT VT = Op.getValueType();
7738 EltVT = VT.getVectorElementType();
7739 std::vector<Constant*> CV;
7740 if (EltVT == MVT::f64) {
7741 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7745 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7751 Constant *C = ConstantVector::get(CV);
7752 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7753 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7754 MachinePointerInfo::getConstantPool(),
7756 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7759 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7760 LLVMContext *Context = DAG.getContext();
7761 DebugLoc dl = Op.getDebugLoc();
7762 EVT VT = Op.getValueType();
7765 EltVT = VT.getVectorElementType();
7766 std::vector<Constant*> CV;
7767 if (EltVT == MVT::f64) {
7768 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7772 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7778 Constant *C = ConstantVector::get(CV);
7779 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7780 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7781 MachinePointerInfo::getConstantPool(),
7783 if (VT.isVector()) {
7784 return DAG.getNode(ISD::BITCAST, dl, VT,
7785 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7786 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7788 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7790 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7794 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7795 LLVMContext *Context = DAG.getContext();
7796 SDValue Op0 = Op.getOperand(0);
7797 SDValue Op1 = Op.getOperand(1);
7798 DebugLoc dl = Op.getDebugLoc();
7799 EVT VT = Op.getValueType();
7800 EVT SrcVT = Op1.getValueType();
7802 // If second operand is smaller, extend it first.
7803 if (SrcVT.bitsLT(VT)) {
7804 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7807 // And if it is bigger, shrink it first.
7808 if (SrcVT.bitsGT(VT)) {
7809 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7813 // At this point the operands and the result should have the same
7814 // type, and that won't be f80 since that is not custom lowered.
7816 // First get the sign bit of second operand.
7817 std::vector<Constant*> CV;
7818 if (SrcVT == MVT::f64) {
7819 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7820 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7822 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7823 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7824 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7825 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7827 Constant *C = ConstantVector::get(CV);
7828 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7829 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7830 MachinePointerInfo::getConstantPool(),
7832 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7834 // Shift sign bit right or left if the two operands have different types.
7835 if (SrcVT.bitsGT(VT)) {
7836 // Op0 is MVT::f32, Op1 is MVT::f64.
7837 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7838 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7839 DAG.getConstant(32, MVT::i32));
7840 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7841 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7842 DAG.getIntPtrConstant(0));
7845 // Clear first operand sign bit.
7847 if (VT == MVT::f64) {
7848 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7849 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7851 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7852 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7853 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7854 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7856 C = ConstantVector::get(CV);
7857 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7858 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7859 MachinePointerInfo::getConstantPool(),
7861 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7863 // Or the value with the sign bit.
7864 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7867 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7868 SDValue N0 = Op.getOperand(0);
7869 DebugLoc dl = Op.getDebugLoc();
7870 EVT VT = Op.getValueType();
7872 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7873 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7874 DAG.getConstant(1, VT));
7875 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7878 /// Emit nodes that will be selected as "test Op0,Op0", or something
7880 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7881 SelectionDAG &DAG) const {
7882 DebugLoc dl = Op.getDebugLoc();
7884 // CF and OF aren't always set the way we want. Determine which
7885 // of these we need.
7886 bool NeedCF = false;
7887 bool NeedOF = false;
7890 case X86::COND_A: case X86::COND_AE:
7891 case X86::COND_B: case X86::COND_BE:
7894 case X86::COND_G: case X86::COND_GE:
7895 case X86::COND_L: case X86::COND_LE:
7896 case X86::COND_O: case X86::COND_NO:
7901 // See if we can use the EFLAGS value from the operand instead of
7902 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7903 // we prove that the arithmetic won't overflow, we can't use OF or CF.
7904 if (Op.getResNo() != 0 || NeedOF || NeedCF)
7905 // Emit a CMP with 0, which is the TEST pattern.
7906 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7907 DAG.getConstant(0, Op.getValueType()));
7909 unsigned Opcode = 0;
7910 unsigned NumOperands = 0;
7911 switch (Op.getNode()->getOpcode()) {
7913 // Due to an isel shortcoming, be conservative if this add is likely to be
7914 // selected as part of a load-modify-store instruction. When the root node
7915 // in a match is a store, isel doesn't know how to remap non-chain non-flag
7916 // uses of other nodes in the match, such as the ADD in this case. This
7917 // leads to the ADD being left around and reselected, with the result being
7918 // two adds in the output. Alas, even if none our users are stores, that
7919 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
7920 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
7921 // climbing the DAG back to the root, and it doesn't seem to be worth the
7923 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7924 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7925 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7928 if (ConstantSDNode *C =
7929 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7930 // An add of one will be selected as an INC.
7931 if (C->getAPIntValue() == 1) {
7932 Opcode = X86ISD::INC;
7937 // An add of negative one (subtract of one) will be selected as a DEC.
7938 if (C->getAPIntValue().isAllOnesValue()) {
7939 Opcode = X86ISD::DEC;
7945 // Otherwise use a regular EFLAGS-setting add.
7946 Opcode = X86ISD::ADD;
7950 // If the primary and result isn't used, don't bother using X86ISD::AND,
7951 // because a TEST instruction will be better.
7952 bool NonFlagUse = false;
7953 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7954 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7956 unsigned UOpNo = UI.getOperandNo();
7957 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7958 // Look pass truncate.
7959 UOpNo = User->use_begin().getOperandNo();
7960 User = *User->use_begin();
7963 if (User->getOpcode() != ISD::BRCOND &&
7964 User->getOpcode() != ISD::SETCC &&
7965 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7978 // Due to the ISEL shortcoming noted above, be conservative if this op is
7979 // likely to be selected as part of a load-modify-store instruction.
7980 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7981 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7982 if (UI->getOpcode() == ISD::STORE)
7985 // Otherwise use a regular EFLAGS-setting instruction.
7986 switch (Op.getNode()->getOpcode()) {
7987 default: llvm_unreachable("unexpected operator!");
7988 case ISD::SUB: Opcode = X86ISD::SUB; break;
7989 case ISD::OR: Opcode = X86ISD::OR; break;
7990 case ISD::XOR: Opcode = X86ISD::XOR; break;
7991 case ISD::AND: Opcode = X86ISD::AND; break;
8003 return SDValue(Op.getNode(), 1);
8010 // Emit a CMP with 0, which is the TEST pattern.
8011 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8012 DAG.getConstant(0, Op.getValueType()));
8014 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8015 SmallVector<SDValue, 4> Ops;
8016 for (unsigned i = 0; i != NumOperands; ++i)
8017 Ops.push_back(Op.getOperand(i));
8019 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8020 DAG.ReplaceAllUsesWith(Op, New);
8021 return SDValue(New.getNode(), 1);
8024 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8026 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8027 SelectionDAG &DAG) const {
8028 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8029 if (C->getAPIntValue() == 0)
8030 return EmitTest(Op0, X86CC, DAG);
8032 DebugLoc dl = Op0.getDebugLoc();
8033 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8036 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8037 /// if it's possible.
8038 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8039 DebugLoc dl, SelectionDAG &DAG) const {
8040 SDValue Op0 = And.getOperand(0);
8041 SDValue Op1 = And.getOperand(1);
8042 if (Op0.getOpcode() == ISD::TRUNCATE)
8043 Op0 = Op0.getOperand(0);
8044 if (Op1.getOpcode() == ISD::TRUNCATE)
8045 Op1 = Op1.getOperand(0);
8048 if (Op1.getOpcode() == ISD::SHL)
8049 std::swap(Op0, Op1);
8050 if (Op0.getOpcode() == ISD::SHL) {
8051 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8052 if (And00C->getZExtValue() == 1) {
8053 // If we looked past a truncate, check that it's only truncating away
8055 unsigned BitWidth = Op0.getValueSizeInBits();
8056 unsigned AndBitWidth = And.getValueSizeInBits();
8057 if (BitWidth > AndBitWidth) {
8058 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8059 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8060 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8064 RHS = Op0.getOperand(1);
8066 } else if (Op1.getOpcode() == ISD::Constant) {
8067 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8068 SDValue AndLHS = Op0;
8069 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8070 LHS = AndLHS.getOperand(0);
8071 RHS = AndLHS.getOperand(1);
8075 if (LHS.getNode()) {
8076 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8077 // instruction. Since the shift amount is in-range-or-undefined, we know
8078 // that doing a bittest on the i32 value is ok. We extend to i32 because
8079 // the encoding for the i16 version is larger than the i32 version.
8080 // Also promote i16 to i32 for performance / code size reason.
8081 if (LHS.getValueType() == MVT::i8 ||
8082 LHS.getValueType() == MVT::i16)
8083 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8085 // If the operand types disagree, extend the shift amount to match. Since
8086 // BT ignores high bits (like shifts) we can use anyextend.
8087 if (LHS.getValueType() != RHS.getValueType())
8088 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8090 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8091 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8092 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8093 DAG.getConstant(Cond, MVT::i8), BT);
8099 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8100 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8101 SDValue Op0 = Op.getOperand(0);
8102 SDValue Op1 = Op.getOperand(1);
8103 DebugLoc dl = Op.getDebugLoc();
8104 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8106 // Optimize to BT if possible.
8107 // Lower (X & (1 << N)) == 0 to BT(X, N).
8108 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8109 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8110 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8111 Op1.getOpcode() == ISD::Constant &&
8112 cast<ConstantSDNode>(Op1)->isNullValue() &&
8113 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8114 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8115 if (NewSetCC.getNode())
8119 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8121 if (Op1.getOpcode() == ISD::Constant &&
8122 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8123 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8124 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8126 // If the input is a setcc, then reuse the input setcc or use a new one with
8127 // the inverted condition.
8128 if (Op0.getOpcode() == X86ISD::SETCC) {
8129 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8130 bool Invert = (CC == ISD::SETNE) ^
8131 cast<ConstantSDNode>(Op1)->isNullValue();
8132 if (!Invert) return Op0;
8134 CCode = X86::GetOppositeBranchCondition(CCode);
8135 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8136 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8140 bool isFP = Op1.getValueType().isFloatingPoint();
8141 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8142 if (X86CC == X86::COND_INVALID)
8145 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8146 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8147 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8150 // Lower256IntVETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8151 // ones, and then concatenate the result back.
8152 static SDValue Lower256IntVETCC(SDValue Op, SelectionDAG &DAG) {
8153 EVT VT = Op.getValueType();
8155 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::VSETCC &&
8156 "Unsupported value type for operation");
8158 int NumElems = VT.getVectorNumElements();
8159 DebugLoc dl = Op.getDebugLoc();
8160 SDValue CC = Op.getOperand(2);
8161 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8162 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8164 // Extract the LHS vectors
8165 SDValue LHS = Op.getOperand(0);
8166 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8167 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8169 // Extract the RHS vectors
8170 SDValue RHS = Op.getOperand(1);
8171 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8172 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8174 // Issue the operation on the smaller types and concatenate the result back
8175 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8176 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8177 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8178 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8179 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8183 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8185 SDValue Op0 = Op.getOperand(0);
8186 SDValue Op1 = Op.getOperand(1);
8187 SDValue CC = Op.getOperand(2);
8188 EVT VT = Op.getValueType();
8189 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8190 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8191 DebugLoc dl = Op.getDebugLoc();
8195 EVT EltVT = Op0.getValueType().getVectorElementType();
8196 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8198 unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8201 switch (SetCCOpcode) {
8204 case ISD::SETEQ: SSECC = 0; break;
8206 case ISD::SETGT: Swap = true; // Fallthrough
8208 case ISD::SETOLT: SSECC = 1; break;
8210 case ISD::SETGE: Swap = true; // Fallthrough
8212 case ISD::SETOLE: SSECC = 2; break;
8213 case ISD::SETUO: SSECC = 3; break;
8215 case ISD::SETNE: SSECC = 4; break;
8216 case ISD::SETULE: Swap = true;
8217 case ISD::SETUGE: SSECC = 5; break;
8218 case ISD::SETULT: Swap = true;
8219 case ISD::SETUGT: SSECC = 6; break;
8220 case ISD::SETO: SSECC = 7; break;
8223 std::swap(Op0, Op1);
8225 // In the two special cases we can't handle, emit two comparisons.
8227 if (SetCCOpcode == ISD::SETUEQ) {
8229 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8230 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8231 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8233 else if (SetCCOpcode == ISD::SETONE) {
8235 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8236 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8237 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8239 llvm_unreachable("Illegal FP comparison");
8241 // Handle all other FP comparisons here.
8242 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8245 // Break 256-bit integer vector compare into smaller ones.
8246 if (!isFP && VT.getSizeInBits() == 256)
8247 return Lower256IntVETCC(Op, DAG);
8249 // We are handling one of the integer comparisons here. Since SSE only has
8250 // GT and EQ comparisons for integer, swapping operands and multiple
8251 // operations may be required for some comparisons.
8252 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8253 bool Swap = false, Invert = false, FlipSigns = false;
8255 switch (VT.getSimpleVT().SimpleTy) {
8257 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8258 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8259 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8260 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8263 switch (SetCCOpcode) {
8265 case ISD::SETNE: Invert = true;
8266 case ISD::SETEQ: Opc = EQOpc; break;
8267 case ISD::SETLT: Swap = true;
8268 case ISD::SETGT: Opc = GTOpc; break;
8269 case ISD::SETGE: Swap = true;
8270 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
8271 case ISD::SETULT: Swap = true;
8272 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8273 case ISD::SETUGE: Swap = true;
8274 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8277 std::swap(Op0, Op1);
8279 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8280 // bits of the inputs before performing those operations.
8282 EVT EltVT = VT.getVectorElementType();
8283 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8285 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8286 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8288 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8289 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8292 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8294 // If the logical-not of the result is required, perform that now.
8296 Result = DAG.getNOT(dl, Result, VT);
8301 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8302 static bool isX86LogicalCmp(SDValue Op) {
8303 unsigned Opc = Op.getNode()->getOpcode();
8304 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8306 if (Op.getResNo() == 1 &&
8307 (Opc == X86ISD::ADD ||
8308 Opc == X86ISD::SUB ||
8309 Opc == X86ISD::ADC ||
8310 Opc == X86ISD::SBB ||
8311 Opc == X86ISD::SMUL ||
8312 Opc == X86ISD::UMUL ||
8313 Opc == X86ISD::INC ||
8314 Opc == X86ISD::DEC ||
8315 Opc == X86ISD::OR ||
8316 Opc == X86ISD::XOR ||
8317 Opc == X86ISD::AND))
8320 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8326 static bool isZero(SDValue V) {
8327 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8328 return C && C->isNullValue();
8331 static bool isAllOnes(SDValue V) {
8332 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8333 return C && C->isAllOnesValue();
8336 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8337 bool addTest = true;
8338 SDValue Cond = Op.getOperand(0);
8339 SDValue Op1 = Op.getOperand(1);
8340 SDValue Op2 = Op.getOperand(2);
8341 DebugLoc DL = Op.getDebugLoc();
8344 if (Cond.getOpcode() == ISD::SETCC) {
8345 SDValue NewCond = LowerSETCC(Cond, DAG);
8346 if (NewCond.getNode())
8350 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8351 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8352 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8353 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8354 if (Cond.getOpcode() == X86ISD::SETCC &&
8355 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8356 isZero(Cond.getOperand(1).getOperand(1))) {
8357 SDValue Cmp = Cond.getOperand(1);
8359 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8361 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8362 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8363 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8365 SDValue CmpOp0 = Cmp.getOperand(0);
8366 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8367 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8369 SDValue Res = // Res = 0 or -1.
8370 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8371 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8373 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8374 Res = DAG.getNOT(DL, Res, Res.getValueType());
8376 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8377 if (N2C == 0 || !N2C->isNullValue())
8378 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8383 // Look past (and (setcc_carry (cmp ...)), 1).
8384 if (Cond.getOpcode() == ISD::AND &&
8385 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8386 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8387 if (C && C->getAPIntValue() == 1)
8388 Cond = Cond.getOperand(0);
8391 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8392 // setting operand in place of the X86ISD::SETCC.
8393 if (Cond.getOpcode() == X86ISD::SETCC ||
8394 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8395 CC = Cond.getOperand(0);
8397 SDValue Cmp = Cond.getOperand(1);
8398 unsigned Opc = Cmp.getOpcode();
8399 EVT VT = Op.getValueType();
8401 bool IllegalFPCMov = false;
8402 if (VT.isFloatingPoint() && !VT.isVector() &&
8403 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8404 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8406 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8407 Opc == X86ISD::BT) { // FIXME
8414 // Look pass the truncate.
8415 if (Cond.getOpcode() == ISD::TRUNCATE)
8416 Cond = Cond.getOperand(0);
8418 // We know the result of AND is compared against zero. Try to match
8420 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8421 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8422 if (NewSetCC.getNode()) {
8423 CC = NewSetCC.getOperand(0);
8424 Cond = NewSetCC.getOperand(1);
8431 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8432 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8435 // a < b ? -1 : 0 -> RES = ~setcc_carry
8436 // a < b ? 0 : -1 -> RES = setcc_carry
8437 // a >= b ? -1 : 0 -> RES = setcc_carry
8438 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8439 if (Cond.getOpcode() == X86ISD::CMP) {
8440 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8442 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8443 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8444 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8445 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8446 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8447 return DAG.getNOT(DL, Res, Res.getValueType());
8452 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8453 // condition is true.
8454 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8455 SDValue Ops[] = { Op2, Op1, CC, Cond };
8456 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8459 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8460 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8461 // from the AND / OR.
8462 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8463 Opc = Op.getOpcode();
8464 if (Opc != ISD::OR && Opc != ISD::AND)
8466 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8467 Op.getOperand(0).hasOneUse() &&
8468 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8469 Op.getOperand(1).hasOneUse());
8472 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8473 // 1 and that the SETCC node has a single use.
8474 static bool isXor1OfSetCC(SDValue Op) {
8475 if (Op.getOpcode() != ISD::XOR)
8477 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8478 if (N1C && N1C->getAPIntValue() == 1) {
8479 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8480 Op.getOperand(0).hasOneUse();
8485 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8486 bool addTest = true;
8487 SDValue Chain = Op.getOperand(0);
8488 SDValue Cond = Op.getOperand(1);
8489 SDValue Dest = Op.getOperand(2);
8490 DebugLoc dl = Op.getDebugLoc();
8493 if (Cond.getOpcode() == ISD::SETCC) {
8494 SDValue NewCond = LowerSETCC(Cond, DAG);
8495 if (NewCond.getNode())
8499 // FIXME: LowerXALUO doesn't handle these!!
8500 else if (Cond.getOpcode() == X86ISD::ADD ||
8501 Cond.getOpcode() == X86ISD::SUB ||
8502 Cond.getOpcode() == X86ISD::SMUL ||
8503 Cond.getOpcode() == X86ISD::UMUL)
8504 Cond = LowerXALUO(Cond, DAG);
8507 // Look pass (and (setcc_carry (cmp ...)), 1).
8508 if (Cond.getOpcode() == ISD::AND &&
8509 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8510 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8511 if (C && C->getAPIntValue() == 1)
8512 Cond = Cond.getOperand(0);
8515 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8516 // setting operand in place of the X86ISD::SETCC.
8517 if (Cond.getOpcode() == X86ISD::SETCC ||
8518 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8519 CC = Cond.getOperand(0);
8521 SDValue Cmp = Cond.getOperand(1);
8522 unsigned Opc = Cmp.getOpcode();
8523 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8524 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8528 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8532 // These can only come from an arithmetic instruction with overflow,
8533 // e.g. SADDO, UADDO.
8534 Cond = Cond.getNode()->getOperand(1);
8541 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8542 SDValue Cmp = Cond.getOperand(0).getOperand(1);
8543 if (CondOpc == ISD::OR) {
8544 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8545 // two branches instead of an explicit OR instruction with a
8547 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8548 isX86LogicalCmp(Cmp)) {
8549 CC = Cond.getOperand(0).getOperand(0);
8550 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8551 Chain, Dest, CC, Cmp);
8552 CC = Cond.getOperand(1).getOperand(0);
8556 } else { // ISD::AND
8557 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8558 // two branches instead of an explicit AND instruction with a
8559 // separate test. However, we only do this if this block doesn't
8560 // have a fall-through edge, because this requires an explicit
8561 // jmp when the condition is false.
8562 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8563 isX86LogicalCmp(Cmp) &&
8564 Op.getNode()->hasOneUse()) {
8565 X86::CondCode CCode =
8566 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8567 CCode = X86::GetOppositeBranchCondition(CCode);
8568 CC = DAG.getConstant(CCode, MVT::i8);
8569 SDNode *User = *Op.getNode()->use_begin();
8570 // Look for an unconditional branch following this conditional branch.
8571 // We need this because we need to reverse the successors in order
8572 // to implement FCMP_OEQ.
8573 if (User->getOpcode() == ISD::BR) {
8574 SDValue FalseBB = User->getOperand(1);
8576 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8577 assert(NewBR == User);
8581 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8582 Chain, Dest, CC, Cmp);
8583 X86::CondCode CCode =
8584 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8585 CCode = X86::GetOppositeBranchCondition(CCode);
8586 CC = DAG.getConstant(CCode, MVT::i8);
8592 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8593 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8594 // It should be transformed during dag combiner except when the condition
8595 // is set by a arithmetics with overflow node.
8596 X86::CondCode CCode =
8597 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8598 CCode = X86::GetOppositeBranchCondition(CCode);
8599 CC = DAG.getConstant(CCode, MVT::i8);
8600 Cond = Cond.getOperand(0).getOperand(1);
8606 // Look pass the truncate.
8607 if (Cond.getOpcode() == ISD::TRUNCATE)
8608 Cond = Cond.getOperand(0);
8610 // We know the result of AND is compared against zero. Try to match
8612 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8613 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8614 if (NewSetCC.getNode()) {
8615 CC = NewSetCC.getOperand(0);
8616 Cond = NewSetCC.getOperand(1);
8623 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8624 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8626 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8627 Chain, Dest, CC, Cond);
8631 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8632 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8633 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8634 // that the guard pages used by the OS virtual memory manager are allocated in
8635 // correct sequence.
8637 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8638 SelectionDAG &DAG) const {
8639 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8640 "This should be used only on Windows targets");
8641 assert(!Subtarget->isTargetEnvMacho());
8642 DebugLoc dl = Op.getDebugLoc();
8645 SDValue Chain = Op.getOperand(0);
8646 SDValue Size = Op.getOperand(1);
8647 // FIXME: Ensure alignment here
8651 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8652 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8654 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8655 Flag = Chain.getValue(1);
8657 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8659 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8660 Flag = Chain.getValue(1);
8662 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8664 SDValue Ops1[2] = { Chain.getValue(0), Chain };
8665 return DAG.getMergeValues(Ops1, 2, dl);
8668 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8669 MachineFunction &MF = DAG.getMachineFunction();
8670 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8672 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8673 DebugLoc DL = Op.getDebugLoc();
8675 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8676 // vastart just stores the address of the VarArgsFrameIndex slot into the
8677 // memory location argument.
8678 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8680 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8681 MachinePointerInfo(SV), false, false, 0);
8685 // gp_offset (0 - 6 * 8)
8686 // fp_offset (48 - 48 + 8 * 16)
8687 // overflow_arg_area (point to parameters coming in memory).
8689 SmallVector<SDValue, 8> MemOps;
8690 SDValue FIN = Op.getOperand(1);
8692 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8693 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8695 FIN, MachinePointerInfo(SV), false, false, 0);
8696 MemOps.push_back(Store);
8699 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8700 FIN, DAG.getIntPtrConstant(4));
8701 Store = DAG.getStore(Op.getOperand(0), DL,
8702 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8704 FIN, MachinePointerInfo(SV, 4), false, false, 0);
8705 MemOps.push_back(Store);
8707 // Store ptr to overflow_arg_area
8708 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8709 FIN, DAG.getIntPtrConstant(4));
8710 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8712 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8713 MachinePointerInfo(SV, 8),
8715 MemOps.push_back(Store);
8717 // Store ptr to reg_save_area.
8718 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8719 FIN, DAG.getIntPtrConstant(8));
8720 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8722 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8723 MachinePointerInfo(SV, 16), false, false, 0);
8724 MemOps.push_back(Store);
8725 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8726 &MemOps[0], MemOps.size());
8729 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8730 assert(Subtarget->is64Bit() &&
8731 "LowerVAARG only handles 64-bit va_arg!");
8732 assert((Subtarget->isTargetLinux() ||
8733 Subtarget->isTargetDarwin()) &&
8734 "Unhandled target in LowerVAARG");
8735 assert(Op.getNode()->getNumOperands() == 4);
8736 SDValue Chain = Op.getOperand(0);
8737 SDValue SrcPtr = Op.getOperand(1);
8738 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8739 unsigned Align = Op.getConstantOperandVal(3);
8740 DebugLoc dl = Op.getDebugLoc();
8742 EVT ArgVT = Op.getNode()->getValueType(0);
8743 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8744 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8747 // Decide which area this value should be read from.
8748 // TODO: Implement the AMD64 ABI in its entirety. This simple
8749 // selection mechanism works only for the basic types.
8750 if (ArgVT == MVT::f80) {
8751 llvm_unreachable("va_arg for f80 not yet implemented");
8752 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8753 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
8754 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8755 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
8757 llvm_unreachable("Unhandled argument type in LowerVAARG");
8761 // Sanity Check: Make sure using fp_offset makes sense.
8762 assert(!UseSoftFloat &&
8763 !(DAG.getMachineFunction()
8764 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8765 Subtarget->hasXMM());
8768 // Insert VAARG_64 node into the DAG
8769 // VAARG_64 returns two values: Variable Argument Address, Chain
8770 SmallVector<SDValue, 11> InstOps;
8771 InstOps.push_back(Chain);
8772 InstOps.push_back(SrcPtr);
8773 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8774 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8775 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8776 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8777 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8778 VTs, &InstOps[0], InstOps.size(),
8780 MachinePointerInfo(SV),
8785 Chain = VAARG.getValue(1);
8787 // Load the next argument and return it
8788 return DAG.getLoad(ArgVT, dl,
8791 MachinePointerInfo(),
8795 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8796 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8797 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8798 SDValue Chain = Op.getOperand(0);
8799 SDValue DstPtr = Op.getOperand(1);
8800 SDValue SrcPtr = Op.getOperand(2);
8801 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8802 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8803 DebugLoc DL = Op.getDebugLoc();
8805 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8806 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8808 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8812 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8813 DebugLoc dl = Op.getDebugLoc();
8814 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8816 default: return SDValue(); // Don't custom lower most intrinsics.
8817 // Comparison intrinsics.
8818 case Intrinsic::x86_sse_comieq_ss:
8819 case Intrinsic::x86_sse_comilt_ss:
8820 case Intrinsic::x86_sse_comile_ss:
8821 case Intrinsic::x86_sse_comigt_ss:
8822 case Intrinsic::x86_sse_comige_ss:
8823 case Intrinsic::x86_sse_comineq_ss:
8824 case Intrinsic::x86_sse_ucomieq_ss:
8825 case Intrinsic::x86_sse_ucomilt_ss:
8826 case Intrinsic::x86_sse_ucomile_ss:
8827 case Intrinsic::x86_sse_ucomigt_ss:
8828 case Intrinsic::x86_sse_ucomige_ss:
8829 case Intrinsic::x86_sse_ucomineq_ss:
8830 case Intrinsic::x86_sse2_comieq_sd:
8831 case Intrinsic::x86_sse2_comilt_sd:
8832 case Intrinsic::x86_sse2_comile_sd:
8833 case Intrinsic::x86_sse2_comigt_sd:
8834 case Intrinsic::x86_sse2_comige_sd:
8835 case Intrinsic::x86_sse2_comineq_sd:
8836 case Intrinsic::x86_sse2_ucomieq_sd:
8837 case Intrinsic::x86_sse2_ucomilt_sd:
8838 case Intrinsic::x86_sse2_ucomile_sd:
8839 case Intrinsic::x86_sse2_ucomigt_sd:
8840 case Intrinsic::x86_sse2_ucomige_sd:
8841 case Intrinsic::x86_sse2_ucomineq_sd: {
8843 ISD::CondCode CC = ISD::SETCC_INVALID;
8846 case Intrinsic::x86_sse_comieq_ss:
8847 case Intrinsic::x86_sse2_comieq_sd:
8851 case Intrinsic::x86_sse_comilt_ss:
8852 case Intrinsic::x86_sse2_comilt_sd:
8856 case Intrinsic::x86_sse_comile_ss:
8857 case Intrinsic::x86_sse2_comile_sd:
8861 case Intrinsic::x86_sse_comigt_ss:
8862 case Intrinsic::x86_sse2_comigt_sd:
8866 case Intrinsic::x86_sse_comige_ss:
8867 case Intrinsic::x86_sse2_comige_sd:
8871 case Intrinsic::x86_sse_comineq_ss:
8872 case Intrinsic::x86_sse2_comineq_sd:
8876 case Intrinsic::x86_sse_ucomieq_ss:
8877 case Intrinsic::x86_sse2_ucomieq_sd:
8878 Opc = X86ISD::UCOMI;
8881 case Intrinsic::x86_sse_ucomilt_ss:
8882 case Intrinsic::x86_sse2_ucomilt_sd:
8883 Opc = X86ISD::UCOMI;
8886 case Intrinsic::x86_sse_ucomile_ss:
8887 case Intrinsic::x86_sse2_ucomile_sd:
8888 Opc = X86ISD::UCOMI;
8891 case Intrinsic::x86_sse_ucomigt_ss:
8892 case Intrinsic::x86_sse2_ucomigt_sd:
8893 Opc = X86ISD::UCOMI;
8896 case Intrinsic::x86_sse_ucomige_ss:
8897 case Intrinsic::x86_sse2_ucomige_sd:
8898 Opc = X86ISD::UCOMI;
8901 case Intrinsic::x86_sse_ucomineq_ss:
8902 case Intrinsic::x86_sse2_ucomineq_sd:
8903 Opc = X86ISD::UCOMI;
8908 SDValue LHS = Op.getOperand(1);
8909 SDValue RHS = Op.getOperand(2);
8910 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8911 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8912 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8913 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8914 DAG.getConstant(X86CC, MVT::i8), Cond);
8915 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8917 // ptest and testp intrinsics. The intrinsic these come from are designed to
8918 // return an integer value, not just an instruction so lower it to the ptest
8919 // or testp pattern and a setcc for the result.
8920 case Intrinsic::x86_sse41_ptestz:
8921 case Intrinsic::x86_sse41_ptestc:
8922 case Intrinsic::x86_sse41_ptestnzc:
8923 case Intrinsic::x86_avx_ptestz_256:
8924 case Intrinsic::x86_avx_ptestc_256:
8925 case Intrinsic::x86_avx_ptestnzc_256:
8926 case Intrinsic::x86_avx_vtestz_ps:
8927 case Intrinsic::x86_avx_vtestc_ps:
8928 case Intrinsic::x86_avx_vtestnzc_ps:
8929 case Intrinsic::x86_avx_vtestz_pd:
8930 case Intrinsic::x86_avx_vtestc_pd:
8931 case Intrinsic::x86_avx_vtestnzc_pd:
8932 case Intrinsic::x86_avx_vtestz_ps_256:
8933 case Intrinsic::x86_avx_vtestc_ps_256:
8934 case Intrinsic::x86_avx_vtestnzc_ps_256:
8935 case Intrinsic::x86_avx_vtestz_pd_256:
8936 case Intrinsic::x86_avx_vtestc_pd_256:
8937 case Intrinsic::x86_avx_vtestnzc_pd_256: {
8938 bool IsTestPacked = false;
8941 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8942 case Intrinsic::x86_avx_vtestz_ps:
8943 case Intrinsic::x86_avx_vtestz_pd:
8944 case Intrinsic::x86_avx_vtestz_ps_256:
8945 case Intrinsic::x86_avx_vtestz_pd_256:
8946 IsTestPacked = true; // Fallthrough
8947 case Intrinsic::x86_sse41_ptestz:
8948 case Intrinsic::x86_avx_ptestz_256:
8950 X86CC = X86::COND_E;
8952 case Intrinsic::x86_avx_vtestc_ps:
8953 case Intrinsic::x86_avx_vtestc_pd:
8954 case Intrinsic::x86_avx_vtestc_ps_256:
8955 case Intrinsic::x86_avx_vtestc_pd_256:
8956 IsTestPacked = true; // Fallthrough
8957 case Intrinsic::x86_sse41_ptestc:
8958 case Intrinsic::x86_avx_ptestc_256:
8960 X86CC = X86::COND_B;
8962 case Intrinsic::x86_avx_vtestnzc_ps:
8963 case Intrinsic::x86_avx_vtestnzc_pd:
8964 case Intrinsic::x86_avx_vtestnzc_ps_256:
8965 case Intrinsic::x86_avx_vtestnzc_pd_256:
8966 IsTestPacked = true; // Fallthrough
8967 case Intrinsic::x86_sse41_ptestnzc:
8968 case Intrinsic::x86_avx_ptestnzc_256:
8970 X86CC = X86::COND_A;
8974 SDValue LHS = Op.getOperand(1);
8975 SDValue RHS = Op.getOperand(2);
8976 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8977 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8978 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8979 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8980 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8983 // Fix vector shift instructions where the last operand is a non-immediate
8985 case Intrinsic::x86_sse2_pslli_w:
8986 case Intrinsic::x86_sse2_pslli_d:
8987 case Intrinsic::x86_sse2_pslli_q:
8988 case Intrinsic::x86_sse2_psrli_w:
8989 case Intrinsic::x86_sse2_psrli_d:
8990 case Intrinsic::x86_sse2_psrli_q:
8991 case Intrinsic::x86_sse2_psrai_w:
8992 case Intrinsic::x86_sse2_psrai_d:
8993 case Intrinsic::x86_mmx_pslli_w:
8994 case Intrinsic::x86_mmx_pslli_d:
8995 case Intrinsic::x86_mmx_pslli_q:
8996 case Intrinsic::x86_mmx_psrli_w:
8997 case Intrinsic::x86_mmx_psrli_d:
8998 case Intrinsic::x86_mmx_psrli_q:
8999 case Intrinsic::x86_mmx_psrai_w:
9000 case Intrinsic::x86_mmx_psrai_d: {
9001 SDValue ShAmt = Op.getOperand(2);
9002 if (isa<ConstantSDNode>(ShAmt))
9005 unsigned NewIntNo = 0;
9006 EVT ShAmtVT = MVT::v4i32;
9008 case Intrinsic::x86_sse2_pslli_w:
9009 NewIntNo = Intrinsic::x86_sse2_psll_w;
9011 case Intrinsic::x86_sse2_pslli_d:
9012 NewIntNo = Intrinsic::x86_sse2_psll_d;
9014 case Intrinsic::x86_sse2_pslli_q:
9015 NewIntNo = Intrinsic::x86_sse2_psll_q;
9017 case Intrinsic::x86_sse2_psrli_w:
9018 NewIntNo = Intrinsic::x86_sse2_psrl_w;
9020 case Intrinsic::x86_sse2_psrli_d:
9021 NewIntNo = Intrinsic::x86_sse2_psrl_d;
9023 case Intrinsic::x86_sse2_psrli_q:
9024 NewIntNo = Intrinsic::x86_sse2_psrl_q;
9026 case Intrinsic::x86_sse2_psrai_w:
9027 NewIntNo = Intrinsic::x86_sse2_psra_w;
9029 case Intrinsic::x86_sse2_psrai_d:
9030 NewIntNo = Intrinsic::x86_sse2_psra_d;
9033 ShAmtVT = MVT::v2i32;
9035 case Intrinsic::x86_mmx_pslli_w:
9036 NewIntNo = Intrinsic::x86_mmx_psll_w;
9038 case Intrinsic::x86_mmx_pslli_d:
9039 NewIntNo = Intrinsic::x86_mmx_psll_d;
9041 case Intrinsic::x86_mmx_pslli_q:
9042 NewIntNo = Intrinsic::x86_mmx_psll_q;
9044 case Intrinsic::x86_mmx_psrli_w:
9045 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9047 case Intrinsic::x86_mmx_psrli_d:
9048 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9050 case Intrinsic::x86_mmx_psrli_q:
9051 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9053 case Intrinsic::x86_mmx_psrai_w:
9054 NewIntNo = Intrinsic::x86_mmx_psra_w;
9056 case Intrinsic::x86_mmx_psrai_d:
9057 NewIntNo = Intrinsic::x86_mmx_psra_d;
9059 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9065 // The vector shift intrinsics with scalars uses 32b shift amounts but
9066 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9070 ShOps[1] = DAG.getConstant(0, MVT::i32);
9071 if (ShAmtVT == MVT::v4i32) {
9072 ShOps[2] = DAG.getUNDEF(MVT::i32);
9073 ShOps[3] = DAG.getUNDEF(MVT::i32);
9074 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9076 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9077 // FIXME this must be lowered to get rid of the invalid type.
9080 EVT VT = Op.getValueType();
9081 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9082 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9083 DAG.getConstant(NewIntNo, MVT::i32),
9084 Op.getOperand(1), ShAmt);
9089 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9090 SelectionDAG &DAG) const {
9091 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9092 MFI->setReturnAddressIsTaken(true);
9094 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9095 DebugLoc dl = Op.getDebugLoc();
9098 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9100 DAG.getConstant(TD->getPointerSize(),
9101 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9102 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9103 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9105 MachinePointerInfo(), false, false, 0);
9108 // Just load the return address.
9109 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9110 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9111 RetAddrFI, MachinePointerInfo(), false, false, 0);
9114 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9115 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9116 MFI->setFrameAddressIsTaken(true);
9118 EVT VT = Op.getValueType();
9119 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9120 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9121 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9122 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9124 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9125 MachinePointerInfo(),
9130 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9131 SelectionDAG &DAG) const {
9132 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9135 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9136 MachineFunction &MF = DAG.getMachineFunction();
9137 SDValue Chain = Op.getOperand(0);
9138 SDValue Offset = Op.getOperand(1);
9139 SDValue Handler = Op.getOperand(2);
9140 DebugLoc dl = Op.getDebugLoc();
9142 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9143 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9145 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9147 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9148 DAG.getIntPtrConstant(TD->getPointerSize()));
9149 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9150 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9152 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9153 MF.getRegInfo().addLiveOut(StoreAddrReg);
9155 return DAG.getNode(X86ISD::EH_RETURN, dl,
9157 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9160 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
9161 SelectionDAG &DAG) const {
9162 SDValue Root = Op.getOperand(0);
9163 SDValue Trmp = Op.getOperand(1); // trampoline
9164 SDValue FPtr = Op.getOperand(2); // nested function
9165 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9166 DebugLoc dl = Op.getDebugLoc();
9168 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9170 if (Subtarget->is64Bit()) {
9171 SDValue OutChains[6];
9173 // Large code-model.
9174 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
9175 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9177 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9178 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9180 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9182 // Load the pointer to the nested function into R11.
9183 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9184 SDValue Addr = Trmp;
9185 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9186 Addr, MachinePointerInfo(TrmpAddr),
9189 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9190 DAG.getConstant(2, MVT::i64));
9191 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9192 MachinePointerInfo(TrmpAddr, 2),
9195 // Load the 'nest' parameter value into R10.
9196 // R10 is specified in X86CallingConv.td
9197 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9198 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9199 DAG.getConstant(10, MVT::i64));
9200 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9201 Addr, MachinePointerInfo(TrmpAddr, 10),
9204 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9205 DAG.getConstant(12, MVT::i64));
9206 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9207 MachinePointerInfo(TrmpAddr, 12),
9210 // Jump to the nested function.
9211 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9212 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9213 DAG.getConstant(20, MVT::i64));
9214 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9215 Addr, MachinePointerInfo(TrmpAddr, 20),
9218 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9219 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9220 DAG.getConstant(22, MVT::i64));
9221 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9222 MachinePointerInfo(TrmpAddr, 22),
9226 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
9227 return DAG.getMergeValues(Ops, 2, dl);
9229 const Function *Func =
9230 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9231 CallingConv::ID CC = Func->getCallingConv();
9236 llvm_unreachable("Unsupported calling convention");
9237 case CallingConv::C:
9238 case CallingConv::X86_StdCall: {
9239 // Pass 'nest' parameter in ECX.
9240 // Must be kept in sync with X86CallingConv.td
9243 // Check that ECX wasn't needed by an 'inreg' parameter.
9244 FunctionType *FTy = Func->getFunctionType();
9245 const AttrListPtr &Attrs = Func->getAttributes();
9247 if (!Attrs.isEmpty() && !Func->isVarArg()) {
9248 unsigned InRegCount = 0;
9251 for (FunctionType::param_iterator I = FTy->param_begin(),
9252 E = FTy->param_end(); I != E; ++I, ++Idx)
9253 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9254 // FIXME: should only count parameters that are lowered to integers.
9255 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9257 if (InRegCount > 2) {
9258 report_fatal_error("Nest register in use - reduce number of inreg"
9264 case CallingConv::X86_FastCall:
9265 case CallingConv::X86_ThisCall:
9266 case CallingConv::Fast:
9267 // Pass 'nest' parameter in EAX.
9268 // Must be kept in sync with X86CallingConv.td
9273 SDValue OutChains[4];
9276 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9277 DAG.getConstant(10, MVT::i32));
9278 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9280 // This is storing the opcode for MOV32ri.
9281 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9282 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9283 OutChains[0] = DAG.getStore(Root, dl,
9284 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9285 Trmp, MachinePointerInfo(TrmpAddr),
9288 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9289 DAG.getConstant(1, MVT::i32));
9290 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9291 MachinePointerInfo(TrmpAddr, 1),
9294 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9295 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9296 DAG.getConstant(5, MVT::i32));
9297 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9298 MachinePointerInfo(TrmpAddr, 5),
9301 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9302 DAG.getConstant(6, MVT::i32));
9303 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9304 MachinePointerInfo(TrmpAddr, 6),
9308 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
9309 return DAG.getMergeValues(Ops, 2, dl);
9313 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9314 SelectionDAG &DAG) const {
9316 The rounding mode is in bits 11:10 of FPSR, and has the following
9323 FLT_ROUNDS, on the other hand, expects the following:
9330 To perform the conversion, we do:
9331 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9334 MachineFunction &MF = DAG.getMachineFunction();
9335 const TargetMachine &TM = MF.getTarget();
9336 const TargetFrameLowering &TFI = *TM.getFrameLowering();
9337 unsigned StackAlignment = TFI.getStackAlignment();
9338 EVT VT = Op.getValueType();
9339 DebugLoc DL = Op.getDebugLoc();
9341 // Save FP Control Word to stack slot
9342 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9343 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9346 MachineMemOperand *MMO =
9347 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9348 MachineMemOperand::MOStore, 2, 2);
9350 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9351 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9352 DAG.getVTList(MVT::Other),
9353 Ops, 2, MVT::i16, MMO);
9355 // Load FP Control Word from stack slot
9356 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9357 MachinePointerInfo(), false, false, 0);
9359 // Transform as necessary
9361 DAG.getNode(ISD::SRL, DL, MVT::i16,
9362 DAG.getNode(ISD::AND, DL, MVT::i16,
9363 CWD, DAG.getConstant(0x800, MVT::i16)),
9364 DAG.getConstant(11, MVT::i8));
9366 DAG.getNode(ISD::SRL, DL, MVT::i16,
9367 DAG.getNode(ISD::AND, DL, MVT::i16,
9368 CWD, DAG.getConstant(0x400, MVT::i16)),
9369 DAG.getConstant(9, MVT::i8));
9372 DAG.getNode(ISD::AND, DL, MVT::i16,
9373 DAG.getNode(ISD::ADD, DL, MVT::i16,
9374 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9375 DAG.getConstant(1, MVT::i16)),
9376 DAG.getConstant(3, MVT::i16));
9379 return DAG.getNode((VT.getSizeInBits() < 16 ?
9380 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9383 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9384 EVT VT = Op.getValueType();
9386 unsigned NumBits = VT.getSizeInBits();
9387 DebugLoc dl = Op.getDebugLoc();
9389 Op = Op.getOperand(0);
9390 if (VT == MVT::i8) {
9391 // Zero extend to i32 since there is not an i8 bsr.
9393 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9396 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9397 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9398 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9400 // If src is zero (i.e. bsr sets ZF), returns NumBits.
9403 DAG.getConstant(NumBits+NumBits-1, OpVT),
9404 DAG.getConstant(X86::COND_E, MVT::i8),
9407 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9409 // Finally xor with NumBits-1.
9410 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9413 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9417 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9418 EVT VT = Op.getValueType();
9420 unsigned NumBits = VT.getSizeInBits();
9421 DebugLoc dl = Op.getDebugLoc();
9423 Op = Op.getOperand(0);
9424 if (VT == MVT::i8) {
9426 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9429 // Issue a bsf (scan bits forward) which also sets EFLAGS.
9430 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9431 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9433 // If src is zero (i.e. bsf sets ZF), returns NumBits.
9436 DAG.getConstant(NumBits, OpVT),
9437 DAG.getConstant(X86::COND_E, MVT::i8),
9440 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9443 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9447 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9448 // ones, and then concatenate the result back.
9449 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9450 EVT VT = Op.getValueType();
9452 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9453 "Unsupported value type for operation");
9455 int NumElems = VT.getVectorNumElements();
9456 DebugLoc dl = Op.getDebugLoc();
9457 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9458 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9460 // Extract the LHS vectors
9461 SDValue LHS = Op.getOperand(0);
9462 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9463 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9465 // Extract the RHS vectors
9466 SDValue RHS = Op.getOperand(1);
9467 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9468 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9470 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9471 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9473 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9474 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9475 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9478 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9479 assert(Op.getValueType().getSizeInBits() == 256 &&
9480 Op.getValueType().isInteger() &&
9481 "Only handle AVX 256-bit vector integer operation");
9482 return Lower256IntArith(Op, DAG);
9485 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9486 assert(Op.getValueType().getSizeInBits() == 256 &&
9487 Op.getValueType().isInteger() &&
9488 "Only handle AVX 256-bit vector integer operation");
9489 return Lower256IntArith(Op, DAG);
9492 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9493 EVT VT = Op.getValueType();
9495 // Decompose 256-bit ops into smaller 128-bit ops.
9496 if (VT.getSizeInBits() == 256)
9497 return Lower256IntArith(Op, DAG);
9499 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9500 DebugLoc dl = Op.getDebugLoc();
9502 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9503 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9504 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9505 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9506 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9508 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9509 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9510 // return AloBlo + AloBhi + AhiBlo;
9512 SDValue A = Op.getOperand(0);
9513 SDValue B = Op.getOperand(1);
9515 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9516 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9517 A, DAG.getConstant(32, MVT::i32));
9518 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9519 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9520 B, DAG.getConstant(32, MVT::i32));
9521 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9522 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9524 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9525 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9527 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9528 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9530 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9531 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9532 AloBhi, DAG.getConstant(32, MVT::i32));
9533 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9534 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9535 AhiBlo, DAG.getConstant(32, MVT::i32));
9536 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9537 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9541 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
9543 EVT VT = Op.getValueType();
9544 DebugLoc dl = Op.getDebugLoc();
9545 SDValue R = Op.getOperand(0);
9546 SDValue Amt = Op.getOperand(1);
9547 LLVMContext *Context = DAG.getContext();
9549 if (!(Subtarget->hasSSE2() || Subtarget->hasAVX()))
9552 // Decompose 256-bit shifts into smaller 128-bit shifts.
9553 if (VT.getSizeInBits() == 256) {
9554 int NumElems = VT.getVectorNumElements();
9555 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9556 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9558 // Extract the two vectors
9559 SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
9560 SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
9563 // Recreate the shift amount vectors
9565 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
9566 // Constant shift amount
9567 SmallVector<SDValue, 4> Amt1Csts;
9568 SmallVector<SDValue, 4> Amt2Csts;
9569 for (int i = 0; i < NumElems/2; ++i)
9570 Amt1Csts.push_back(Amt->getOperand(i));
9571 for (int i = NumElems/2; i < NumElems; ++i)
9572 Amt2Csts.push_back(Amt->getOperand(i));
9574 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9575 &Amt1Csts[0], NumElems/2);
9576 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9577 &Amt2Csts[0], NumElems/2);
9579 // Variable shift amount
9580 Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
9581 Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
9585 // Issue new vector shifts for the smaller types
9586 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
9587 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
9589 // Concatenate the result back
9590 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
9593 // Optimize shl/srl/sra with constant shift amount.
9594 if (isSplatVector(Amt.getNode())) {
9595 SDValue SclrAmt = Amt->getOperand(0);
9596 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
9597 uint64_t ShiftAmt = C->getZExtValue();
9599 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
9600 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9601 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9602 R, DAG.getConstant(ShiftAmt, MVT::i32));
9604 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
9605 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9606 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9607 R, DAG.getConstant(ShiftAmt, MVT::i32));
9609 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
9610 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9611 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9612 R, DAG.getConstant(ShiftAmt, MVT::i32));
9614 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
9615 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9616 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9617 R, DAG.getConstant(ShiftAmt, MVT::i32));
9619 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
9620 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9621 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9622 R, DAG.getConstant(ShiftAmt, MVT::i32));
9624 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
9625 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9626 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9627 R, DAG.getConstant(ShiftAmt, MVT::i32));
9629 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
9630 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9631 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9632 R, DAG.getConstant(ShiftAmt, MVT::i32));
9634 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
9635 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9636 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9637 R, DAG.getConstant(ShiftAmt, MVT::i32));
9641 // Lower SHL with variable shift amount.
9642 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
9643 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9644 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9645 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
9647 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
9649 std::vector<Constant*> CV(4, CI);
9650 Constant *C = ConstantVector::get(CV);
9651 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9652 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9653 MachinePointerInfo::getConstantPool(),
9656 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
9657 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
9658 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9659 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9661 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9663 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9664 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9665 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9667 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
9668 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
9670 std::vector<Constant*> CVM1(16, CM1);
9671 std::vector<Constant*> CVM2(16, CM2);
9672 Constant *C = ConstantVector::get(CVM1);
9673 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9674 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9675 MachinePointerInfo::getConstantPool(),
9678 // r = pblendv(r, psllw(r & (char16)15, 4), a);
9679 M = DAG.getNode(ISD::AND, dl, VT, R, M);
9680 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9681 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9682 DAG.getConstant(4, MVT::i32));
9683 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9685 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9687 C = ConstantVector::get(CVM2);
9688 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9689 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9690 MachinePointerInfo::getConstantPool(),
9693 // r = pblendv(r, psllw(r & (char16)63, 2), a);
9694 M = DAG.getNode(ISD::AND, dl, VT, R, M);
9695 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9696 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9697 DAG.getConstant(2, MVT::i32));
9698 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9700 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9702 // return pblendv(r, r+r, a);
9703 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
9704 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
9710 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
9711 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
9712 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
9713 // looks for this combo and may remove the "setcc" instruction if the "setcc"
9714 // has only one use.
9715 SDNode *N = Op.getNode();
9716 SDValue LHS = N->getOperand(0);
9717 SDValue RHS = N->getOperand(1);
9718 unsigned BaseOp = 0;
9720 DebugLoc DL = Op.getDebugLoc();
9721 switch (Op.getOpcode()) {
9722 default: llvm_unreachable("Unknown ovf instruction!");
9724 // A subtract of one will be selected as a INC. Note that INC doesn't
9725 // set CF, so we can't do this for UADDO.
9726 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9728 BaseOp = X86ISD::INC;
9732 BaseOp = X86ISD::ADD;
9736 BaseOp = X86ISD::ADD;
9740 // A subtract of one will be selected as a DEC. Note that DEC doesn't
9741 // set CF, so we can't do this for USUBO.
9742 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9744 BaseOp = X86ISD::DEC;
9748 BaseOp = X86ISD::SUB;
9752 BaseOp = X86ISD::SUB;
9756 BaseOp = X86ISD::SMUL;
9759 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9760 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9762 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9765 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9766 DAG.getConstant(X86::COND_O, MVT::i32),
9767 SDValue(Sum.getNode(), 2));
9769 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
9773 // Also sets EFLAGS.
9774 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9775 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9778 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9779 DAG.getConstant(Cond, MVT::i32),
9780 SDValue(Sum.getNode(), 1));
9782 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
9785 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
9786 DebugLoc dl = Op.getDebugLoc();
9787 SDNode* Node = Op.getNode();
9788 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
9789 EVT VT = Node->getValueType(0);
9791 if (Subtarget->hasSSE2() && VT.isVector()) {
9792 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
9793 ExtraVT.getScalarType().getSizeInBits();
9794 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
9796 unsigned SHLIntrinsicsID = 0;
9797 unsigned SRAIntrinsicsID = 0;
9798 switch (VT.getSimpleVT().SimpleTy) {
9802 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q;
9803 SRAIntrinsicsID = 0;
9807 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
9808 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
9812 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
9813 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
9818 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9819 DAG.getConstant(SHLIntrinsicsID, MVT::i32),
9820 Node->getOperand(0), ShAmt);
9822 // In case of 1 bit sext, no need to shr
9823 if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
9825 if (SRAIntrinsicsID) {
9826 Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9827 DAG.getConstant(SRAIntrinsicsID, MVT::i32),
9837 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9838 DebugLoc dl = Op.getDebugLoc();
9840 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
9841 // There isn't any reason to disable it if the target processor supports it.
9842 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
9843 SDValue Chain = Op.getOperand(0);
9844 SDValue Zero = DAG.getConstant(0, MVT::i32);
9846 DAG.getRegister(X86::ESP, MVT::i32), // Base
9847 DAG.getTargetConstant(1, MVT::i8), // Scale
9848 DAG.getRegister(0, MVT::i32), // Index
9849 DAG.getTargetConstant(0, MVT::i32), // Disp
9850 DAG.getRegister(0, MVT::i32), // Segment.
9855 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9856 array_lengthof(Ops));
9857 return SDValue(Res, 0);
9860 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9862 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9864 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9865 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9866 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9867 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9869 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9870 if (!Op1 && !Op2 && !Op3 && Op4)
9871 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9873 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9874 if (Op1 && !Op2 && !Op3 && !Op4)
9875 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9877 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9879 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9882 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
9883 SelectionDAG &DAG) const {
9884 DebugLoc dl = Op.getDebugLoc();
9885 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
9886 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
9887 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
9888 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9890 // The only fence that needs an instruction is a sequentially-consistent
9891 // cross-thread fence.
9892 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
9893 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
9894 // no-sse2). There isn't any reason to disable it if the target processor
9896 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
9897 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9899 SDValue Chain = Op.getOperand(0);
9900 SDValue Zero = DAG.getConstant(0, MVT::i32);
9902 DAG.getRegister(X86::ESP, MVT::i32), // Base
9903 DAG.getTargetConstant(1, MVT::i8), // Scale
9904 DAG.getRegister(0, MVT::i32), // Index
9905 DAG.getTargetConstant(0, MVT::i32), // Disp
9906 DAG.getRegister(0, MVT::i32), // Segment.
9911 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9912 array_lengthof(Ops));
9913 return SDValue(Res, 0);
9916 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
9917 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9921 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9922 EVT T = Op.getValueType();
9923 DebugLoc DL = Op.getDebugLoc();
9926 switch(T.getSimpleVT().SimpleTy) {
9928 assert(false && "Invalid value type!");
9929 case MVT::i8: Reg = X86::AL; size = 1; break;
9930 case MVT::i16: Reg = X86::AX; size = 2; break;
9931 case MVT::i32: Reg = X86::EAX; size = 4; break;
9933 assert(Subtarget->is64Bit() && "Node not type legal!");
9934 Reg = X86::RAX; size = 8;
9937 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9938 Op.getOperand(2), SDValue());
9939 SDValue Ops[] = { cpIn.getValue(0),
9942 DAG.getTargetConstant(size, MVT::i8),
9944 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9945 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9946 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9949 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9953 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9954 SelectionDAG &DAG) const {
9955 assert(Subtarget->is64Bit() && "Result not type legalized?");
9956 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9957 SDValue TheChain = Op.getOperand(0);
9958 DebugLoc dl = Op.getDebugLoc();
9959 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9960 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9961 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9963 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9964 DAG.getConstant(32, MVT::i8));
9966 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9969 return DAG.getMergeValues(Ops, 2, dl);
9972 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9973 SelectionDAG &DAG) const {
9974 EVT SrcVT = Op.getOperand(0).getValueType();
9975 EVT DstVT = Op.getValueType();
9976 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9977 Subtarget->hasMMX() && "Unexpected custom BITCAST");
9978 assert((DstVT == MVT::i64 ||
9979 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9980 "Unexpected custom BITCAST");
9981 // i64 <=> MMX conversions are Legal.
9982 if (SrcVT==MVT::i64 && DstVT.isVector())
9984 if (DstVT==MVT::i64 && SrcVT.isVector())
9986 // MMX <=> MMX conversions are Legal.
9987 if (SrcVT.isVector() && DstVT.isVector())
9989 // All other conversions need to be expanded.
9993 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9994 SDNode *Node = Op.getNode();
9995 DebugLoc dl = Node->getDebugLoc();
9996 EVT T = Node->getValueType(0);
9997 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9998 DAG.getConstant(0, T), Node->getOperand(2));
9999 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10000 cast<AtomicSDNode>(Node)->getMemoryVT(),
10001 Node->getOperand(0),
10002 Node->getOperand(1), negOp,
10003 cast<AtomicSDNode>(Node)->getSrcValue(),
10004 cast<AtomicSDNode>(Node)->getAlignment(),
10005 cast<AtomicSDNode>(Node)->getOrdering(),
10006 cast<AtomicSDNode>(Node)->getSynchScope());
10009 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10010 SDNode *Node = Op.getNode();
10011 DebugLoc dl = Node->getDebugLoc();
10012 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10014 // Convert seq_cst store -> xchg
10015 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10016 // FIXME: On 32-bit, store -> fist or movq would be more efficient
10017 // (The only way to get a 16-byte store is cmpxchg16b)
10018 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10019 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10020 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10021 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10022 cast<AtomicSDNode>(Node)->getMemoryVT(),
10023 Node->getOperand(0),
10024 Node->getOperand(1), Node->getOperand(2),
10025 cast<AtomicSDNode>(Node)->getMemOperand(),
10026 cast<AtomicSDNode>(Node)->getOrdering(),
10027 cast<AtomicSDNode>(Node)->getSynchScope());
10028 return Swap.getValue(1);
10030 // Other atomic stores have a simple pattern.
10034 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10035 EVT VT = Op.getNode()->getValueType(0);
10037 // Let legalize expand this if it isn't a legal type yet.
10038 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10041 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10044 bool ExtraOp = false;
10045 switch (Op.getOpcode()) {
10046 default: assert(0 && "Invalid code");
10047 case ISD::ADDC: Opc = X86ISD::ADD; break;
10048 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10049 case ISD::SUBC: Opc = X86ISD::SUB; break;
10050 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10054 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10056 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10057 Op.getOperand(1), Op.getOperand(2));
10060 /// LowerOperation - Provide custom lowering hooks for some operations.
10062 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10063 switch (Op.getOpcode()) {
10064 default: llvm_unreachable("Should not custom lower this!");
10065 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10066 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10067 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10068 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10069 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10070 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
10071 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10072 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10073 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10074 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10075 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10076 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10077 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10078 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10079 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10080 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10081 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10082 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10083 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10084 case ISD::SHL_PARTS:
10085 case ISD::SRA_PARTS:
10086 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
10087 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
10088 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
10089 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
10090 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
10091 case ISD::FABS: return LowerFABS(Op, DAG);
10092 case ISD::FNEG: return LowerFNEG(Op, DAG);
10093 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10094 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
10095 case ISD::SETCC: return LowerSETCC(Op, DAG);
10096 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
10097 case ISD::SELECT: return LowerSELECT(Op, DAG);
10098 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10099 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
10100 case ISD::VASTART: return LowerVASTART(Op, DAG);
10101 case ISD::VAARG: return LowerVAARG(Op, DAG);
10102 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
10103 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10104 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10105 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10106 case ISD::FRAME_TO_ARGS_OFFSET:
10107 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10108 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10109 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
10110 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
10111 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10112 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
10113 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
10114 case ISD::MUL: return LowerMUL(Op, DAG);
10117 case ISD::SHL: return LowerShift(Op, DAG);
10123 case ISD::UMULO: return LowerXALUO(Op, DAG);
10124 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
10125 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
10129 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10130 case ISD::ADD: return LowerADD(Op, DAG);
10131 case ISD::SUB: return LowerSUB(Op, DAG);
10135 static void ReplaceATOMIC_LOAD(SDNode *Node,
10136 SmallVectorImpl<SDValue> &Results,
10137 SelectionDAG &DAG) {
10138 DebugLoc dl = Node->getDebugLoc();
10139 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10141 // Convert wide load -> cmpxchg8b/cmpxchg16b
10142 // FIXME: On 32-bit, load -> fild or movq would be more efficient
10143 // (The only way to get a 16-byte load is cmpxchg16b)
10144 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10145 SDValue Zero = DAG.getConstant(0, cast<AtomicSDNode>(Node)->getMemoryVT());
10146 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl,
10147 cast<AtomicSDNode>(Node)->getMemoryVT(),
10148 Node->getOperand(0),
10149 Node->getOperand(1), Zero, Zero,
10150 cast<AtomicSDNode>(Node)->getMemOperand(),
10151 cast<AtomicSDNode>(Node)->getOrdering(),
10152 cast<AtomicSDNode>(Node)->getSynchScope());
10153 Results.push_back(Swap.getValue(0));
10154 Results.push_back(Swap.getValue(1));
10157 void X86TargetLowering::
10158 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10159 SelectionDAG &DAG, unsigned NewOp) const {
10160 EVT T = Node->getValueType(0);
10161 DebugLoc dl = Node->getDebugLoc();
10162 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
10164 SDValue Chain = Node->getOperand(0);
10165 SDValue In1 = Node->getOperand(1);
10166 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10167 Node->getOperand(2), DAG.getIntPtrConstant(0));
10168 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10169 Node->getOperand(2), DAG.getIntPtrConstant(1));
10170 SDValue Ops[] = { Chain, In1, In2L, In2H };
10171 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10173 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10174 cast<MemSDNode>(Node)->getMemOperand());
10175 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10176 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10177 Results.push_back(Result.getValue(2));
10180 /// ReplaceNodeResults - Replace a node with an illegal result type
10181 /// with a new node built out of custom code.
10182 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10183 SmallVectorImpl<SDValue>&Results,
10184 SelectionDAG &DAG) const {
10185 DebugLoc dl = N->getDebugLoc();
10186 switch (N->getOpcode()) {
10188 assert(false && "Do not know how to custom type legalize this operation!");
10190 case ISD::SIGN_EXTEND_INREG:
10195 // We don't want to expand or promote these.
10197 case ISD::FP_TO_SINT: {
10198 std::pair<SDValue,SDValue> Vals =
10199 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10200 SDValue FIST = Vals.first, StackSlot = Vals.second;
10201 if (FIST.getNode() != 0) {
10202 EVT VT = N->getValueType(0);
10203 // Return a load from the stack slot.
10204 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10205 MachinePointerInfo(), false, false, 0));
10209 case ISD::READCYCLECOUNTER: {
10210 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10211 SDValue TheChain = N->getOperand(0);
10212 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10213 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10215 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10217 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10218 SDValue Ops[] = { eax, edx };
10219 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10220 Results.push_back(edx.getValue(1));
10223 case ISD::ATOMIC_CMP_SWAP: {
10224 EVT T = N->getValueType(0);
10225 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
10226 SDValue cpInL, cpInH;
10227 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
10228 DAG.getConstant(0, MVT::i32));
10229 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
10230 DAG.getConstant(1, MVT::i32));
10231 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
10232 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
10233 cpInL.getValue(1));
10234 SDValue swapInL, swapInH;
10235 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
10236 DAG.getConstant(0, MVT::i32));
10237 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
10238 DAG.getConstant(1, MVT::i32));
10239 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
10240 cpInH.getValue(1));
10241 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
10242 swapInL.getValue(1));
10243 SDValue Ops[] = { swapInH.getValue(0),
10245 swapInH.getValue(1) };
10246 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10247 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10248 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
10250 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
10251 MVT::i32, Result.getValue(1));
10252 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
10253 MVT::i32, cpOutL.getValue(2));
10254 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10255 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10256 Results.push_back(cpOutH.getValue(1));
10259 case ISD::ATOMIC_LOAD_ADD:
10260 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10262 case ISD::ATOMIC_LOAD_AND:
10263 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10265 case ISD::ATOMIC_LOAD_NAND:
10266 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10268 case ISD::ATOMIC_LOAD_OR:
10269 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10271 case ISD::ATOMIC_LOAD_SUB:
10272 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10274 case ISD::ATOMIC_LOAD_XOR:
10275 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10277 case ISD::ATOMIC_SWAP:
10278 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10280 case ISD::ATOMIC_LOAD:
10281 ReplaceATOMIC_LOAD(N, Results, DAG);
10285 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10287 default: return NULL;
10288 case X86ISD::BSF: return "X86ISD::BSF";
10289 case X86ISD::BSR: return "X86ISD::BSR";
10290 case X86ISD::SHLD: return "X86ISD::SHLD";
10291 case X86ISD::SHRD: return "X86ISD::SHRD";
10292 case X86ISD::FAND: return "X86ISD::FAND";
10293 case X86ISD::FOR: return "X86ISD::FOR";
10294 case X86ISD::FXOR: return "X86ISD::FXOR";
10295 case X86ISD::FSRL: return "X86ISD::FSRL";
10296 case X86ISD::FILD: return "X86ISD::FILD";
10297 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
10298 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10299 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10300 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10301 case X86ISD::FLD: return "X86ISD::FLD";
10302 case X86ISD::FST: return "X86ISD::FST";
10303 case X86ISD::CALL: return "X86ISD::CALL";
10304 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
10305 case X86ISD::BT: return "X86ISD::BT";
10306 case X86ISD::CMP: return "X86ISD::CMP";
10307 case X86ISD::COMI: return "X86ISD::COMI";
10308 case X86ISD::UCOMI: return "X86ISD::UCOMI";
10309 case X86ISD::SETCC: return "X86ISD::SETCC";
10310 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
10311 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
10312 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
10313 case X86ISD::CMOV: return "X86ISD::CMOV";
10314 case X86ISD::BRCOND: return "X86ISD::BRCOND";
10315 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
10316 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
10317 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
10318 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
10319 case X86ISD::Wrapper: return "X86ISD::Wrapper";
10320 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
10321 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
10322 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
10323 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
10324 case X86ISD::PINSRB: return "X86ISD::PINSRB";
10325 case X86ISD::PINSRW: return "X86ISD::PINSRW";
10326 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
10327 case X86ISD::ANDNP: return "X86ISD::ANDNP";
10328 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
10329 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
10330 case X86ISD::PSIGND: return "X86ISD::PSIGND";
10331 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB";
10332 case X86ISD::FMAX: return "X86ISD::FMAX";
10333 case X86ISD::FMIN: return "X86ISD::FMIN";
10334 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
10335 case X86ISD::FRCP: return "X86ISD::FRCP";
10336 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
10337 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
10338 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
10339 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
10340 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
10341 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
10342 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
10343 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
10344 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
10345 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
10346 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
10347 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
10348 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
10349 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
10350 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
10351 case X86ISD::VSHL: return "X86ISD::VSHL";
10352 case X86ISD::VSRL: return "X86ISD::VSRL";
10353 case X86ISD::CMPPD: return "X86ISD::CMPPD";
10354 case X86ISD::CMPPS: return "X86ISD::CMPPS";
10355 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
10356 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
10357 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
10358 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
10359 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
10360 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
10361 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
10362 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
10363 case X86ISD::ADD: return "X86ISD::ADD";
10364 case X86ISD::SUB: return "X86ISD::SUB";
10365 case X86ISD::ADC: return "X86ISD::ADC";
10366 case X86ISD::SBB: return "X86ISD::SBB";
10367 case X86ISD::SMUL: return "X86ISD::SMUL";
10368 case X86ISD::UMUL: return "X86ISD::UMUL";
10369 case X86ISD::INC: return "X86ISD::INC";
10370 case X86ISD::DEC: return "X86ISD::DEC";
10371 case X86ISD::OR: return "X86ISD::OR";
10372 case X86ISD::XOR: return "X86ISD::XOR";
10373 case X86ISD::AND: return "X86ISD::AND";
10374 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
10375 case X86ISD::PTEST: return "X86ISD::PTEST";
10376 case X86ISD::TESTP: return "X86ISD::TESTP";
10377 case X86ISD::PALIGN: return "X86ISD::PALIGN";
10378 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
10379 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
10380 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
10381 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
10382 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
10383 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
10384 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
10385 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
10386 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
10387 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
10388 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
10389 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
10390 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
10391 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
10392 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
10393 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
10394 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
10395 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
10396 case X86ISD::MOVSD: return "X86ISD::MOVSD";
10397 case X86ISD::MOVSS: return "X86ISD::MOVSS";
10398 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
10399 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
10400 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
10401 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
10402 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
10403 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
10404 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
10405 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
10406 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
10407 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
10408 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
10409 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
10410 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
10411 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
10412 case X86ISD::VPERMILPS: return "X86ISD::VPERMILPS";
10413 case X86ISD::VPERMILPSY: return "X86ISD::VPERMILPSY";
10414 case X86ISD::VPERMILPD: return "X86ISD::VPERMILPD";
10415 case X86ISD::VPERMILPDY: return "X86ISD::VPERMILPDY";
10416 case X86ISD::VPERM2F128: return "X86ISD::VPERM2F128";
10417 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10418 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
10419 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
10420 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
10424 // isLegalAddressingMode - Return true if the addressing mode represented
10425 // by AM is legal for this target, for a load/store of the specified type.
10426 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10428 // X86 supports extremely general addressing modes.
10429 CodeModel::Model M = getTargetMachine().getCodeModel();
10430 Reloc::Model R = getTargetMachine().getRelocationModel();
10432 // X86 allows a sign-extended 32-bit immediate field as a displacement.
10433 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10438 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10440 // If a reference to this global requires an extra load, we can't fold it.
10441 if (isGlobalStubReference(GVFlags))
10444 // If BaseGV requires a register for the PIC base, we cannot also have a
10445 // BaseReg specified.
10446 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
10449 // If lower 4G is not available, then we must use rip-relative addressing.
10450 if ((M != CodeModel::Small || R != Reloc::Static) &&
10451 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
10455 switch (AM.Scale) {
10461 // These scales always work.
10466 // These scales are formed with basereg+scalereg. Only accept if there is
10471 default: // Other stuff never works.
10479 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10480 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10482 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10483 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10484 if (NumBits1 <= NumBits2)
10489 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10490 if (!VT1.isInteger() || !VT2.isInteger())
10492 unsigned NumBits1 = VT1.getSizeInBits();
10493 unsigned NumBits2 = VT2.getSizeInBits();
10494 if (NumBits1 <= NumBits2)
10499 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
10500 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10501 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
10504 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
10505 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10506 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
10509 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
10510 // i16 instructions are longer (0x66 prefix) and potentially slower.
10511 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
10514 /// isShuffleMaskLegal - Targets can use this to indicate that they only
10515 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
10516 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
10517 /// are assumed to be legal.
10519 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
10521 // Very little shuffling can be done for 64-bit vectors right now.
10522 if (VT.getSizeInBits() == 64)
10523 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
10525 // FIXME: pshufb, blends, shifts.
10526 return (VT.getVectorNumElements() == 2 ||
10527 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
10528 isMOVLMask(M, VT) ||
10529 isSHUFPMask(M, VT) ||
10530 isPSHUFDMask(M, VT) ||
10531 isPSHUFHWMask(M, VT) ||
10532 isPSHUFLWMask(M, VT) ||
10533 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
10534 isUNPCKLMask(M, VT) ||
10535 isUNPCKHMask(M, VT) ||
10536 isUNPCKL_v_undef_Mask(M, VT) ||
10537 isUNPCKH_v_undef_Mask(M, VT));
10541 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
10543 unsigned NumElts = VT.getVectorNumElements();
10544 // FIXME: This collection of masks seems suspect.
10547 if (NumElts == 4 && VT.getSizeInBits() == 128) {
10548 return (isMOVLMask(Mask, VT) ||
10549 isCommutedMOVLMask(Mask, VT, true) ||
10550 isSHUFPMask(Mask, VT) ||
10551 isCommutedSHUFPMask(Mask, VT));
10556 //===----------------------------------------------------------------------===//
10557 // X86 Scheduler Hooks
10558 //===----------------------------------------------------------------------===//
10560 // private utility function
10561 MachineBasicBlock *
10562 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
10563 MachineBasicBlock *MBB,
10570 TargetRegisterClass *RC,
10571 bool invSrc) const {
10572 // For the atomic bitwise operator, we generate
10575 // ld t1 = [bitinstr.addr]
10576 // op t2 = t1, [bitinstr.val]
10578 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
10580 // fallthrough -->nextMBB
10581 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10582 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10583 MachineFunction::iterator MBBIter = MBB;
10586 /// First build the CFG
10587 MachineFunction *F = MBB->getParent();
10588 MachineBasicBlock *thisMBB = MBB;
10589 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10590 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10591 F->insert(MBBIter, newMBB);
10592 F->insert(MBBIter, nextMBB);
10594 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10595 nextMBB->splice(nextMBB->begin(), thisMBB,
10596 llvm::next(MachineBasicBlock::iterator(bInstr)),
10598 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10600 // Update thisMBB to fall through to newMBB
10601 thisMBB->addSuccessor(newMBB);
10603 // newMBB jumps to itself and fall through to nextMBB
10604 newMBB->addSuccessor(nextMBB);
10605 newMBB->addSuccessor(newMBB);
10607 // Insert instructions into newMBB based on incoming instruction
10608 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10609 "unexpected number of operands");
10610 DebugLoc dl = bInstr->getDebugLoc();
10611 MachineOperand& destOper = bInstr->getOperand(0);
10612 MachineOperand* argOpers[2 + X86::AddrNumOperands];
10613 int numArgs = bInstr->getNumOperands() - 1;
10614 for (int i=0; i < numArgs; ++i)
10615 argOpers[i] = &bInstr->getOperand(i+1);
10617 // x86 address has 4 operands: base, index, scale, and displacement
10618 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10619 int valArgIndx = lastAddrIndx + 1;
10621 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10622 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
10623 for (int i=0; i <= lastAddrIndx; ++i)
10624 (*MIB).addOperand(*argOpers[i]);
10626 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
10628 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
10633 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10634 assert((argOpers[valArgIndx]->isReg() ||
10635 argOpers[valArgIndx]->isImm()) &&
10636 "invalid operand");
10637 if (argOpers[valArgIndx]->isReg())
10638 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
10640 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
10642 (*MIB).addOperand(*argOpers[valArgIndx]);
10644 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
10647 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
10648 for (int i=0; i <= lastAddrIndx; ++i)
10649 (*MIB).addOperand(*argOpers[i]);
10651 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10652 (*MIB).setMemRefs(bInstr->memoperands_begin(),
10653 bInstr->memoperands_end());
10655 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10656 MIB.addReg(EAXreg);
10659 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10661 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
10665 // private utility function: 64 bit atomics on 32 bit host.
10666 MachineBasicBlock *
10667 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
10668 MachineBasicBlock *MBB,
10673 bool invSrc) const {
10674 // For the atomic bitwise operator, we generate
10675 // thisMBB (instructions are in pairs, except cmpxchg8b)
10676 // ld t1,t2 = [bitinstr.addr]
10678 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
10679 // op t5, t6 <- out1, out2, [bitinstr.val]
10680 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
10681 // mov ECX, EBX <- t5, t6
10682 // mov EAX, EDX <- t1, t2
10683 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
10684 // mov t3, t4 <- EAX, EDX
10686 // result in out1, out2
10687 // fallthrough -->nextMBB
10689 const TargetRegisterClass *RC = X86::GR32RegisterClass;
10690 const unsigned LoadOpc = X86::MOV32rm;
10691 const unsigned NotOpc = X86::NOT32r;
10692 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10693 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10694 MachineFunction::iterator MBBIter = MBB;
10697 /// First build the CFG
10698 MachineFunction *F = MBB->getParent();
10699 MachineBasicBlock *thisMBB = MBB;
10700 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10701 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10702 F->insert(MBBIter, newMBB);
10703 F->insert(MBBIter, nextMBB);
10705 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10706 nextMBB->splice(nextMBB->begin(), thisMBB,
10707 llvm::next(MachineBasicBlock::iterator(bInstr)),
10709 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10711 // Update thisMBB to fall through to newMBB
10712 thisMBB->addSuccessor(newMBB);
10714 // newMBB jumps to itself and fall through to nextMBB
10715 newMBB->addSuccessor(nextMBB);
10716 newMBB->addSuccessor(newMBB);
10718 DebugLoc dl = bInstr->getDebugLoc();
10719 // Insert instructions into newMBB based on incoming instruction
10720 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
10721 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
10722 "unexpected number of operands");
10723 MachineOperand& dest1Oper = bInstr->getOperand(0);
10724 MachineOperand& dest2Oper = bInstr->getOperand(1);
10725 MachineOperand* argOpers[2 + X86::AddrNumOperands];
10726 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
10727 argOpers[i] = &bInstr->getOperand(i+2);
10729 // We use some of the operands multiple times, so conservatively just
10730 // clear any kill flags that might be present.
10731 if (argOpers[i]->isReg() && argOpers[i]->isUse())
10732 argOpers[i]->setIsKill(false);
10735 // x86 address has 5 operands: base, index, scale, displacement, and segment.
10736 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10738 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10739 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
10740 for (int i=0; i <= lastAddrIndx; ++i)
10741 (*MIB).addOperand(*argOpers[i]);
10742 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10743 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
10744 // add 4 to displacement.
10745 for (int i=0; i <= lastAddrIndx-2; ++i)
10746 (*MIB).addOperand(*argOpers[i]);
10747 MachineOperand newOp3 = *(argOpers[3]);
10748 if (newOp3.isImm())
10749 newOp3.setImm(newOp3.getImm()+4);
10751 newOp3.setOffset(newOp3.getOffset()+4);
10752 (*MIB).addOperand(newOp3);
10753 (*MIB).addOperand(*argOpers[lastAddrIndx]);
10755 // t3/4 are defined later, at the bottom of the loop
10756 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
10757 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
10758 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
10759 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
10760 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
10761 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
10763 // The subsequent operations should be using the destination registers of
10764 //the PHI instructions.
10766 t1 = F->getRegInfo().createVirtualRegister(RC);
10767 t2 = F->getRegInfo().createVirtualRegister(RC);
10768 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
10769 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
10771 t1 = dest1Oper.getReg();
10772 t2 = dest2Oper.getReg();
10775 int valArgIndx = lastAddrIndx + 1;
10776 assert((argOpers[valArgIndx]->isReg() ||
10777 argOpers[valArgIndx]->isImm()) &&
10778 "invalid operand");
10779 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
10780 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
10781 if (argOpers[valArgIndx]->isReg())
10782 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
10784 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
10785 if (regOpcL != X86::MOV32rr)
10787 (*MIB).addOperand(*argOpers[valArgIndx]);
10788 assert(argOpers[valArgIndx + 1]->isReg() ==
10789 argOpers[valArgIndx]->isReg());
10790 assert(argOpers[valArgIndx + 1]->isImm() ==
10791 argOpers[valArgIndx]->isImm());
10792 if (argOpers[valArgIndx + 1]->isReg())
10793 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
10795 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
10796 if (regOpcH != X86::MOV32rr)
10798 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
10800 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10802 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
10805 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
10807 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
10810 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
10811 for (int i=0; i <= lastAddrIndx; ++i)
10812 (*MIB).addOperand(*argOpers[i]);
10814 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10815 (*MIB).setMemRefs(bInstr->memoperands_begin(),
10816 bInstr->memoperands_end());
10818 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
10819 MIB.addReg(X86::EAX);
10820 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
10821 MIB.addReg(X86::EDX);
10824 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10826 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
10830 // private utility function
10831 MachineBasicBlock *
10832 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
10833 MachineBasicBlock *MBB,
10834 unsigned cmovOpc) const {
10835 // For the atomic min/max operator, we generate
10838 // ld t1 = [min/max.addr]
10839 // mov t2 = [min/max.val]
10841 // cmov[cond] t2 = t1
10843 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
10845 // fallthrough -->nextMBB
10847 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10848 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10849 MachineFunction::iterator MBBIter = MBB;
10852 /// First build the CFG
10853 MachineFunction *F = MBB->getParent();
10854 MachineBasicBlock *thisMBB = MBB;
10855 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10856 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10857 F->insert(MBBIter, newMBB);
10858 F->insert(MBBIter, nextMBB);
10860 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10861 nextMBB->splice(nextMBB->begin(), thisMBB,
10862 llvm::next(MachineBasicBlock::iterator(mInstr)),
10864 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10866 // Update thisMBB to fall through to newMBB
10867 thisMBB->addSuccessor(newMBB);
10869 // newMBB jumps to newMBB and fall through to nextMBB
10870 newMBB->addSuccessor(nextMBB);
10871 newMBB->addSuccessor(newMBB);
10873 DebugLoc dl = mInstr->getDebugLoc();
10874 // Insert instructions into newMBB based on incoming instruction
10875 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10876 "unexpected number of operands");
10877 MachineOperand& destOper = mInstr->getOperand(0);
10878 MachineOperand* argOpers[2 + X86::AddrNumOperands];
10879 int numArgs = mInstr->getNumOperands() - 1;
10880 for (int i=0; i < numArgs; ++i)
10881 argOpers[i] = &mInstr->getOperand(i+1);
10883 // x86 address has 4 operands: base, index, scale, and displacement
10884 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10885 int valArgIndx = lastAddrIndx + 1;
10887 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10888 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10889 for (int i=0; i <= lastAddrIndx; ++i)
10890 (*MIB).addOperand(*argOpers[i]);
10892 // We only support register and immediate values
10893 assert((argOpers[valArgIndx]->isReg() ||
10894 argOpers[valArgIndx]->isImm()) &&
10895 "invalid operand");
10897 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10898 if (argOpers[valArgIndx]->isReg())
10899 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10901 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10902 (*MIB).addOperand(*argOpers[valArgIndx]);
10904 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10907 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10912 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10913 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10917 // Cmp and exchange if none has modified the memory location
10918 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10919 for (int i=0; i <= lastAddrIndx; ++i)
10920 (*MIB).addOperand(*argOpers[i]);
10922 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10923 (*MIB).setMemRefs(mInstr->memoperands_begin(),
10924 mInstr->memoperands_end());
10926 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10927 MIB.addReg(X86::EAX);
10930 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10932 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
10936 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10937 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10938 // in the .td file.
10939 MachineBasicBlock *
10940 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10941 unsigned numArgs, bool memArg) const {
10942 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10943 "Target must have SSE4.2 or AVX features enabled");
10945 DebugLoc dl = MI->getDebugLoc();
10946 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10948 if (!Subtarget->hasAVX()) {
10950 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10952 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10955 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10957 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10960 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10961 for (unsigned i = 0; i < numArgs; ++i) {
10962 MachineOperand &Op = MI->getOperand(i+1);
10963 if (!(Op.isReg() && Op.isImplicit()))
10964 MIB.addOperand(Op);
10966 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10967 .addReg(X86::XMM0);
10969 MI->eraseFromParent();
10973 MachineBasicBlock *
10974 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10975 DebugLoc dl = MI->getDebugLoc();
10976 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10978 // Address into RAX/EAX, other two args into ECX, EDX.
10979 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10980 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10981 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10982 for (int i = 0; i < X86::AddrNumOperands; ++i)
10983 MIB.addOperand(MI->getOperand(i));
10985 unsigned ValOps = X86::AddrNumOperands;
10986 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10987 .addReg(MI->getOperand(ValOps).getReg());
10988 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10989 .addReg(MI->getOperand(ValOps+1).getReg());
10991 // The instruction doesn't actually take any operands though.
10992 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10994 MI->eraseFromParent(); // The pseudo is gone now.
10998 MachineBasicBlock *
10999 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11000 DebugLoc dl = MI->getDebugLoc();
11001 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11003 // First arg in ECX, the second in EAX.
11004 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11005 .addReg(MI->getOperand(0).getReg());
11006 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11007 .addReg(MI->getOperand(1).getReg());
11009 // The instruction doesn't actually take any operands though.
11010 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11012 MI->eraseFromParent(); // The pseudo is gone now.
11016 MachineBasicBlock *
11017 X86TargetLowering::EmitVAARG64WithCustomInserter(
11019 MachineBasicBlock *MBB) const {
11020 // Emit va_arg instruction on X86-64.
11022 // Operands to this pseudo-instruction:
11023 // 0 ) Output : destination address (reg)
11024 // 1-5) Input : va_list address (addr, i64mem)
11025 // 6 ) ArgSize : Size (in bytes) of vararg type
11026 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11027 // 8 ) Align : Alignment of type
11028 // 9 ) EFLAGS (implicit-def)
11030 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11031 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11033 unsigned DestReg = MI->getOperand(0).getReg();
11034 MachineOperand &Base = MI->getOperand(1);
11035 MachineOperand &Scale = MI->getOperand(2);
11036 MachineOperand &Index = MI->getOperand(3);
11037 MachineOperand &Disp = MI->getOperand(4);
11038 MachineOperand &Segment = MI->getOperand(5);
11039 unsigned ArgSize = MI->getOperand(6).getImm();
11040 unsigned ArgMode = MI->getOperand(7).getImm();
11041 unsigned Align = MI->getOperand(8).getImm();
11043 // Memory Reference
11044 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11045 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11046 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11048 // Machine Information
11049 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11050 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11051 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11052 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11053 DebugLoc DL = MI->getDebugLoc();
11055 // struct va_list {
11058 // i64 overflow_area (address)
11059 // i64 reg_save_area (address)
11061 // sizeof(va_list) = 24
11062 // alignment(va_list) = 8
11064 unsigned TotalNumIntRegs = 6;
11065 unsigned TotalNumXMMRegs = 8;
11066 bool UseGPOffset = (ArgMode == 1);
11067 bool UseFPOffset = (ArgMode == 2);
11068 unsigned MaxOffset = TotalNumIntRegs * 8 +
11069 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11071 /* Align ArgSize to a multiple of 8 */
11072 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11073 bool NeedsAlign = (Align > 8);
11075 MachineBasicBlock *thisMBB = MBB;
11076 MachineBasicBlock *overflowMBB;
11077 MachineBasicBlock *offsetMBB;
11078 MachineBasicBlock *endMBB;
11080 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
11081 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
11082 unsigned OffsetReg = 0;
11084 if (!UseGPOffset && !UseFPOffset) {
11085 // If we only pull from the overflow region, we don't create a branch.
11086 // We don't need to alter control flow.
11087 OffsetDestReg = 0; // unused
11088 OverflowDestReg = DestReg;
11091 overflowMBB = thisMBB;
11094 // First emit code to check if gp_offset (or fp_offset) is below the bound.
11095 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11096 // If not, pull from overflow_area. (branch to overflowMBB)
11101 // offsetMBB overflowMBB
11106 // Registers for the PHI in endMBB
11107 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11108 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11110 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11111 MachineFunction *MF = MBB->getParent();
11112 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11113 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11114 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11116 MachineFunction::iterator MBBIter = MBB;
11119 // Insert the new basic blocks
11120 MF->insert(MBBIter, offsetMBB);
11121 MF->insert(MBBIter, overflowMBB);
11122 MF->insert(MBBIter, endMBB);
11124 // Transfer the remainder of MBB and its successor edges to endMBB.
11125 endMBB->splice(endMBB->begin(), thisMBB,
11126 llvm::next(MachineBasicBlock::iterator(MI)),
11128 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11130 // Make offsetMBB and overflowMBB successors of thisMBB
11131 thisMBB->addSuccessor(offsetMBB);
11132 thisMBB->addSuccessor(overflowMBB);
11134 // endMBB is a successor of both offsetMBB and overflowMBB
11135 offsetMBB->addSuccessor(endMBB);
11136 overflowMBB->addSuccessor(endMBB);
11138 // Load the offset value into a register
11139 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11140 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11144 .addDisp(Disp, UseFPOffset ? 4 : 0)
11145 .addOperand(Segment)
11146 .setMemRefs(MMOBegin, MMOEnd);
11148 // Check if there is enough room left to pull this argument.
11149 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11151 .addImm(MaxOffset + 8 - ArgSizeA8);
11153 // Branch to "overflowMBB" if offset >= max
11154 // Fall through to "offsetMBB" otherwise
11155 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11156 .addMBB(overflowMBB);
11159 // In offsetMBB, emit code to use the reg_save_area.
11161 assert(OffsetReg != 0);
11163 // Read the reg_save_area address.
11164 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11165 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11170 .addOperand(Segment)
11171 .setMemRefs(MMOBegin, MMOEnd);
11173 // Zero-extend the offset
11174 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11175 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11178 .addImm(X86::sub_32bit);
11180 // Add the offset to the reg_save_area to get the final address.
11181 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11182 .addReg(OffsetReg64)
11183 .addReg(RegSaveReg);
11185 // Compute the offset for the next argument
11186 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11187 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11189 .addImm(UseFPOffset ? 16 : 8);
11191 // Store it back into the va_list.
11192 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11196 .addDisp(Disp, UseFPOffset ? 4 : 0)
11197 .addOperand(Segment)
11198 .addReg(NextOffsetReg)
11199 .setMemRefs(MMOBegin, MMOEnd);
11202 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11207 // Emit code to use overflow area
11210 // Load the overflow_area address into a register.
11211 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11212 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11217 .addOperand(Segment)
11218 .setMemRefs(MMOBegin, MMOEnd);
11220 // If we need to align it, do so. Otherwise, just copy the address
11221 // to OverflowDestReg.
11223 // Align the overflow address
11224 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11225 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11227 // aligned_addr = (addr + (align-1)) & ~(align-1)
11228 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11229 .addReg(OverflowAddrReg)
11232 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11234 .addImm(~(uint64_t)(Align-1));
11236 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11237 .addReg(OverflowAddrReg);
11240 // Compute the next overflow address after this argument.
11241 // (the overflow address should be kept 8-byte aligned)
11242 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11243 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11244 .addReg(OverflowDestReg)
11245 .addImm(ArgSizeA8);
11247 // Store the new overflow address.
11248 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11253 .addOperand(Segment)
11254 .addReg(NextAddrReg)
11255 .setMemRefs(MMOBegin, MMOEnd);
11257 // If we branched, emit the PHI to the front of endMBB.
11259 BuildMI(*endMBB, endMBB->begin(), DL,
11260 TII->get(X86::PHI), DestReg)
11261 .addReg(OffsetDestReg).addMBB(offsetMBB)
11262 .addReg(OverflowDestReg).addMBB(overflowMBB);
11265 // Erase the pseudo instruction
11266 MI->eraseFromParent();
11271 MachineBasicBlock *
11272 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11274 MachineBasicBlock *MBB) const {
11275 // Emit code to save XMM registers to the stack. The ABI says that the
11276 // number of registers to save is given in %al, so it's theoretically
11277 // possible to do an indirect jump trick to avoid saving all of them,
11278 // however this code takes a simpler approach and just executes all
11279 // of the stores if %al is non-zero. It's less code, and it's probably
11280 // easier on the hardware branch predictor, and stores aren't all that
11281 // expensive anyway.
11283 // Create the new basic blocks. One block contains all the XMM stores,
11284 // and one block is the final destination regardless of whether any
11285 // stores were performed.
11286 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11287 MachineFunction *F = MBB->getParent();
11288 MachineFunction::iterator MBBIter = MBB;
11290 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11291 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11292 F->insert(MBBIter, XMMSaveMBB);
11293 F->insert(MBBIter, EndMBB);
11295 // Transfer the remainder of MBB and its successor edges to EndMBB.
11296 EndMBB->splice(EndMBB->begin(), MBB,
11297 llvm::next(MachineBasicBlock::iterator(MI)),
11299 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11301 // The original block will now fall through to the XMM save block.
11302 MBB->addSuccessor(XMMSaveMBB);
11303 // The XMMSaveMBB will fall through to the end block.
11304 XMMSaveMBB->addSuccessor(EndMBB);
11306 // Now add the instructions.
11307 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11308 DebugLoc DL = MI->getDebugLoc();
11310 unsigned CountReg = MI->getOperand(0).getReg();
11311 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11312 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11314 if (!Subtarget->isTargetWin64()) {
11315 // If %al is 0, branch around the XMM save block.
11316 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11317 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11318 MBB->addSuccessor(EndMBB);
11321 // In the XMM save block, save all the XMM argument registers.
11322 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11323 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11324 MachineMemOperand *MMO =
11325 F->getMachineMemOperand(
11326 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11327 MachineMemOperand::MOStore,
11328 /*Size=*/16, /*Align=*/16);
11329 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
11330 .addFrameIndex(RegSaveFrameIndex)
11331 .addImm(/*Scale=*/1)
11332 .addReg(/*IndexReg=*/0)
11333 .addImm(/*Disp=*/Offset)
11334 .addReg(/*Segment=*/0)
11335 .addReg(MI->getOperand(i).getReg())
11336 .addMemOperand(MMO);
11339 MI->eraseFromParent(); // The pseudo instruction is gone now.
11344 MachineBasicBlock *
11345 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11346 MachineBasicBlock *BB) const {
11347 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11348 DebugLoc DL = MI->getDebugLoc();
11350 // To "insert" a SELECT_CC instruction, we actually have to insert the
11351 // diamond control-flow pattern. The incoming instruction knows the
11352 // destination vreg to set, the condition code register to branch on, the
11353 // true/false values to select between, and a branch opcode to use.
11354 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11355 MachineFunction::iterator It = BB;
11361 // cmpTY ccX, r1, r2
11363 // fallthrough --> copy0MBB
11364 MachineBasicBlock *thisMBB = BB;
11365 MachineFunction *F = BB->getParent();
11366 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11367 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11368 F->insert(It, copy0MBB);
11369 F->insert(It, sinkMBB);
11371 // If the EFLAGS register isn't dead in the terminator, then claim that it's
11372 // live into the sink and copy blocks.
11373 const MachineFunction *MF = BB->getParent();
11374 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
11375 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
11377 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
11378 const MachineOperand &MO = MI->getOperand(I);
11379 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
11380 unsigned Reg = MO.getReg();
11381 if (Reg != X86::EFLAGS) continue;
11382 copy0MBB->addLiveIn(Reg);
11383 sinkMBB->addLiveIn(Reg);
11386 // Transfer the remainder of BB and its successor edges to sinkMBB.
11387 sinkMBB->splice(sinkMBB->begin(), BB,
11388 llvm::next(MachineBasicBlock::iterator(MI)),
11390 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11392 // Add the true and fallthrough blocks as its successors.
11393 BB->addSuccessor(copy0MBB);
11394 BB->addSuccessor(sinkMBB);
11396 // Create the conditional branch instruction.
11398 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11399 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11402 // %FalseValue = ...
11403 // # fallthrough to sinkMBB
11404 copy0MBB->addSuccessor(sinkMBB);
11407 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11409 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11410 TII->get(X86::PHI), MI->getOperand(0).getReg())
11411 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11412 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11414 MI->eraseFromParent(); // The pseudo instruction is gone now.
11418 MachineBasicBlock *
11419 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
11420 MachineBasicBlock *BB) const {
11421 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11422 DebugLoc DL = MI->getDebugLoc();
11424 assert(!Subtarget->isTargetEnvMacho());
11426 // The lowering is pretty easy: we're just emitting the call to _alloca. The
11427 // non-trivial part is impdef of ESP.
11429 if (Subtarget->isTargetWin64()) {
11430 if (Subtarget->isTargetCygMing()) {
11431 // ___chkstk(Mingw64):
11432 // Clobbers R10, R11, RAX and EFLAGS.
11434 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11435 .addExternalSymbol("___chkstk")
11436 .addReg(X86::RAX, RegState::Implicit)
11437 .addReg(X86::RSP, RegState::Implicit)
11438 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
11439 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
11440 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11442 // __chkstk(MSVCRT): does not update stack pointer.
11443 // Clobbers R10, R11 and EFLAGS.
11444 // FIXME: RAX(allocated size) might be reused and not killed.
11445 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11446 .addExternalSymbol("__chkstk")
11447 .addReg(X86::RAX, RegState::Implicit)
11448 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11449 // RAX has the offset to subtracted from RSP.
11450 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
11455 const char *StackProbeSymbol =
11456 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
11458 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
11459 .addExternalSymbol(StackProbeSymbol)
11460 .addReg(X86::EAX, RegState::Implicit)
11461 .addReg(X86::ESP, RegState::Implicit)
11462 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
11463 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
11464 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11467 MI->eraseFromParent(); // The pseudo instruction is gone now.
11471 MachineBasicBlock *
11472 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
11473 MachineBasicBlock *BB) const {
11474 // This is pretty easy. We're taking the value that we received from
11475 // our load from the relocation, sticking it in either RDI (x86-64)
11476 // or EAX and doing an indirect call. The return value will then
11477 // be in the normal return register.
11478 const X86InstrInfo *TII
11479 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
11480 DebugLoc DL = MI->getDebugLoc();
11481 MachineFunction *F = BB->getParent();
11483 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
11484 assert(MI->getOperand(3).isGlobal() && "This should be a global");
11486 if (Subtarget->is64Bit()) {
11487 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11488 TII->get(X86::MOV64rm), X86::RDI)
11490 .addImm(0).addReg(0)
11491 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11492 MI->getOperand(3).getTargetFlags())
11494 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
11495 addDirectMem(MIB, X86::RDI);
11496 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
11497 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11498 TII->get(X86::MOV32rm), X86::EAX)
11500 .addImm(0).addReg(0)
11501 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11502 MI->getOperand(3).getTargetFlags())
11504 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11505 addDirectMem(MIB, X86::EAX);
11507 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11508 TII->get(X86::MOV32rm), X86::EAX)
11509 .addReg(TII->getGlobalBaseReg(F))
11510 .addImm(0).addReg(0)
11511 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11512 MI->getOperand(3).getTargetFlags())
11514 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11515 addDirectMem(MIB, X86::EAX);
11518 MI->eraseFromParent(); // The pseudo instruction is gone now.
11522 MachineBasicBlock *
11523 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
11524 MachineBasicBlock *BB) const {
11525 switch (MI->getOpcode()) {
11526 default: assert(false && "Unexpected instr type to insert");
11527 case X86::TAILJMPd64:
11528 case X86::TAILJMPr64:
11529 case X86::TAILJMPm64:
11530 assert(!"TAILJMP64 would not be touched here.");
11531 case X86::TCRETURNdi64:
11532 case X86::TCRETURNri64:
11533 case X86::TCRETURNmi64:
11534 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
11535 // On AMD64, additional defs should be added before register allocation.
11536 if (!Subtarget->isTargetWin64()) {
11537 MI->addRegisterDefined(X86::RSI);
11538 MI->addRegisterDefined(X86::RDI);
11539 MI->addRegisterDefined(X86::XMM6);
11540 MI->addRegisterDefined(X86::XMM7);
11541 MI->addRegisterDefined(X86::XMM8);
11542 MI->addRegisterDefined(X86::XMM9);
11543 MI->addRegisterDefined(X86::XMM10);
11544 MI->addRegisterDefined(X86::XMM11);
11545 MI->addRegisterDefined(X86::XMM12);
11546 MI->addRegisterDefined(X86::XMM13);
11547 MI->addRegisterDefined(X86::XMM14);
11548 MI->addRegisterDefined(X86::XMM15);
11551 case X86::WIN_ALLOCA:
11552 return EmitLoweredWinAlloca(MI, BB);
11553 case X86::TLSCall_32:
11554 case X86::TLSCall_64:
11555 return EmitLoweredTLSCall(MI, BB);
11556 case X86::CMOV_GR8:
11557 case X86::CMOV_FR32:
11558 case X86::CMOV_FR64:
11559 case X86::CMOV_V4F32:
11560 case X86::CMOV_V2F64:
11561 case X86::CMOV_V2I64:
11562 case X86::CMOV_V8F32:
11563 case X86::CMOV_V4F64:
11564 case X86::CMOV_V4I64:
11565 case X86::CMOV_GR16:
11566 case X86::CMOV_GR32:
11567 case X86::CMOV_RFP32:
11568 case X86::CMOV_RFP64:
11569 case X86::CMOV_RFP80:
11570 return EmitLoweredSelect(MI, BB);
11572 case X86::FP32_TO_INT16_IN_MEM:
11573 case X86::FP32_TO_INT32_IN_MEM:
11574 case X86::FP32_TO_INT64_IN_MEM:
11575 case X86::FP64_TO_INT16_IN_MEM:
11576 case X86::FP64_TO_INT32_IN_MEM:
11577 case X86::FP64_TO_INT64_IN_MEM:
11578 case X86::FP80_TO_INT16_IN_MEM:
11579 case X86::FP80_TO_INT32_IN_MEM:
11580 case X86::FP80_TO_INT64_IN_MEM: {
11581 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11582 DebugLoc DL = MI->getDebugLoc();
11584 // Change the floating point control register to use "round towards zero"
11585 // mode when truncating to an integer value.
11586 MachineFunction *F = BB->getParent();
11587 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
11588 addFrameReference(BuildMI(*BB, MI, DL,
11589 TII->get(X86::FNSTCW16m)), CWFrameIdx);
11591 // Load the old value of the high byte of the control word...
11593 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
11594 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
11597 // Set the high part to be round to zero...
11598 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
11601 // Reload the modified control word now...
11602 addFrameReference(BuildMI(*BB, MI, DL,
11603 TII->get(X86::FLDCW16m)), CWFrameIdx);
11605 // Restore the memory image of control word to original value
11606 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
11609 // Get the X86 opcode to use.
11611 switch (MI->getOpcode()) {
11612 default: llvm_unreachable("illegal opcode!");
11613 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
11614 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
11615 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
11616 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
11617 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
11618 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
11619 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
11620 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
11621 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
11625 MachineOperand &Op = MI->getOperand(0);
11627 AM.BaseType = X86AddressMode::RegBase;
11628 AM.Base.Reg = Op.getReg();
11630 AM.BaseType = X86AddressMode::FrameIndexBase;
11631 AM.Base.FrameIndex = Op.getIndex();
11633 Op = MI->getOperand(1);
11635 AM.Scale = Op.getImm();
11636 Op = MI->getOperand(2);
11638 AM.IndexReg = Op.getImm();
11639 Op = MI->getOperand(3);
11640 if (Op.isGlobal()) {
11641 AM.GV = Op.getGlobal();
11643 AM.Disp = Op.getImm();
11645 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
11646 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
11648 // Reload the original control word now.
11649 addFrameReference(BuildMI(*BB, MI, DL,
11650 TII->get(X86::FLDCW16m)), CWFrameIdx);
11652 MI->eraseFromParent(); // The pseudo instruction is gone now.
11655 // String/text processing lowering.
11656 case X86::PCMPISTRM128REG:
11657 case X86::VPCMPISTRM128REG:
11658 return EmitPCMP(MI, BB, 3, false /* in-mem */);
11659 case X86::PCMPISTRM128MEM:
11660 case X86::VPCMPISTRM128MEM:
11661 return EmitPCMP(MI, BB, 3, true /* in-mem */);
11662 case X86::PCMPESTRM128REG:
11663 case X86::VPCMPESTRM128REG:
11664 return EmitPCMP(MI, BB, 5, false /* in mem */);
11665 case X86::PCMPESTRM128MEM:
11666 case X86::VPCMPESTRM128MEM:
11667 return EmitPCMP(MI, BB, 5, true /* in mem */);
11669 // Thread synchronization.
11671 return EmitMonitor(MI, BB);
11673 return EmitMwait(MI, BB);
11675 // Atomic Lowering.
11676 case X86::ATOMAND32:
11677 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
11678 X86::AND32ri, X86::MOV32rm,
11680 X86::NOT32r, X86::EAX,
11681 X86::GR32RegisterClass);
11682 case X86::ATOMOR32:
11683 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
11684 X86::OR32ri, X86::MOV32rm,
11686 X86::NOT32r, X86::EAX,
11687 X86::GR32RegisterClass);
11688 case X86::ATOMXOR32:
11689 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
11690 X86::XOR32ri, X86::MOV32rm,
11692 X86::NOT32r, X86::EAX,
11693 X86::GR32RegisterClass);
11694 case X86::ATOMNAND32:
11695 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
11696 X86::AND32ri, X86::MOV32rm,
11698 X86::NOT32r, X86::EAX,
11699 X86::GR32RegisterClass, true);
11700 case X86::ATOMMIN32:
11701 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
11702 case X86::ATOMMAX32:
11703 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
11704 case X86::ATOMUMIN32:
11705 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
11706 case X86::ATOMUMAX32:
11707 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
11709 case X86::ATOMAND16:
11710 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
11711 X86::AND16ri, X86::MOV16rm,
11713 X86::NOT16r, X86::AX,
11714 X86::GR16RegisterClass);
11715 case X86::ATOMOR16:
11716 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
11717 X86::OR16ri, X86::MOV16rm,
11719 X86::NOT16r, X86::AX,
11720 X86::GR16RegisterClass);
11721 case X86::ATOMXOR16:
11722 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
11723 X86::XOR16ri, X86::MOV16rm,
11725 X86::NOT16r, X86::AX,
11726 X86::GR16RegisterClass);
11727 case X86::ATOMNAND16:
11728 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
11729 X86::AND16ri, X86::MOV16rm,
11731 X86::NOT16r, X86::AX,
11732 X86::GR16RegisterClass, true);
11733 case X86::ATOMMIN16:
11734 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
11735 case X86::ATOMMAX16:
11736 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
11737 case X86::ATOMUMIN16:
11738 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
11739 case X86::ATOMUMAX16:
11740 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
11742 case X86::ATOMAND8:
11743 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
11744 X86::AND8ri, X86::MOV8rm,
11746 X86::NOT8r, X86::AL,
11747 X86::GR8RegisterClass);
11749 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
11750 X86::OR8ri, X86::MOV8rm,
11752 X86::NOT8r, X86::AL,
11753 X86::GR8RegisterClass);
11754 case X86::ATOMXOR8:
11755 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
11756 X86::XOR8ri, X86::MOV8rm,
11758 X86::NOT8r, X86::AL,
11759 X86::GR8RegisterClass);
11760 case X86::ATOMNAND8:
11761 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
11762 X86::AND8ri, X86::MOV8rm,
11764 X86::NOT8r, X86::AL,
11765 X86::GR8RegisterClass, true);
11766 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
11767 // This group is for 64-bit host.
11768 case X86::ATOMAND64:
11769 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
11770 X86::AND64ri32, X86::MOV64rm,
11772 X86::NOT64r, X86::RAX,
11773 X86::GR64RegisterClass);
11774 case X86::ATOMOR64:
11775 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
11776 X86::OR64ri32, X86::MOV64rm,
11778 X86::NOT64r, X86::RAX,
11779 X86::GR64RegisterClass);
11780 case X86::ATOMXOR64:
11781 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
11782 X86::XOR64ri32, X86::MOV64rm,
11784 X86::NOT64r, X86::RAX,
11785 X86::GR64RegisterClass);
11786 case X86::ATOMNAND64:
11787 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
11788 X86::AND64ri32, X86::MOV64rm,
11790 X86::NOT64r, X86::RAX,
11791 X86::GR64RegisterClass, true);
11792 case X86::ATOMMIN64:
11793 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
11794 case X86::ATOMMAX64:
11795 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
11796 case X86::ATOMUMIN64:
11797 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
11798 case X86::ATOMUMAX64:
11799 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
11801 // This group does 64-bit operations on a 32-bit host.
11802 case X86::ATOMAND6432:
11803 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11804 X86::AND32rr, X86::AND32rr,
11805 X86::AND32ri, X86::AND32ri,
11807 case X86::ATOMOR6432:
11808 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11809 X86::OR32rr, X86::OR32rr,
11810 X86::OR32ri, X86::OR32ri,
11812 case X86::ATOMXOR6432:
11813 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11814 X86::XOR32rr, X86::XOR32rr,
11815 X86::XOR32ri, X86::XOR32ri,
11817 case X86::ATOMNAND6432:
11818 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11819 X86::AND32rr, X86::AND32rr,
11820 X86::AND32ri, X86::AND32ri,
11822 case X86::ATOMADD6432:
11823 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11824 X86::ADD32rr, X86::ADC32rr,
11825 X86::ADD32ri, X86::ADC32ri,
11827 case X86::ATOMSUB6432:
11828 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11829 X86::SUB32rr, X86::SBB32rr,
11830 X86::SUB32ri, X86::SBB32ri,
11832 case X86::ATOMSWAP6432:
11833 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11834 X86::MOV32rr, X86::MOV32rr,
11835 X86::MOV32ri, X86::MOV32ri,
11837 case X86::VASTART_SAVE_XMM_REGS:
11838 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
11840 case X86::VAARG_64:
11841 return EmitVAARG64WithCustomInserter(MI, BB);
11845 //===----------------------------------------------------------------------===//
11846 // X86 Optimization Hooks
11847 //===----------------------------------------------------------------------===//
11849 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
11853 const SelectionDAG &DAG,
11854 unsigned Depth) const {
11855 unsigned Opc = Op.getOpcode();
11856 assert((Opc >= ISD::BUILTIN_OP_END ||
11857 Opc == ISD::INTRINSIC_WO_CHAIN ||
11858 Opc == ISD::INTRINSIC_W_CHAIN ||
11859 Opc == ISD::INTRINSIC_VOID) &&
11860 "Should use MaskedValueIsZero if you don't know whether Op"
11861 " is a target node!");
11863 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
11877 // These nodes' second result is a boolean.
11878 if (Op.getResNo() == 0)
11881 case X86ISD::SETCC:
11882 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11883 Mask.getBitWidth() - 1);
11888 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11889 unsigned Depth) const {
11890 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11891 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11892 return Op.getValueType().getScalarType().getSizeInBits();
11898 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11899 /// node is a GlobalAddress + offset.
11900 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11901 const GlobalValue* &GA,
11902 int64_t &Offset) const {
11903 if (N->getOpcode() == X86ISD::Wrapper) {
11904 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11905 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11906 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11910 return TargetLowering::isGAPlusOffset(N, GA, Offset);
11913 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
11914 /// same as extracting the high 128-bit part of 256-bit vector and then
11915 /// inserting the result into the low part of a new 256-bit vector
11916 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
11917 EVT VT = SVOp->getValueType(0);
11918 int NumElems = VT.getVectorNumElements();
11920 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
11921 for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
11922 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
11923 SVOp->getMaskElt(j) >= 0)
11929 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
11930 /// same as extracting the low 128-bit part of 256-bit vector and then
11931 /// inserting the result into the high part of a new 256-bit vector
11932 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
11933 EVT VT = SVOp->getValueType(0);
11934 int NumElems = VT.getVectorNumElements();
11936 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
11937 for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
11938 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
11939 SVOp->getMaskElt(j) >= 0)
11945 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
11946 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
11947 TargetLowering::DAGCombinerInfo &DCI) {
11948 DebugLoc dl = N->getDebugLoc();
11949 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
11950 SDValue V1 = SVOp->getOperand(0);
11951 SDValue V2 = SVOp->getOperand(1);
11952 EVT VT = SVOp->getValueType(0);
11953 int NumElems = VT.getVectorNumElements();
11955 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
11956 V2.getOpcode() == ISD::CONCAT_VECTORS) {
11960 // V UNDEF BUILD_VECTOR UNDEF
11962 // CONCAT_VECTOR CONCAT_VECTOR
11965 // RESULT: V + zero extended
11967 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
11968 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
11969 V1.getOperand(1).getOpcode() != ISD::UNDEF)
11972 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
11975 // To match the shuffle mask, the first half of the mask should
11976 // be exactly the first vector, and all the rest a splat with the
11977 // first element of the second one.
11978 for (int i = 0; i < NumElems/2; ++i)
11979 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
11980 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
11983 // Emit a zeroed vector and insert the desired subvector on its
11985 SDValue Zeros = getZeroVector(VT, true /* HasSSE2 */, DAG, dl);
11986 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
11987 DAG.getConstant(0, MVT::i32), DAG, dl);
11988 return DCI.CombineTo(N, InsV);
11991 //===--------------------------------------------------------------------===//
11992 // Combine some shuffles into subvector extracts and inserts:
11995 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
11996 if (isShuffleHigh128VectorInsertLow(SVOp)) {
11997 SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
11999 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12000 V, DAG.getConstant(0, MVT::i32), DAG, dl);
12001 return DCI.CombineTo(N, InsV);
12004 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12005 if (isShuffleLow128VectorInsertHigh(SVOp)) {
12006 SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12007 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12008 V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12009 return DCI.CombineTo(N, InsV);
12015 /// PerformShuffleCombine - Performs several different shuffle combines.
12016 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12017 TargetLowering::DAGCombinerInfo &DCI,
12018 const X86Subtarget *Subtarget) {
12019 DebugLoc dl = N->getDebugLoc();
12020 EVT VT = N->getValueType(0);
12022 // Don't create instructions with illegal types after legalize types has run.
12023 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12024 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12027 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12028 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12029 N->getOpcode() == ISD::VECTOR_SHUFFLE)
12030 return PerformShuffleCombine256(N, DAG, DCI);
12032 // Only handle 128 wide vector from here on.
12033 if (VT.getSizeInBits() != 128)
12036 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12037 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12038 // consecutive, non-overlapping, and in the right order.
12039 SmallVector<SDValue, 16> Elts;
12040 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12041 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12043 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12046 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12047 /// generation and convert it from being a bunch of shuffles and extracts
12048 /// to a simple store and scalar loads to extract the elements.
12049 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12050 const TargetLowering &TLI) {
12051 SDValue InputVector = N->getOperand(0);
12053 // Only operate on vectors of 4 elements, where the alternative shuffling
12054 // gets to be more expensive.
12055 if (InputVector.getValueType() != MVT::v4i32)
12058 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12059 // single use which is a sign-extend or zero-extend, and all elements are
12061 SmallVector<SDNode *, 4> Uses;
12062 unsigned ExtractedElements = 0;
12063 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12064 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12065 if (UI.getUse().getResNo() != InputVector.getResNo())
12068 SDNode *Extract = *UI;
12069 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12072 if (Extract->getValueType(0) != MVT::i32)
12074 if (!Extract->hasOneUse())
12076 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12077 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12079 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12082 // Record which element was extracted.
12083 ExtractedElements |=
12084 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12086 Uses.push_back(Extract);
12089 // If not all the elements were used, this may not be worthwhile.
12090 if (ExtractedElements != 15)
12093 // Ok, we've now decided to do the transformation.
12094 DebugLoc dl = InputVector.getDebugLoc();
12096 // Store the value to a temporary stack slot.
12097 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12098 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12099 MachinePointerInfo(), false, false, 0);
12101 // Replace each use (extract) with a load of the appropriate element.
12102 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12103 UE = Uses.end(); UI != UE; ++UI) {
12104 SDNode *Extract = *UI;
12106 // cOMpute the element's address.
12107 SDValue Idx = Extract->getOperand(1);
12109 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12110 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12111 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12113 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12114 StackPtr, OffsetVal);
12116 // Load the scalar.
12117 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12118 ScalarAddr, MachinePointerInfo(),
12121 // Replace the exact with the load.
12122 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12125 // The replacement was made in place; don't return anything.
12129 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
12130 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12131 const X86Subtarget *Subtarget) {
12132 DebugLoc DL = N->getDebugLoc();
12133 SDValue Cond = N->getOperand(0);
12134 // Get the LHS/RHS of the select.
12135 SDValue LHS = N->getOperand(1);
12136 SDValue RHS = N->getOperand(2);
12138 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12139 // instructions match the semantics of the common C idiom x<y?x:y but not
12140 // x<=y?x:y, because of how they handle negative zero (which can be
12141 // ignored in unsafe-math mode).
12142 if (Subtarget->hasSSE2() &&
12143 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
12144 Cond.getOpcode() == ISD::SETCC) {
12145 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12147 unsigned Opcode = 0;
12148 // Check for x CC y ? x : y.
12149 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12150 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12154 // Converting this to a min would handle NaNs incorrectly, and swapping
12155 // the operands would cause it to handle comparisons between positive
12156 // and negative zero incorrectly.
12157 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12158 if (!UnsafeFPMath &&
12159 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12161 std::swap(LHS, RHS);
12163 Opcode = X86ISD::FMIN;
12166 // Converting this to a min would handle comparisons between positive
12167 // and negative zero incorrectly.
12168 if (!UnsafeFPMath &&
12169 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12171 Opcode = X86ISD::FMIN;
12174 // Converting this to a min would handle both negative zeros and NaNs
12175 // incorrectly, but we can swap the operands to fix both.
12176 std::swap(LHS, RHS);
12180 Opcode = X86ISD::FMIN;
12184 // Converting this to a max would handle comparisons between positive
12185 // and negative zero incorrectly.
12186 if (!UnsafeFPMath &&
12187 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12189 Opcode = X86ISD::FMAX;
12192 // Converting this to a max would handle NaNs incorrectly, and swapping
12193 // the operands would cause it to handle comparisons between positive
12194 // and negative zero incorrectly.
12195 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12196 if (!UnsafeFPMath &&
12197 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12199 std::swap(LHS, RHS);
12201 Opcode = X86ISD::FMAX;
12204 // Converting this to a max would handle both negative zeros and NaNs
12205 // incorrectly, but we can swap the operands to fix both.
12206 std::swap(LHS, RHS);
12210 Opcode = X86ISD::FMAX;
12213 // Check for x CC y ? y : x -- a min/max with reversed arms.
12214 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12215 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12219 // Converting this to a min would handle comparisons between positive
12220 // and negative zero incorrectly, and swapping the operands would
12221 // cause it to handle NaNs incorrectly.
12222 if (!UnsafeFPMath &&
12223 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12224 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12226 std::swap(LHS, RHS);
12228 Opcode = X86ISD::FMIN;
12231 // Converting this to a min would handle NaNs incorrectly.
12232 if (!UnsafeFPMath &&
12233 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12235 Opcode = X86ISD::FMIN;
12238 // Converting this to a min would handle both negative zeros and NaNs
12239 // incorrectly, but we can swap the operands to fix both.
12240 std::swap(LHS, RHS);
12244 Opcode = X86ISD::FMIN;
12248 // Converting this to a max would handle NaNs incorrectly.
12249 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12251 Opcode = X86ISD::FMAX;
12254 // Converting this to a max would handle comparisons between positive
12255 // and negative zero incorrectly, and swapping the operands would
12256 // cause it to handle NaNs incorrectly.
12257 if (!UnsafeFPMath &&
12258 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12259 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12261 std::swap(LHS, RHS);
12263 Opcode = X86ISD::FMAX;
12266 // Converting this to a max would handle both negative zeros and NaNs
12267 // incorrectly, but we can swap the operands to fix both.
12268 std::swap(LHS, RHS);
12272 Opcode = X86ISD::FMAX;
12278 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12281 // If this is a select between two integer constants, try to do some
12283 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
12284 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
12285 // Don't do this for crazy integer types.
12286 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
12287 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
12288 // so that TrueC (the true value) is larger than FalseC.
12289 bool NeedsCondInvert = false;
12291 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
12292 // Efficiently invertible.
12293 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
12294 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
12295 isa<ConstantSDNode>(Cond.getOperand(1))))) {
12296 NeedsCondInvert = true;
12297 std::swap(TrueC, FalseC);
12300 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
12301 if (FalseC->getAPIntValue() == 0 &&
12302 TrueC->getAPIntValue().isPowerOf2()) {
12303 if (NeedsCondInvert) // Invert the condition if needed.
12304 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12305 DAG.getConstant(1, Cond.getValueType()));
12307 // Zero extend the condition if needed.
12308 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
12310 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12311 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
12312 DAG.getConstant(ShAmt, MVT::i8));
12315 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
12316 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12317 if (NeedsCondInvert) // Invert the condition if needed.
12318 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12319 DAG.getConstant(1, Cond.getValueType()));
12321 // Zero extend the condition if needed.
12322 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12323 FalseC->getValueType(0), Cond);
12324 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12325 SDValue(FalseC, 0));
12328 // Optimize cases that will turn into an LEA instruction. This requires
12329 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12330 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12331 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12332 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12334 bool isFastMultiplier = false;
12336 switch ((unsigned char)Diff) {
12338 case 1: // result = add base, cond
12339 case 2: // result = lea base( , cond*2)
12340 case 3: // result = lea base(cond, cond*2)
12341 case 4: // result = lea base( , cond*4)
12342 case 5: // result = lea base(cond, cond*4)
12343 case 8: // result = lea base( , cond*8)
12344 case 9: // result = lea base(cond, cond*8)
12345 isFastMultiplier = true;
12350 if (isFastMultiplier) {
12351 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12352 if (NeedsCondInvert) // Invert the condition if needed.
12353 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12354 DAG.getConstant(1, Cond.getValueType()));
12356 // Zero extend the condition if needed.
12357 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12359 // Scale the condition by the difference.
12361 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12362 DAG.getConstant(Diff, Cond.getValueType()));
12364 // Add the base if non-zero.
12365 if (FalseC->getAPIntValue() != 0)
12366 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12367 SDValue(FalseC, 0));
12377 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
12378 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
12379 TargetLowering::DAGCombinerInfo &DCI) {
12380 DebugLoc DL = N->getDebugLoc();
12382 // If the flag operand isn't dead, don't touch this CMOV.
12383 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
12386 SDValue FalseOp = N->getOperand(0);
12387 SDValue TrueOp = N->getOperand(1);
12388 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
12389 SDValue Cond = N->getOperand(3);
12390 if (CC == X86::COND_E || CC == X86::COND_NE) {
12391 switch (Cond.getOpcode()) {
12395 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
12396 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
12397 return (CC == X86::COND_E) ? FalseOp : TrueOp;
12401 // If this is a select between two integer constants, try to do some
12402 // optimizations. Note that the operands are ordered the opposite of SELECT
12404 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
12405 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
12406 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
12407 // larger than FalseC (the false value).
12408 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
12409 CC = X86::GetOppositeBranchCondition(CC);
12410 std::swap(TrueC, FalseC);
12413 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
12414 // This is efficient for any integer data type (including i8/i16) and
12416 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
12417 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12418 DAG.getConstant(CC, MVT::i8), Cond);
12420 // Zero extend the condition if needed.
12421 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
12423 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12424 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
12425 DAG.getConstant(ShAmt, MVT::i8));
12426 if (N->getNumValues() == 2) // Dead flag value?
12427 return DCI.CombineTo(N, Cond, SDValue());
12431 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
12432 // for any integer data type, including i8/i16.
12433 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12434 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12435 DAG.getConstant(CC, MVT::i8), Cond);
12437 // Zero extend the condition if needed.
12438 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12439 FalseC->getValueType(0), Cond);
12440 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12441 SDValue(FalseC, 0));
12443 if (N->getNumValues() == 2) // Dead flag value?
12444 return DCI.CombineTo(N, Cond, SDValue());
12448 // Optimize cases that will turn into an LEA instruction. This requires
12449 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12450 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12451 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12452 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12454 bool isFastMultiplier = false;
12456 switch ((unsigned char)Diff) {
12458 case 1: // result = add base, cond
12459 case 2: // result = lea base( , cond*2)
12460 case 3: // result = lea base(cond, cond*2)
12461 case 4: // result = lea base( , cond*4)
12462 case 5: // result = lea base(cond, cond*4)
12463 case 8: // result = lea base( , cond*8)
12464 case 9: // result = lea base(cond, cond*8)
12465 isFastMultiplier = true;
12470 if (isFastMultiplier) {
12471 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12472 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12473 DAG.getConstant(CC, MVT::i8), Cond);
12474 // Zero extend the condition if needed.
12475 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12477 // Scale the condition by the difference.
12479 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12480 DAG.getConstant(Diff, Cond.getValueType()));
12482 // Add the base if non-zero.
12483 if (FalseC->getAPIntValue() != 0)
12484 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12485 SDValue(FalseC, 0));
12486 if (N->getNumValues() == 2) // Dead flag value?
12487 return DCI.CombineTo(N, Cond, SDValue());
12497 /// PerformMulCombine - Optimize a single multiply with constant into two
12498 /// in order to implement it with two cheaper instructions, e.g.
12499 /// LEA + SHL, LEA + LEA.
12500 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
12501 TargetLowering::DAGCombinerInfo &DCI) {
12502 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12505 EVT VT = N->getValueType(0);
12506 if (VT != MVT::i64)
12509 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12512 uint64_t MulAmt = C->getZExtValue();
12513 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
12516 uint64_t MulAmt1 = 0;
12517 uint64_t MulAmt2 = 0;
12518 if ((MulAmt % 9) == 0) {
12520 MulAmt2 = MulAmt / 9;
12521 } else if ((MulAmt % 5) == 0) {
12523 MulAmt2 = MulAmt / 5;
12524 } else if ((MulAmt % 3) == 0) {
12526 MulAmt2 = MulAmt / 3;
12529 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
12530 DebugLoc DL = N->getDebugLoc();
12532 if (isPowerOf2_64(MulAmt2) &&
12533 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
12534 // If second multiplifer is pow2, issue it first. We want the multiply by
12535 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
12537 std::swap(MulAmt1, MulAmt2);
12540 if (isPowerOf2_64(MulAmt1))
12541 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
12542 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
12544 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
12545 DAG.getConstant(MulAmt1, VT));
12547 if (isPowerOf2_64(MulAmt2))
12548 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
12549 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
12551 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
12552 DAG.getConstant(MulAmt2, VT));
12554 // Do not add new nodes to DAG combiner worklist.
12555 DCI.CombineTo(N, NewMul, false);
12560 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
12561 SDValue N0 = N->getOperand(0);
12562 SDValue N1 = N->getOperand(1);
12563 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
12564 EVT VT = N0.getValueType();
12566 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
12567 // since the result of setcc_c is all zero's or all ones.
12568 if (N1C && N0.getOpcode() == ISD::AND &&
12569 N0.getOperand(1).getOpcode() == ISD::Constant) {
12570 SDValue N00 = N0.getOperand(0);
12571 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
12572 ((N00.getOpcode() == ISD::ANY_EXTEND ||
12573 N00.getOpcode() == ISD::ZERO_EXTEND) &&
12574 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
12575 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
12576 APInt ShAmt = N1C->getAPIntValue();
12577 Mask = Mask.shl(ShAmt);
12579 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
12580 N00, DAG.getConstant(Mask, VT));
12587 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
12589 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
12590 const X86Subtarget *Subtarget) {
12591 EVT VT = N->getValueType(0);
12592 if (!VT.isVector() && VT.isInteger() &&
12593 N->getOpcode() == ISD::SHL)
12594 return PerformSHLCombine(N, DAG);
12596 // On X86 with SSE2 support, we can transform this to a vector shift if
12597 // all elements are shifted by the same amount. We can't do this in legalize
12598 // because the a constant vector is typically transformed to a constant pool
12599 // so we have no knowledge of the shift amount.
12600 if (!(Subtarget->hasSSE2() || Subtarget->hasAVX()))
12603 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
12606 SDValue ShAmtOp = N->getOperand(1);
12607 EVT EltVT = VT.getVectorElementType();
12608 DebugLoc DL = N->getDebugLoc();
12609 SDValue BaseShAmt = SDValue();
12610 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
12611 unsigned NumElts = VT.getVectorNumElements();
12613 for (; i != NumElts; ++i) {
12614 SDValue Arg = ShAmtOp.getOperand(i);
12615 if (Arg.getOpcode() == ISD::UNDEF) continue;
12619 for (; i != NumElts; ++i) {
12620 SDValue Arg = ShAmtOp.getOperand(i);
12621 if (Arg.getOpcode() == ISD::UNDEF) continue;
12622 if (Arg != BaseShAmt) {
12626 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
12627 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
12628 SDValue InVec = ShAmtOp.getOperand(0);
12629 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12630 unsigned NumElts = InVec.getValueType().getVectorNumElements();
12632 for (; i != NumElts; ++i) {
12633 SDValue Arg = InVec.getOperand(i);
12634 if (Arg.getOpcode() == ISD::UNDEF) continue;
12638 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12639 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12640 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
12641 if (C->getZExtValue() == SplatIdx)
12642 BaseShAmt = InVec.getOperand(1);
12645 if (BaseShAmt.getNode() == 0)
12646 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
12647 DAG.getIntPtrConstant(0));
12651 // The shift amount is an i32.
12652 if (EltVT.bitsGT(MVT::i32))
12653 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
12654 else if (EltVT.bitsLT(MVT::i32))
12655 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
12657 // The shift amount is identical so we can do a vector shift.
12658 SDValue ValOp = N->getOperand(0);
12659 switch (N->getOpcode()) {
12661 llvm_unreachable("Unknown shift opcode!");
12664 if (VT == MVT::v2i64)
12665 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12666 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
12668 if (VT == MVT::v4i32)
12669 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12670 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
12672 if (VT == MVT::v8i16)
12673 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12674 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
12678 if (VT == MVT::v4i32)
12679 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12680 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
12682 if (VT == MVT::v8i16)
12683 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12684 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
12688 if (VT == MVT::v2i64)
12689 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12690 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
12692 if (VT == MVT::v4i32)
12693 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12694 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
12696 if (VT == MVT::v8i16)
12697 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12698 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
12706 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
12707 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
12708 // and friends. Likewise for OR -> CMPNEQSS.
12709 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
12710 TargetLowering::DAGCombinerInfo &DCI,
12711 const X86Subtarget *Subtarget) {
12714 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
12715 // we're requiring SSE2 for both.
12716 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
12717 SDValue N0 = N->getOperand(0);
12718 SDValue N1 = N->getOperand(1);
12719 SDValue CMP0 = N0->getOperand(1);
12720 SDValue CMP1 = N1->getOperand(1);
12721 DebugLoc DL = N->getDebugLoc();
12723 // The SETCCs should both refer to the same CMP.
12724 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
12727 SDValue CMP00 = CMP0->getOperand(0);
12728 SDValue CMP01 = CMP0->getOperand(1);
12729 EVT VT = CMP00.getValueType();
12731 if (VT == MVT::f32 || VT == MVT::f64) {
12732 bool ExpectingFlags = false;
12733 // Check for any users that want flags:
12734 for (SDNode::use_iterator UI = N->use_begin(),
12736 !ExpectingFlags && UI != UE; ++UI)
12737 switch (UI->getOpcode()) {
12742 ExpectingFlags = true;
12744 case ISD::CopyToReg:
12745 case ISD::SIGN_EXTEND:
12746 case ISD::ZERO_EXTEND:
12747 case ISD::ANY_EXTEND:
12751 if (!ExpectingFlags) {
12752 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
12753 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
12755 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
12756 X86::CondCode tmp = cc0;
12761 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
12762 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
12763 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
12764 X86ISD::NodeType NTOperator = is64BitFP ?
12765 X86ISD::FSETCCsd : X86ISD::FSETCCss;
12766 // FIXME: need symbolic constants for these magic numbers.
12767 // See X86ATTInstPrinter.cpp:printSSECC().
12768 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
12769 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
12770 DAG.getConstant(x86cc, MVT::i8));
12771 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
12773 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
12774 DAG.getConstant(1, MVT::i32));
12775 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
12776 return OneBitOfTruth;
12784 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
12785 /// so it can be folded inside ANDNP.
12786 static bool CanFoldXORWithAllOnes(const SDNode *N) {
12787 EVT VT = N->getValueType(0);
12789 // Match direct AllOnes for 128 and 256-bit vectors
12790 if (ISD::isBuildVectorAllOnes(N))
12793 // Look through a bit convert.
12794 if (N->getOpcode() == ISD::BITCAST)
12795 N = N->getOperand(0).getNode();
12797 // Sometimes the operand may come from a insert_subvector building a 256-bit
12799 if (VT.getSizeInBits() == 256 &&
12800 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
12801 SDValue V1 = N->getOperand(0);
12802 SDValue V2 = N->getOperand(1);
12804 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
12805 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
12806 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
12807 ISD::isBuildVectorAllOnes(V2.getNode()))
12814 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
12815 TargetLowering::DAGCombinerInfo &DCI,
12816 const X86Subtarget *Subtarget) {
12817 if (DCI.isBeforeLegalizeOps())
12820 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
12824 // Want to form ANDNP nodes:
12825 // 1) In the hopes of then easily combining them with OR and AND nodes
12826 // to form PBLEND/PSIGN.
12827 // 2) To match ANDN packed intrinsics
12828 EVT VT = N->getValueType(0);
12829 if (VT != MVT::v2i64 && VT != MVT::v4i64)
12832 SDValue N0 = N->getOperand(0);
12833 SDValue N1 = N->getOperand(1);
12834 DebugLoc DL = N->getDebugLoc();
12836 // Check LHS for vnot
12837 if (N0.getOpcode() == ISD::XOR &&
12838 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
12839 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
12840 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
12842 // Check RHS for vnot
12843 if (N1.getOpcode() == ISD::XOR &&
12844 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
12845 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
12846 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
12851 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
12852 TargetLowering::DAGCombinerInfo &DCI,
12853 const X86Subtarget *Subtarget) {
12854 if (DCI.isBeforeLegalizeOps())
12857 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
12861 EVT VT = N->getValueType(0);
12862 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
12865 SDValue N0 = N->getOperand(0);
12866 SDValue N1 = N->getOperand(1);
12868 // look for psign/blend
12869 if (Subtarget->hasSSSE3()) {
12870 if (VT == MVT::v2i64) {
12871 // Canonicalize pandn to RHS
12872 if (N0.getOpcode() == X86ISD::ANDNP)
12874 // or (and (m, x), (pandn m, y))
12875 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
12876 SDValue Mask = N1.getOperand(0);
12877 SDValue X = N1.getOperand(1);
12879 if (N0.getOperand(0) == Mask)
12880 Y = N0.getOperand(1);
12881 if (N0.getOperand(1) == Mask)
12882 Y = N0.getOperand(0);
12884 // Check to see if the mask appeared in both the AND and ANDNP and
12888 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
12889 if (Mask.getOpcode() != ISD::BITCAST ||
12890 X.getOpcode() != ISD::BITCAST ||
12891 Y.getOpcode() != ISD::BITCAST)
12894 // Look through mask bitcast.
12895 Mask = Mask.getOperand(0);
12896 EVT MaskVT = Mask.getValueType();
12898 // Validate that the Mask operand is a vector sra node. The sra node
12899 // will be an intrinsic.
12900 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
12903 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
12904 // there is no psrai.b
12905 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
12906 case Intrinsic::x86_sse2_psrai_w:
12907 case Intrinsic::x86_sse2_psrai_d:
12909 default: return SDValue();
12912 // Check that the SRA is all signbits.
12913 SDValue SraC = Mask.getOperand(2);
12914 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
12915 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
12916 if ((SraAmt + 1) != EltBits)
12919 DebugLoc DL = N->getDebugLoc();
12921 // Now we know we at least have a plendvb with the mask val. See if
12922 // we can form a psignb/w/d.
12923 // psign = x.type == y.type == mask.type && y = sub(0, x);
12924 X = X.getOperand(0);
12925 Y = Y.getOperand(0);
12926 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
12927 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
12928 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
12931 case 8: Opc = X86ISD::PSIGNB; break;
12932 case 16: Opc = X86ISD::PSIGNW; break;
12933 case 32: Opc = X86ISD::PSIGND; break;
12937 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
12938 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
12941 // PBLENDVB only available on SSE 4.1
12942 if (!Subtarget->hasSSE41())
12945 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
12946 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
12947 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
12948 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
12949 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
12954 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
12955 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
12957 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
12959 if (!N0.hasOneUse() || !N1.hasOneUse())
12962 SDValue ShAmt0 = N0.getOperand(1);
12963 if (ShAmt0.getValueType() != MVT::i8)
12965 SDValue ShAmt1 = N1.getOperand(1);
12966 if (ShAmt1.getValueType() != MVT::i8)
12968 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
12969 ShAmt0 = ShAmt0.getOperand(0);
12970 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
12971 ShAmt1 = ShAmt1.getOperand(0);
12973 DebugLoc DL = N->getDebugLoc();
12974 unsigned Opc = X86ISD::SHLD;
12975 SDValue Op0 = N0.getOperand(0);
12976 SDValue Op1 = N1.getOperand(0);
12977 if (ShAmt0.getOpcode() == ISD::SUB) {
12978 Opc = X86ISD::SHRD;
12979 std::swap(Op0, Op1);
12980 std::swap(ShAmt0, ShAmt1);
12983 unsigned Bits = VT.getSizeInBits();
12984 if (ShAmt1.getOpcode() == ISD::SUB) {
12985 SDValue Sum = ShAmt1.getOperand(0);
12986 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
12987 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
12988 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
12989 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
12990 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
12991 return DAG.getNode(Opc, DL, VT,
12993 DAG.getNode(ISD::TRUNCATE, DL,
12996 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
12997 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
12999 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13000 return DAG.getNode(Opc, DL, VT,
13001 N0.getOperand(0), N1.getOperand(0),
13002 DAG.getNode(ISD::TRUNCATE, DL,
13009 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13010 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13011 const X86Subtarget *Subtarget) {
13012 StoreSDNode *St = cast<StoreSDNode>(N);
13013 EVT VT = St->getValue().getValueType();
13014 EVT StVT = St->getMemoryVT();
13015 DebugLoc dl = St->getDebugLoc();
13016 SDValue StoredVal = St->getOperand(1);
13017 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13019 // If we are saving a concatination of two XMM registers, perform two stores.
13020 // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13021 // 128-bit ones. If in the future the cost becomes only one memory access the
13022 // first version would be better.
13023 if (VT.getSizeInBits() == 256 &&
13024 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13025 StoredVal.getNumOperands() == 2) {
13027 SDValue Value0 = StoredVal.getOperand(0);
13028 SDValue Value1 = StoredVal.getOperand(1);
13030 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13031 SDValue Ptr0 = St->getBasePtr();
13032 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13034 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13035 St->getPointerInfo(), St->isVolatile(),
13036 St->isNonTemporal(), St->getAlignment());
13037 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13038 St->getPointerInfo(), St->isVolatile(),
13039 St->isNonTemporal(), St->getAlignment());
13040 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13043 // Optimize trunc store (of multiple scalars) to shuffle and store.
13044 // First, pack all of the elements in one place. Next, store to memory
13045 // in fewer chunks.
13046 if (St->isTruncatingStore() && VT.isVector()) {
13047 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13048 unsigned NumElems = VT.getVectorNumElements();
13049 assert(StVT != VT && "Cannot truncate to the same type");
13050 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13051 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13053 // From, To sizes and ElemCount must be pow of two
13054 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13055 // We are going to use the original vector elt for storing.
13056 // accumulated smaller vector elements must be a multiple of bigger size.
13057 if (0 != (NumElems * ToSz) % FromSz) return SDValue();
13058 unsigned SizeRatio = FromSz / ToSz;
13060 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13062 // Create a type on which we perform the shuffle
13063 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13064 StVT.getScalarType(), NumElems*SizeRatio);
13066 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13068 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13069 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13070 for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13072 // Can't shuffle using an illegal type
13073 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13075 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13076 DAG.getUNDEF(WideVec.getValueType()),
13077 ShuffleVec.data());
13078 // At this point all of the data is stored at the bottom of the
13079 // register. We now need to save it to mem.
13081 // Find the largest store unit
13082 MVT StoreType = MVT::i8;
13083 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13084 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13085 MVT Tp = (MVT::SimpleValueType)tp;
13086 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
13090 // Bitcast the original vector into a vector of store-size units
13091 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13092 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13093 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13094 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
13095 SmallVector<SDValue, 8> Chains;
13096 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
13097 TLI.getPointerTy());
13098 SDValue Ptr = St->getBasePtr();
13100 // Perform one or more big stores into memory.
13101 for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
13102 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
13103 StoreType, ShuffWide,
13104 DAG.getIntPtrConstant(i));
13105 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
13106 St->getPointerInfo(), St->isVolatile(),
13107 St->isNonTemporal(), St->getAlignment());
13108 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13109 Chains.push_back(Ch);
13112 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
13117 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
13118 // the FP state in cases where an emms may be missing.
13119 // A preferable solution to the general problem is to figure out the right
13120 // places to insert EMMS. This qualifies as a quick hack.
13122 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
13123 if (VT.getSizeInBits() != 64)
13126 const Function *F = DAG.getMachineFunction().getFunction();
13127 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
13128 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
13129 && Subtarget->hasSSE2();
13130 if ((VT.isVector() ||
13131 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
13132 isa<LoadSDNode>(St->getValue()) &&
13133 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
13134 St->getChain().hasOneUse() && !St->isVolatile()) {
13135 SDNode* LdVal = St->getValue().getNode();
13136 LoadSDNode *Ld = 0;
13137 int TokenFactorIndex = -1;
13138 SmallVector<SDValue, 8> Ops;
13139 SDNode* ChainVal = St->getChain().getNode();
13140 // Must be a store of a load. We currently handle two cases: the load
13141 // is a direct child, and it's under an intervening TokenFactor. It is
13142 // possible to dig deeper under nested TokenFactors.
13143 if (ChainVal == LdVal)
13144 Ld = cast<LoadSDNode>(St->getChain());
13145 else if (St->getValue().hasOneUse() &&
13146 ChainVal->getOpcode() == ISD::TokenFactor) {
13147 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
13148 if (ChainVal->getOperand(i).getNode() == LdVal) {
13149 TokenFactorIndex = i;
13150 Ld = cast<LoadSDNode>(St->getValue());
13152 Ops.push_back(ChainVal->getOperand(i));
13156 if (!Ld || !ISD::isNormalLoad(Ld))
13159 // If this is not the MMX case, i.e. we are just turning i64 load/store
13160 // into f64 load/store, avoid the transformation if there are multiple
13161 // uses of the loaded value.
13162 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
13165 DebugLoc LdDL = Ld->getDebugLoc();
13166 DebugLoc StDL = N->getDebugLoc();
13167 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
13168 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
13170 if (Subtarget->is64Bit() || F64IsLegal) {
13171 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
13172 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
13173 Ld->getPointerInfo(), Ld->isVolatile(),
13174 Ld->isNonTemporal(), Ld->getAlignment());
13175 SDValue NewChain = NewLd.getValue(1);
13176 if (TokenFactorIndex != -1) {
13177 Ops.push_back(NewChain);
13178 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13181 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
13182 St->getPointerInfo(),
13183 St->isVolatile(), St->isNonTemporal(),
13184 St->getAlignment());
13187 // Otherwise, lower to two pairs of 32-bit loads / stores.
13188 SDValue LoAddr = Ld->getBasePtr();
13189 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
13190 DAG.getConstant(4, MVT::i32));
13192 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
13193 Ld->getPointerInfo(),
13194 Ld->isVolatile(), Ld->isNonTemporal(),
13195 Ld->getAlignment());
13196 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
13197 Ld->getPointerInfo().getWithOffset(4),
13198 Ld->isVolatile(), Ld->isNonTemporal(),
13199 MinAlign(Ld->getAlignment(), 4));
13201 SDValue NewChain = LoLd.getValue(1);
13202 if (TokenFactorIndex != -1) {
13203 Ops.push_back(LoLd);
13204 Ops.push_back(HiLd);
13205 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13209 LoAddr = St->getBasePtr();
13210 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
13211 DAG.getConstant(4, MVT::i32));
13213 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
13214 St->getPointerInfo(),
13215 St->isVolatile(), St->isNonTemporal(),
13216 St->getAlignment());
13217 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
13218 St->getPointerInfo().getWithOffset(4),
13220 St->isNonTemporal(),
13221 MinAlign(St->getAlignment(), 4));
13222 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
13227 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
13228 /// X86ISD::FXOR nodes.
13229 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
13230 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
13231 // F[X]OR(0.0, x) -> x
13232 // F[X]OR(x, 0.0) -> x
13233 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13234 if (C->getValueAPF().isPosZero())
13235 return N->getOperand(1);
13236 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13237 if (C->getValueAPF().isPosZero())
13238 return N->getOperand(0);
13242 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
13243 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
13244 // FAND(0.0, x) -> 0.0
13245 // FAND(x, 0.0) -> 0.0
13246 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13247 if (C->getValueAPF().isPosZero())
13248 return N->getOperand(0);
13249 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13250 if (C->getValueAPF().isPosZero())
13251 return N->getOperand(1);
13255 static SDValue PerformBTCombine(SDNode *N,
13257 TargetLowering::DAGCombinerInfo &DCI) {
13258 // BT ignores high bits in the bit index operand.
13259 SDValue Op1 = N->getOperand(1);
13260 if (Op1.hasOneUse()) {
13261 unsigned BitWidth = Op1.getValueSizeInBits();
13262 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
13263 APInt KnownZero, KnownOne;
13264 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
13265 !DCI.isBeforeLegalizeOps());
13266 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13267 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
13268 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
13269 DCI.CommitTargetLoweringOpt(TLO);
13274 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
13275 SDValue Op = N->getOperand(0);
13276 if (Op.getOpcode() == ISD::BITCAST)
13277 Op = Op.getOperand(0);
13278 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
13279 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
13280 VT.getVectorElementType().getSizeInBits() ==
13281 OpVT.getVectorElementType().getSizeInBits()) {
13282 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
13287 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
13288 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
13289 // (and (i32 x86isd::setcc_carry), 1)
13290 // This eliminates the zext. This transformation is necessary because
13291 // ISD::SETCC is always legalized to i8.
13292 DebugLoc dl = N->getDebugLoc();
13293 SDValue N0 = N->getOperand(0);
13294 EVT VT = N->getValueType(0);
13295 if (N0.getOpcode() == ISD::AND &&
13297 N0.getOperand(0).hasOneUse()) {
13298 SDValue N00 = N0.getOperand(0);
13299 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
13301 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
13302 if (!C || C->getZExtValue() != 1)
13304 return DAG.getNode(ISD::AND, dl, VT,
13305 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
13306 N00.getOperand(0), N00.getOperand(1)),
13307 DAG.getConstant(1, VT));
13313 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
13314 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
13315 unsigned X86CC = N->getConstantOperandVal(0);
13316 SDValue EFLAG = N->getOperand(1);
13317 DebugLoc DL = N->getDebugLoc();
13319 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
13320 // a zext and produces an all-ones bit which is more useful than 0/1 in some
13322 if (X86CC == X86::COND_B)
13323 return DAG.getNode(ISD::AND, DL, MVT::i8,
13324 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
13325 DAG.getConstant(X86CC, MVT::i8), EFLAG),
13326 DAG.getConstant(1, MVT::i8));
13331 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
13332 const X86TargetLowering *XTLI) {
13333 SDValue Op0 = N->getOperand(0);
13334 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
13335 // a 32-bit target where SSE doesn't support i64->FP operations.
13336 if (Op0.getOpcode() == ISD::LOAD) {
13337 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
13338 EVT VT = Ld->getValueType(0);
13339 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
13340 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
13341 !XTLI->getSubtarget()->is64Bit() &&
13342 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13343 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
13344 Ld->getChain(), Op0, DAG);
13345 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
13352 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
13353 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
13354 X86TargetLowering::DAGCombinerInfo &DCI) {
13355 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
13356 // the result is either zero or one (depending on the input carry bit).
13357 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
13358 if (X86::isZeroNode(N->getOperand(0)) &&
13359 X86::isZeroNode(N->getOperand(1)) &&
13360 // We don't have a good way to replace an EFLAGS use, so only do this when
13362 SDValue(N, 1).use_empty()) {
13363 DebugLoc DL = N->getDebugLoc();
13364 EVT VT = N->getValueType(0);
13365 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
13366 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
13367 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
13368 DAG.getConstant(X86::COND_B,MVT::i8),
13370 DAG.getConstant(1, VT));
13371 return DCI.CombineTo(N, Res1, CarryOut);
13377 // fold (add Y, (sete X, 0)) -> adc 0, Y
13378 // (add Y, (setne X, 0)) -> sbb -1, Y
13379 // (sub (sete X, 0), Y) -> sbb 0, Y
13380 // (sub (setne X, 0), Y) -> adc -1, Y
13381 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
13382 DebugLoc DL = N->getDebugLoc();
13384 // Look through ZExts.
13385 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
13386 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
13389 SDValue SetCC = Ext.getOperand(0);
13390 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
13393 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
13394 if (CC != X86::COND_E && CC != X86::COND_NE)
13397 SDValue Cmp = SetCC.getOperand(1);
13398 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
13399 !X86::isZeroNode(Cmp.getOperand(1)) ||
13400 !Cmp.getOperand(0).getValueType().isInteger())
13403 SDValue CmpOp0 = Cmp.getOperand(0);
13404 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
13405 DAG.getConstant(1, CmpOp0.getValueType()));
13407 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
13408 if (CC == X86::COND_NE)
13409 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
13410 DL, OtherVal.getValueType(), OtherVal,
13411 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
13412 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
13413 DL, OtherVal.getValueType(), OtherVal,
13414 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
13417 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
13418 SDValue Op0 = N->getOperand(0);
13419 SDValue Op1 = N->getOperand(1);
13421 // X86 can't encode an immediate LHS of a sub. See if we can push the
13422 // negation into a preceding instruction.
13423 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
13424 // If the RHS of the sub is a XOR with one use and a constant, invert the
13425 // immediate. Then add one to the LHS of the sub so we can turn
13426 // X-Y -> X+~Y+1, saving one register.
13427 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
13428 isa<ConstantSDNode>(Op1.getOperand(1))) {
13429 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
13430 EVT VT = Op0.getValueType();
13431 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
13433 DAG.getConstant(~XorC, VT));
13434 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
13435 DAG.getConstant(C->getAPIntValue()+1, VT));
13439 return OptimizeConditionalInDecrement(N, DAG);
13442 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
13443 DAGCombinerInfo &DCI) const {
13444 SelectionDAG &DAG = DCI.DAG;
13445 switch (N->getOpcode()) {
13447 case ISD::EXTRACT_VECTOR_ELT:
13448 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
13449 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
13450 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
13451 case ISD::ADD: return OptimizeConditionalInDecrement(N, DAG);
13452 case ISD::SUB: return PerformSubCombine(N, DAG);
13453 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
13454 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
13457 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
13458 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
13459 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
13460 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
13461 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
13463 case X86ISD::FOR: return PerformFORCombine(N, DAG);
13464 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
13465 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
13466 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
13467 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
13468 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
13469 case X86ISD::SHUFPS: // Handle all target specific shuffles
13470 case X86ISD::SHUFPD:
13471 case X86ISD::PALIGN:
13472 case X86ISD::PUNPCKHBW:
13473 case X86ISD::PUNPCKHWD:
13474 case X86ISD::PUNPCKHDQ:
13475 case X86ISD::PUNPCKHQDQ:
13476 case X86ISD::UNPCKHPS:
13477 case X86ISD::UNPCKHPD:
13478 case X86ISD::VUNPCKHPSY:
13479 case X86ISD::VUNPCKHPDY:
13480 case X86ISD::PUNPCKLBW:
13481 case X86ISD::PUNPCKLWD:
13482 case X86ISD::PUNPCKLDQ:
13483 case X86ISD::PUNPCKLQDQ:
13484 case X86ISD::UNPCKLPS:
13485 case X86ISD::UNPCKLPD:
13486 case X86ISD::VUNPCKLPSY:
13487 case X86ISD::VUNPCKLPDY:
13488 case X86ISD::MOVHLPS:
13489 case X86ISD::MOVLHPS:
13490 case X86ISD::PSHUFD:
13491 case X86ISD::PSHUFHW:
13492 case X86ISD::PSHUFLW:
13493 case X86ISD::MOVSS:
13494 case X86ISD::MOVSD:
13495 case X86ISD::VPERMILPS:
13496 case X86ISD::VPERMILPSY:
13497 case X86ISD::VPERMILPD:
13498 case X86ISD::VPERMILPDY:
13499 case X86ISD::VPERM2F128:
13500 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
13506 /// isTypeDesirableForOp - Return true if the target has native support for
13507 /// the specified value type and it is 'desirable' to use the type for the
13508 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
13509 /// instruction encodings are longer and some i16 instructions are slow.
13510 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
13511 if (!isTypeLegal(VT))
13513 if (VT != MVT::i16)
13520 case ISD::SIGN_EXTEND:
13521 case ISD::ZERO_EXTEND:
13522 case ISD::ANY_EXTEND:
13535 /// IsDesirableToPromoteOp - This method query the target whether it is
13536 /// beneficial for dag combiner to promote the specified node. If true, it
13537 /// should return the desired promotion type by reference.
13538 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
13539 EVT VT = Op.getValueType();
13540 if (VT != MVT::i16)
13543 bool Promote = false;
13544 bool Commute = false;
13545 switch (Op.getOpcode()) {
13548 LoadSDNode *LD = cast<LoadSDNode>(Op);
13549 // If the non-extending load has a single use and it's not live out, then it
13550 // might be folded.
13551 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
13552 Op.hasOneUse()*/) {
13553 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13554 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
13555 // The only case where we'd want to promote LOAD (rather then it being
13556 // promoted as an operand is when it's only use is liveout.
13557 if (UI->getOpcode() != ISD::CopyToReg)
13564 case ISD::SIGN_EXTEND:
13565 case ISD::ZERO_EXTEND:
13566 case ISD::ANY_EXTEND:
13571 SDValue N0 = Op.getOperand(0);
13572 // Look out for (store (shl (load), x)).
13573 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
13586 SDValue N0 = Op.getOperand(0);
13587 SDValue N1 = Op.getOperand(1);
13588 if (!Commute && MayFoldLoad(N1))
13590 // Avoid disabling potential load folding opportunities.
13591 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
13593 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
13603 //===----------------------------------------------------------------------===//
13604 // X86 Inline Assembly Support
13605 //===----------------------------------------------------------------------===//
13607 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
13608 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
13610 std::string AsmStr = IA->getAsmString();
13612 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
13613 SmallVector<StringRef, 4> AsmPieces;
13614 SplitString(AsmStr, AsmPieces, ";\n");
13616 switch (AsmPieces.size()) {
13617 default: return false;
13619 AsmStr = AsmPieces[0];
13621 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
13623 // FIXME: this should verify that we are targeting a 486 or better. If not,
13624 // we will turn this bswap into something that will be lowered to logical ops
13625 // instead of emitting the bswap asm. For now, we don't support 486 or lower
13626 // so don't worry about this.
13628 if (AsmPieces.size() == 2 &&
13629 (AsmPieces[0] == "bswap" ||
13630 AsmPieces[0] == "bswapq" ||
13631 AsmPieces[0] == "bswapl") &&
13632 (AsmPieces[1] == "$0" ||
13633 AsmPieces[1] == "${0:q}")) {
13634 // No need to check constraints, nothing other than the equivalent of
13635 // "=r,0" would be valid here.
13636 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13637 if (!Ty || Ty->getBitWidth() % 16 != 0)
13639 return IntrinsicLowering::LowerToByteSwap(CI);
13641 // rorw $$8, ${0:w} --> llvm.bswap.i16
13642 if (CI->getType()->isIntegerTy(16) &&
13643 AsmPieces.size() == 3 &&
13644 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
13645 AsmPieces[1] == "$$8," &&
13646 AsmPieces[2] == "${0:w}" &&
13647 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
13649 const std::string &ConstraintsStr = IA->getConstraintString();
13650 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
13651 std::sort(AsmPieces.begin(), AsmPieces.end());
13652 if (AsmPieces.size() == 4 &&
13653 AsmPieces[0] == "~{cc}" &&
13654 AsmPieces[1] == "~{dirflag}" &&
13655 AsmPieces[2] == "~{flags}" &&
13656 AsmPieces[3] == "~{fpsr}") {
13657 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13658 if (!Ty || Ty->getBitWidth() % 16 != 0)
13660 return IntrinsicLowering::LowerToByteSwap(CI);
13665 if (CI->getType()->isIntegerTy(32) &&
13666 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
13667 SmallVector<StringRef, 4> Words;
13668 SplitString(AsmPieces[0], Words, " \t,");
13669 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
13670 Words[2] == "${0:w}") {
13672 SplitString(AsmPieces[1], Words, " \t,");
13673 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
13674 Words[2] == "$0") {
13676 SplitString(AsmPieces[2], Words, " \t,");
13677 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
13678 Words[2] == "${0:w}") {
13680 const std::string &ConstraintsStr = IA->getConstraintString();
13681 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
13682 std::sort(AsmPieces.begin(), AsmPieces.end());
13683 if (AsmPieces.size() == 4 &&
13684 AsmPieces[0] == "~{cc}" &&
13685 AsmPieces[1] == "~{dirflag}" &&
13686 AsmPieces[2] == "~{flags}" &&
13687 AsmPieces[3] == "~{fpsr}") {
13688 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13689 if (!Ty || Ty->getBitWidth() % 16 != 0)
13691 return IntrinsicLowering::LowerToByteSwap(CI);
13698 if (CI->getType()->isIntegerTy(64)) {
13699 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
13700 if (Constraints.size() >= 2 &&
13701 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
13702 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
13703 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
13704 SmallVector<StringRef, 4> Words;
13705 SplitString(AsmPieces[0], Words, " \t");
13706 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
13708 SplitString(AsmPieces[1], Words, " \t");
13709 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
13711 SplitString(AsmPieces[2], Words, " \t,");
13712 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
13713 Words[2] == "%edx") {
13714 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13715 if (!Ty || Ty->getBitWidth() % 16 != 0)
13717 return IntrinsicLowering::LowerToByteSwap(CI);
13730 /// getConstraintType - Given a constraint letter, return the type of
13731 /// constraint it is for this target.
13732 X86TargetLowering::ConstraintType
13733 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
13734 if (Constraint.size() == 1) {
13735 switch (Constraint[0]) {
13746 return C_RegisterClass;
13770 return TargetLowering::getConstraintType(Constraint);
13773 /// Examine constraint type and operand type and determine a weight value.
13774 /// This object must already have been set up with the operand type
13775 /// and the current alternative constraint selected.
13776 TargetLowering::ConstraintWeight
13777 X86TargetLowering::getSingleConstraintMatchWeight(
13778 AsmOperandInfo &info, const char *constraint) const {
13779 ConstraintWeight weight = CW_Invalid;
13780 Value *CallOperandVal = info.CallOperandVal;
13781 // If we don't have a value, we can't do a match,
13782 // but allow it at the lowest weight.
13783 if (CallOperandVal == NULL)
13785 Type *type = CallOperandVal->getType();
13786 // Look at the constraint type.
13787 switch (*constraint) {
13789 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13800 if (CallOperandVal->getType()->isIntegerTy())
13801 weight = CW_SpecificReg;
13806 if (type->isFloatingPointTy())
13807 weight = CW_SpecificReg;
13810 if (type->isX86_MMXTy() && Subtarget->hasMMX())
13811 weight = CW_SpecificReg;
13815 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
13816 weight = CW_Register;
13819 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
13820 if (C->getZExtValue() <= 31)
13821 weight = CW_Constant;
13825 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13826 if (C->getZExtValue() <= 63)
13827 weight = CW_Constant;
13831 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13832 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
13833 weight = CW_Constant;
13837 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13838 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
13839 weight = CW_Constant;
13843 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13844 if (C->getZExtValue() <= 3)
13845 weight = CW_Constant;
13849 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13850 if (C->getZExtValue() <= 0xff)
13851 weight = CW_Constant;
13856 if (dyn_cast<ConstantFP>(CallOperandVal)) {
13857 weight = CW_Constant;
13861 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13862 if ((C->getSExtValue() >= -0x80000000LL) &&
13863 (C->getSExtValue() <= 0x7fffffffLL))
13864 weight = CW_Constant;
13868 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13869 if (C->getZExtValue() <= 0xffffffff)
13870 weight = CW_Constant;
13877 /// LowerXConstraint - try to replace an X constraint, which matches anything,
13878 /// with another that has more specific requirements based on the type of the
13879 /// corresponding operand.
13880 const char *X86TargetLowering::
13881 LowerXConstraint(EVT ConstraintVT) const {
13882 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
13883 // 'f' like normal targets.
13884 if (ConstraintVT.isFloatingPoint()) {
13885 if (Subtarget->hasXMMInt())
13887 if (Subtarget->hasXMM())
13891 return TargetLowering::LowerXConstraint(ConstraintVT);
13894 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13895 /// vector. If it is invalid, don't add anything to Ops.
13896 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13897 std::string &Constraint,
13898 std::vector<SDValue>&Ops,
13899 SelectionDAG &DAG) const {
13900 SDValue Result(0, 0);
13902 // Only support length 1 constraints for now.
13903 if (Constraint.length() > 1) return;
13905 char ConstraintLetter = Constraint[0];
13906 switch (ConstraintLetter) {
13909 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13910 if (C->getZExtValue() <= 31) {
13911 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13917 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13918 if (C->getZExtValue() <= 63) {
13919 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13925 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13926 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
13927 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13933 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13934 if (C->getZExtValue() <= 255) {
13935 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13941 // 32-bit signed value
13942 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13943 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
13944 C->getSExtValue())) {
13945 // Widen to 64 bits here to get it sign extended.
13946 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
13949 // FIXME gcc accepts some relocatable values here too, but only in certain
13950 // memory models; it's complicated.
13955 // 32-bit unsigned value
13956 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13957 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
13958 C->getZExtValue())) {
13959 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13963 // FIXME gcc accepts some relocatable values here too, but only in certain
13964 // memory models; it's complicated.
13968 // Literal immediates are always ok.
13969 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
13970 // Widen to 64 bits here to get it sign extended.
13971 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
13975 // In any sort of PIC mode addresses need to be computed at runtime by
13976 // adding in a register or some sort of table lookup. These can't
13977 // be used as immediates.
13978 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
13981 // If we are in non-pic codegen mode, we allow the address of a global (with
13982 // an optional displacement) to be used with 'i'.
13983 GlobalAddressSDNode *GA = 0;
13984 int64_t Offset = 0;
13986 // Match either (GA), (GA+C), (GA+C1+C2), etc.
13988 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
13989 Offset += GA->getOffset();
13991 } else if (Op.getOpcode() == ISD::ADD) {
13992 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
13993 Offset += C->getZExtValue();
13994 Op = Op.getOperand(0);
13997 } else if (Op.getOpcode() == ISD::SUB) {
13998 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
13999 Offset += -C->getZExtValue();
14000 Op = Op.getOperand(0);
14005 // Otherwise, this isn't something we can handle, reject it.
14009 const GlobalValue *GV = GA->getGlobal();
14010 // If we require an extra load to get this address, as in PIC mode, we
14011 // can't accept it.
14012 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
14013 getTargetMachine())))
14016 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
14017 GA->getValueType(0), Offset);
14022 if (Result.getNode()) {
14023 Ops.push_back(Result);
14026 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14029 std::pair<unsigned, const TargetRegisterClass*>
14030 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
14032 // First, see if this is a constraint that directly corresponds to an LLVM
14034 if (Constraint.size() == 1) {
14035 // GCC Constraint Letters
14036 switch (Constraint[0]) {
14038 // TODO: Slight differences here in allocation order and leaving
14039 // RIP in the class. Do they matter any more here than they do
14040 // in the normal allocation?
14041 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
14042 if (Subtarget->is64Bit()) {
14043 if (VT == MVT::i32 || VT == MVT::f32)
14044 return std::make_pair(0U, X86::GR32RegisterClass);
14045 else if (VT == MVT::i16)
14046 return std::make_pair(0U, X86::GR16RegisterClass);
14047 else if (VT == MVT::i8 || VT == MVT::i1)
14048 return std::make_pair(0U, X86::GR8RegisterClass);
14049 else if (VT == MVT::i64 || VT == MVT::f64)
14050 return std::make_pair(0U, X86::GR64RegisterClass);
14053 // 32-bit fallthrough
14054 case 'Q': // Q_REGS
14055 if (VT == MVT::i32 || VT == MVT::f32)
14056 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
14057 else if (VT == MVT::i16)
14058 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
14059 else if (VT == MVT::i8 || VT == MVT::i1)
14060 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
14061 else if (VT == MVT::i64)
14062 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
14064 case 'r': // GENERAL_REGS
14065 case 'l': // INDEX_REGS
14066 if (VT == MVT::i8 || VT == MVT::i1)
14067 return std::make_pair(0U, X86::GR8RegisterClass);
14068 if (VT == MVT::i16)
14069 return std::make_pair(0U, X86::GR16RegisterClass);
14070 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
14071 return std::make_pair(0U, X86::GR32RegisterClass);
14072 return std::make_pair(0U, X86::GR64RegisterClass);
14073 case 'R': // LEGACY_REGS
14074 if (VT == MVT::i8 || VT == MVT::i1)
14075 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
14076 if (VT == MVT::i16)
14077 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
14078 if (VT == MVT::i32 || !Subtarget->is64Bit())
14079 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
14080 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
14081 case 'f': // FP Stack registers.
14082 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
14083 // value to the correct fpstack register class.
14084 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
14085 return std::make_pair(0U, X86::RFP32RegisterClass);
14086 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
14087 return std::make_pair(0U, X86::RFP64RegisterClass);
14088 return std::make_pair(0U, X86::RFP80RegisterClass);
14089 case 'y': // MMX_REGS if MMX allowed.
14090 if (!Subtarget->hasMMX()) break;
14091 return std::make_pair(0U, X86::VR64RegisterClass);
14092 case 'Y': // SSE_REGS if SSE2 allowed
14093 if (!Subtarget->hasXMMInt()) break;
14095 case 'x': // SSE_REGS if SSE1 allowed
14096 if (!Subtarget->hasXMM()) break;
14098 switch (VT.getSimpleVT().SimpleTy) {
14100 // Scalar SSE types.
14103 return std::make_pair(0U, X86::FR32RegisterClass);
14106 return std::make_pair(0U, X86::FR64RegisterClass);
14114 return std::make_pair(0U, X86::VR128RegisterClass);
14120 // Use the default implementation in TargetLowering to convert the register
14121 // constraint into a member of a register class.
14122 std::pair<unsigned, const TargetRegisterClass*> Res;
14123 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
14125 // Not found as a standard register?
14126 if (Res.second == 0) {
14127 // Map st(0) -> st(7) -> ST0
14128 if (Constraint.size() == 7 && Constraint[0] == '{' &&
14129 tolower(Constraint[1]) == 's' &&
14130 tolower(Constraint[2]) == 't' &&
14131 Constraint[3] == '(' &&
14132 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
14133 Constraint[5] == ')' &&
14134 Constraint[6] == '}') {
14136 Res.first = X86::ST0+Constraint[4]-'0';
14137 Res.second = X86::RFP80RegisterClass;
14141 // GCC allows "st(0)" to be called just plain "st".
14142 if (StringRef("{st}").equals_lower(Constraint)) {
14143 Res.first = X86::ST0;
14144 Res.second = X86::RFP80RegisterClass;
14149 if (StringRef("{flags}").equals_lower(Constraint)) {
14150 Res.first = X86::EFLAGS;
14151 Res.second = X86::CCRRegisterClass;
14155 // 'A' means EAX + EDX.
14156 if (Constraint == "A") {
14157 Res.first = X86::EAX;
14158 Res.second = X86::GR32_ADRegisterClass;
14164 // Otherwise, check to see if this is a register class of the wrong value
14165 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
14166 // turn into {ax},{dx}.
14167 if (Res.second->hasType(VT))
14168 return Res; // Correct type already, nothing to do.
14170 // All of the single-register GCC register classes map their values onto
14171 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
14172 // really want an 8-bit or 32-bit register, map to the appropriate register
14173 // class and return the appropriate register.
14174 if (Res.second == X86::GR16RegisterClass) {
14175 if (VT == MVT::i8) {
14176 unsigned DestReg = 0;
14177 switch (Res.first) {
14179 case X86::AX: DestReg = X86::AL; break;
14180 case X86::DX: DestReg = X86::DL; break;
14181 case X86::CX: DestReg = X86::CL; break;
14182 case X86::BX: DestReg = X86::BL; break;
14185 Res.first = DestReg;
14186 Res.second = X86::GR8RegisterClass;
14188 } else if (VT == MVT::i32) {
14189 unsigned DestReg = 0;
14190 switch (Res.first) {
14192 case X86::AX: DestReg = X86::EAX; break;
14193 case X86::DX: DestReg = X86::EDX; break;
14194 case X86::CX: DestReg = X86::ECX; break;
14195 case X86::BX: DestReg = X86::EBX; break;
14196 case X86::SI: DestReg = X86::ESI; break;
14197 case X86::DI: DestReg = X86::EDI; break;
14198 case X86::BP: DestReg = X86::EBP; break;
14199 case X86::SP: DestReg = X86::ESP; break;
14202 Res.first = DestReg;
14203 Res.second = X86::GR32RegisterClass;
14205 } else if (VT == MVT::i64) {
14206 unsigned DestReg = 0;
14207 switch (Res.first) {
14209 case X86::AX: DestReg = X86::RAX; break;
14210 case X86::DX: DestReg = X86::RDX; break;
14211 case X86::CX: DestReg = X86::RCX; break;
14212 case X86::BX: DestReg = X86::RBX; break;
14213 case X86::SI: DestReg = X86::RSI; break;
14214 case X86::DI: DestReg = X86::RDI; break;
14215 case X86::BP: DestReg = X86::RBP; break;
14216 case X86::SP: DestReg = X86::RSP; break;
14219 Res.first = DestReg;
14220 Res.second = X86::GR64RegisterClass;
14223 } else if (Res.second == X86::FR32RegisterClass ||
14224 Res.second == X86::FR64RegisterClass ||
14225 Res.second == X86::VR128RegisterClass) {
14226 // Handle references to XMM physical registers that got mapped into the
14227 // wrong class. This can happen with constraints like {xmm0} where the
14228 // target independent register mapper will just pick the first match it can
14229 // find, ignoring the required type.
14230 if (VT == MVT::f32)
14231 Res.second = X86::FR32RegisterClass;
14232 else if (VT == MVT::f64)
14233 Res.second = X86::FR64RegisterClass;
14234 else if (X86::VR128RegisterClass->hasType(VT))
14235 Res.second = X86::VR128RegisterClass;