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);
469 if (!Subtarget->is64Bit()) {
470 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
471 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
472 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
473 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
474 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
475 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
476 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
479 // FIXME - use subtarget debug flags
480 if (!Subtarget->isTargetDarwin() &&
481 !Subtarget->isTargetELF() &&
482 !Subtarget->isTargetCygMing()) {
483 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
486 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
487 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
488 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
489 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
490 if (Subtarget->is64Bit()) {
491 setExceptionPointerRegister(X86::RAX);
492 setExceptionSelectorRegister(X86::RDX);
494 setExceptionPointerRegister(X86::EAX);
495 setExceptionSelectorRegister(X86::EDX);
497 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
498 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
500 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
502 setOperationAction(ISD::TRAP, MVT::Other, Legal);
504 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
505 setOperationAction(ISD::VASTART , MVT::Other, Custom);
506 setOperationAction(ISD::VAEND , MVT::Other, Expand);
507 if (Subtarget->is64Bit()) {
508 setOperationAction(ISD::VAARG , MVT::Other, Custom);
509 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
511 setOperationAction(ISD::VAARG , MVT::Other, Expand);
512 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
515 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
516 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
517 setOperationAction(ISD::DYNAMIC_STACKALLOC,
518 (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
519 (Subtarget->isTargetCOFF()
520 && !Subtarget->isTargetEnvMacho()
523 if (!UseSoftFloat && X86ScalarSSEf64) {
524 // f32 and f64 use SSE.
525 // Set up the FP register classes.
526 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
527 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
529 // Use ANDPD to simulate FABS.
530 setOperationAction(ISD::FABS , MVT::f64, Custom);
531 setOperationAction(ISD::FABS , MVT::f32, Custom);
533 // Use XORP to simulate FNEG.
534 setOperationAction(ISD::FNEG , MVT::f64, Custom);
535 setOperationAction(ISD::FNEG , MVT::f32, Custom);
537 // Use ANDPD and ORPD to simulate FCOPYSIGN.
538 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
539 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
541 // Lower this to FGETSIGNx86 plus an AND.
542 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
543 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
545 // We don't support sin/cos/fmod
546 setOperationAction(ISD::FSIN , MVT::f64, Expand);
547 setOperationAction(ISD::FCOS , MVT::f64, Expand);
548 setOperationAction(ISD::FSIN , MVT::f32, Expand);
549 setOperationAction(ISD::FCOS , MVT::f32, Expand);
551 // Expand FP immediates into loads from the stack, except for the special
553 addLegalFPImmediate(APFloat(+0.0)); // xorpd
554 addLegalFPImmediate(APFloat(+0.0f)); // xorps
555 } else if (!UseSoftFloat && X86ScalarSSEf32) {
556 // Use SSE for f32, x87 for f64.
557 // Set up the FP register classes.
558 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
559 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
561 // Use ANDPS to simulate FABS.
562 setOperationAction(ISD::FABS , MVT::f32, Custom);
564 // Use XORP to simulate FNEG.
565 setOperationAction(ISD::FNEG , MVT::f32, Custom);
567 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
569 // Use ANDPS and ORPS to simulate FCOPYSIGN.
570 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
571 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
573 // We don't support sin/cos/fmod
574 setOperationAction(ISD::FSIN , MVT::f32, Expand);
575 setOperationAction(ISD::FCOS , MVT::f32, Expand);
577 // Special cases we handle for FP constants.
578 addLegalFPImmediate(APFloat(+0.0f)); // xorps
579 addLegalFPImmediate(APFloat(+0.0)); // FLD0
580 addLegalFPImmediate(APFloat(+1.0)); // FLD1
581 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
582 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
585 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
586 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
588 } else if (!UseSoftFloat) {
589 // f32 and f64 in x87.
590 // Set up the FP register classes.
591 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
592 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
594 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
595 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
596 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
597 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
600 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
601 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
603 addLegalFPImmediate(APFloat(+0.0)); // FLD0
604 addLegalFPImmediate(APFloat(+1.0)); // FLD1
605 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
606 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
607 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
608 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
609 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
610 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
613 // We don't support FMA.
614 setOperationAction(ISD::FMA, MVT::f64, Expand);
615 setOperationAction(ISD::FMA, MVT::f32, Expand);
617 // Long double always uses X87.
619 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
620 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
621 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
623 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
624 addLegalFPImmediate(TmpFlt); // FLD0
626 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
629 APFloat TmpFlt2(+1.0);
630 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
632 addLegalFPImmediate(TmpFlt2); // FLD1
633 TmpFlt2.changeSign();
634 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
638 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
639 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
642 setOperationAction(ISD::FMA, MVT::f80, Expand);
645 // Always use a library call for pow.
646 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
647 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
648 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
650 setOperationAction(ISD::FLOG, MVT::f80, Expand);
651 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
652 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
653 setOperationAction(ISD::FEXP, MVT::f80, Expand);
654 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
656 // First set operation action for all vector types to either promote
657 // (for widening) or expand (for scalarization). Then we will selectively
658 // turn on ones that can be effectively codegen'd.
659 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
660 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
661 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
662 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
663 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
664 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
665 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
666 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
667 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
668 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
669 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
670 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
671 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
672 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
673 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
674 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
675 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
676 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
677 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
678 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
679 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
680 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
681 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
682 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
683 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
684 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
685 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
686 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
687 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
688 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
689 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
690 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
691 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
692 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
693 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
694 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
695 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
696 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
698 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
699 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
700 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
701 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
702 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
703 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
704 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
705 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
711 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
715 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
716 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
717 setTruncStoreAction((MVT::SimpleValueType)VT,
718 (MVT::SimpleValueType)InnerVT, Expand);
719 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
720 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
721 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
724 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
725 // with -msoft-float, disable use of MMX as well.
726 if (!UseSoftFloat && Subtarget->hasMMX()) {
727 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
728 // No operations on x86mmx supported, everything uses intrinsics.
731 // MMX-sized vectors (other than x86mmx) are expected to be expanded
732 // into smaller operations.
733 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
734 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
735 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
736 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
737 setOperationAction(ISD::AND, MVT::v8i8, Expand);
738 setOperationAction(ISD::AND, MVT::v4i16, Expand);
739 setOperationAction(ISD::AND, MVT::v2i32, Expand);
740 setOperationAction(ISD::AND, MVT::v1i64, Expand);
741 setOperationAction(ISD::OR, MVT::v8i8, Expand);
742 setOperationAction(ISD::OR, MVT::v4i16, Expand);
743 setOperationAction(ISD::OR, MVT::v2i32, Expand);
744 setOperationAction(ISD::OR, MVT::v1i64, Expand);
745 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
746 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
747 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
748 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
749 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
750 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
751 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
752 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
753 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
754 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
755 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
756 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
757 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
758 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
759 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
760 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
761 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
763 if (!UseSoftFloat && Subtarget->hasXMM()) {
764 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
766 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
767 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
768 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
769 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
770 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
771 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
772 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
773 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
774 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
775 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
776 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
777 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
780 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
781 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
783 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
784 // registers cannot be used even for integer operations.
785 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
786 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
787 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
788 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
790 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
791 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
792 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
793 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
794 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
795 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
796 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
797 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
798 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
799 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
800 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
801 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
802 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
803 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
804 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
805 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
807 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
808 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
809 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
810 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
812 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
813 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
814 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
815 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
816 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
818 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
819 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
820 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
821 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
822 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
824 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
825 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
826 EVT VT = (MVT::SimpleValueType)i;
827 // Do not attempt to custom lower non-power-of-2 vectors
828 if (!isPowerOf2_32(VT.getVectorNumElements()))
830 // Do not attempt to custom lower non-128-bit vectors
831 if (!VT.is128BitVector())
833 setOperationAction(ISD::BUILD_VECTOR,
834 VT.getSimpleVT().SimpleTy, Custom);
835 setOperationAction(ISD::VECTOR_SHUFFLE,
836 VT.getSimpleVT().SimpleTy, Custom);
837 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
838 VT.getSimpleVT().SimpleTy, Custom);
841 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
842 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
843 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
844 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
845 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
846 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
848 if (Subtarget->is64Bit()) {
849 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
850 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
853 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
854 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
855 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
858 // Do not attempt to promote non-128-bit vectors
859 if (!VT.is128BitVector())
862 setOperationAction(ISD::AND, SVT, Promote);
863 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
864 setOperationAction(ISD::OR, SVT, Promote);
865 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
866 setOperationAction(ISD::XOR, SVT, Promote);
867 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
868 setOperationAction(ISD::LOAD, SVT, Promote);
869 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
870 setOperationAction(ISD::SELECT, SVT, Promote);
871 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
874 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
876 // Custom lower v2i64 and v2f64 selects.
877 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
878 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
879 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
880 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
882 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
883 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
886 if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
887 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
888 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
889 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
890 setOperationAction(ISD::FRINT, MVT::f32, Legal);
891 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
892 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
893 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
894 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
895 setOperationAction(ISD::FRINT, MVT::f64, Legal);
896 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
898 // FIXME: Do we need to handle scalar-to-vector here?
899 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
901 // Can turn SHL into an integer multiply.
902 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
903 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
905 // i8 and i16 vectors are custom , because the source register and source
906 // source memory operand types are not the same width. f32 vectors are
907 // custom since the immediate controlling the insert encodes additional
909 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
910 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
911 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
912 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
914 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
915 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
916 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
917 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
919 if (Subtarget->is64Bit()) {
920 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
921 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
925 if (Subtarget->hasSSE2() || Subtarget->hasAVX()) {
926 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
927 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
928 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
929 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
931 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
932 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
933 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
935 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
936 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
939 if (Subtarget->hasSSE42() || Subtarget->hasAVX())
940 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
942 if (!UseSoftFloat && Subtarget->hasAVX()) {
943 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
944 addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
945 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
946 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
947 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
948 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
950 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
951 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
952 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
954 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
955 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
956 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
957 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
958 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
959 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
961 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
962 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
963 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
964 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
965 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
966 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
968 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
969 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
970 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
972 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom);
973 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom);
974 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
975 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
976 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom);
977 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom);
979 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
980 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
981 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
982 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
984 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
985 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
986 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
987 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
989 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
990 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
992 setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
993 setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
994 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
995 setOperationAction(ISD::VSETCC, MVT::v4i64, Custom);
997 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
998 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
999 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1001 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1002 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1003 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1004 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1006 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1007 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1008 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1009 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1011 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1012 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1013 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1014 // Don't lower v32i8 because there is no 128-bit byte mul
1016 // Custom lower several nodes for 256-bit types.
1017 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1018 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1019 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1022 // Extract subvector is special because the value type
1023 // (result) is 128-bit but the source is 256-bit wide.
1024 if (VT.is128BitVector())
1025 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1027 // Do not attempt to custom lower other non-256-bit vectors
1028 if (!VT.is256BitVector())
1031 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1032 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1033 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1034 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1035 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1036 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1039 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1040 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1041 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1044 // Do not attempt to promote non-256-bit vectors
1045 if (!VT.is256BitVector())
1048 setOperationAction(ISD::AND, SVT, Promote);
1049 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1050 setOperationAction(ISD::OR, SVT, Promote);
1051 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1052 setOperationAction(ISD::XOR, SVT, Promote);
1053 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1054 setOperationAction(ISD::LOAD, SVT, Promote);
1055 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1056 setOperationAction(ISD::SELECT, SVT, Promote);
1057 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1061 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1062 // of this type with custom code.
1063 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1064 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1065 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1068 // We want to custom lower some of our intrinsics.
1069 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1072 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1073 // handle type legalization for these operations here.
1075 // FIXME: We really should do custom legalization for addition and
1076 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1077 // than generic legalization for 64-bit multiplication-with-overflow, though.
1078 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1079 // Add/Sub/Mul with overflow operations are custom lowered.
1081 setOperationAction(ISD::SADDO, VT, Custom);
1082 setOperationAction(ISD::UADDO, VT, Custom);
1083 setOperationAction(ISD::SSUBO, VT, Custom);
1084 setOperationAction(ISD::USUBO, VT, Custom);
1085 setOperationAction(ISD::SMULO, VT, Custom);
1086 setOperationAction(ISD::UMULO, VT, Custom);
1089 // There are no 8-bit 3-address imul/mul instructions
1090 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1091 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1093 if (!Subtarget->is64Bit()) {
1094 // These libcalls are not available in 32-bit.
1095 setLibcallName(RTLIB::SHL_I128, 0);
1096 setLibcallName(RTLIB::SRL_I128, 0);
1097 setLibcallName(RTLIB::SRA_I128, 0);
1100 // We have target-specific dag combine patterns for the following nodes:
1101 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1102 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1103 setTargetDAGCombine(ISD::BUILD_VECTOR);
1104 setTargetDAGCombine(ISD::SELECT);
1105 setTargetDAGCombine(ISD::SHL);
1106 setTargetDAGCombine(ISD::SRA);
1107 setTargetDAGCombine(ISD::SRL);
1108 setTargetDAGCombine(ISD::OR);
1109 setTargetDAGCombine(ISD::AND);
1110 setTargetDAGCombine(ISD::ADD);
1111 setTargetDAGCombine(ISD::SUB);
1112 setTargetDAGCombine(ISD::STORE);
1113 setTargetDAGCombine(ISD::ZERO_EXTEND);
1114 setTargetDAGCombine(ISD::SINT_TO_FP);
1115 if (Subtarget->is64Bit())
1116 setTargetDAGCombine(ISD::MUL);
1118 computeRegisterProperties();
1120 // On Darwin, -Os means optimize for size without hurting performance,
1121 // do not reduce the limit.
1122 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1123 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1124 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1125 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1126 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1127 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1128 setPrefLoopAlignment(16);
1129 benefitFromCodePlacementOpt = true;
1131 setPrefFunctionAlignment(4);
1135 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1140 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1141 /// the desired ByVal argument alignment.
1142 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1145 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1146 if (VTy->getBitWidth() == 128)
1148 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1149 unsigned EltAlign = 0;
1150 getMaxByValAlign(ATy->getElementType(), EltAlign);
1151 if (EltAlign > MaxAlign)
1152 MaxAlign = EltAlign;
1153 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1154 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1155 unsigned EltAlign = 0;
1156 getMaxByValAlign(STy->getElementType(i), EltAlign);
1157 if (EltAlign > MaxAlign)
1158 MaxAlign = EltAlign;
1166 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1167 /// function arguments in the caller parameter area. For X86, aggregates
1168 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1169 /// are at 4-byte boundaries.
1170 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1171 if (Subtarget->is64Bit()) {
1172 // Max of 8 and alignment of type.
1173 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1180 if (Subtarget->hasXMM())
1181 getMaxByValAlign(Ty, Align);
1185 /// getOptimalMemOpType - Returns the target specific optimal type for load
1186 /// and store operations as a result of memset, memcpy, and memmove
1187 /// lowering. If DstAlign is zero that means it's safe to destination
1188 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1189 /// means there isn't a need to check it against alignment requirement,
1190 /// probably because the source does not need to be loaded. If
1191 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1192 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1193 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1194 /// constant so it does not need to be loaded.
1195 /// It returns EVT::Other if the type should be determined using generic
1196 /// target-independent logic.
1198 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1199 unsigned DstAlign, unsigned SrcAlign,
1200 bool NonScalarIntSafe,
1202 MachineFunction &MF) const {
1203 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1204 // linux. This is because the stack realignment code can't handle certain
1205 // cases like PR2962. This should be removed when PR2962 is fixed.
1206 const Function *F = MF.getFunction();
1207 if (NonScalarIntSafe &&
1208 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1210 (Subtarget->isUnalignedMemAccessFast() ||
1211 ((DstAlign == 0 || DstAlign >= 16) &&
1212 (SrcAlign == 0 || SrcAlign >= 16))) &&
1213 Subtarget->getStackAlignment() >= 16) {
1214 if (Subtarget->hasSSE2())
1216 if (Subtarget->hasSSE1())
1218 } else if (!MemcpyStrSrc && Size >= 8 &&
1219 !Subtarget->is64Bit() &&
1220 Subtarget->getStackAlignment() >= 8 &&
1221 Subtarget->hasXMMInt()) {
1222 // Do not use f64 to lower memcpy if source is string constant. It's
1223 // better to use i32 to avoid the loads.
1227 if (Subtarget->is64Bit() && Size >= 8)
1232 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1233 /// current function. The returned value is a member of the
1234 /// MachineJumpTableInfo::JTEntryKind enum.
1235 unsigned X86TargetLowering::getJumpTableEncoding() const {
1236 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1238 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1239 Subtarget->isPICStyleGOT())
1240 return MachineJumpTableInfo::EK_Custom32;
1242 // Otherwise, use the normal jump table encoding heuristics.
1243 return TargetLowering::getJumpTableEncoding();
1247 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1248 const MachineBasicBlock *MBB,
1249 unsigned uid,MCContext &Ctx) const{
1250 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1251 Subtarget->isPICStyleGOT());
1252 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1254 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1255 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1258 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1260 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1261 SelectionDAG &DAG) const {
1262 if (!Subtarget->is64Bit())
1263 // This doesn't have DebugLoc associated with it, but is not really the
1264 // same as a Register.
1265 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1269 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1270 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1272 const MCExpr *X86TargetLowering::
1273 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1274 MCContext &Ctx) const {
1275 // X86-64 uses RIP relative addressing based on the jump table label.
1276 if (Subtarget->isPICStyleRIPRel())
1277 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1279 // Otherwise, the reference is relative to the PIC base.
1280 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1283 // FIXME: Why this routine is here? Move to RegInfo!
1284 std::pair<const TargetRegisterClass*, uint8_t>
1285 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1286 const TargetRegisterClass *RRC = 0;
1288 switch (VT.getSimpleVT().SimpleTy) {
1290 return TargetLowering::findRepresentativeClass(VT);
1291 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1292 RRC = (Subtarget->is64Bit()
1293 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1296 RRC = X86::VR64RegisterClass;
1298 case MVT::f32: case MVT::f64:
1299 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1300 case MVT::v4f32: case MVT::v2f64:
1301 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1303 RRC = X86::VR128RegisterClass;
1306 return std::make_pair(RRC, Cost);
1309 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1310 unsigned &Offset) const {
1311 if (!Subtarget->isTargetLinux())
1314 if (Subtarget->is64Bit()) {
1315 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1317 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1330 //===----------------------------------------------------------------------===//
1331 // Return Value Calling Convention Implementation
1332 //===----------------------------------------------------------------------===//
1334 #include "X86GenCallingConv.inc"
1337 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1338 MachineFunction &MF, bool isVarArg,
1339 const SmallVectorImpl<ISD::OutputArg> &Outs,
1340 LLVMContext &Context) const {
1341 SmallVector<CCValAssign, 16> RVLocs;
1342 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1344 return CCInfo.CheckReturn(Outs, RetCC_X86);
1348 X86TargetLowering::LowerReturn(SDValue Chain,
1349 CallingConv::ID CallConv, bool isVarArg,
1350 const SmallVectorImpl<ISD::OutputArg> &Outs,
1351 const SmallVectorImpl<SDValue> &OutVals,
1352 DebugLoc dl, SelectionDAG &DAG) const {
1353 MachineFunction &MF = DAG.getMachineFunction();
1354 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1356 SmallVector<CCValAssign, 16> RVLocs;
1357 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1358 RVLocs, *DAG.getContext());
1359 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1361 // Add the regs to the liveout set for the function.
1362 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1363 for (unsigned i = 0; i != RVLocs.size(); ++i)
1364 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1365 MRI.addLiveOut(RVLocs[i].getLocReg());
1369 SmallVector<SDValue, 6> RetOps;
1370 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1371 // Operand #1 = Bytes To Pop
1372 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1375 // Copy the result values into the output registers.
1376 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1377 CCValAssign &VA = RVLocs[i];
1378 assert(VA.isRegLoc() && "Can only return in registers!");
1379 SDValue ValToCopy = OutVals[i];
1380 EVT ValVT = ValToCopy.getValueType();
1382 // If this is x86-64, and we disabled SSE, we can't return FP values,
1383 // or SSE or MMX vectors.
1384 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1385 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1386 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1387 report_fatal_error("SSE register return with SSE disabled");
1389 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1390 // llvm-gcc has never done it right and no one has noticed, so this
1391 // should be OK for now.
1392 if (ValVT == MVT::f64 &&
1393 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1394 report_fatal_error("SSE2 register return with SSE2 disabled");
1396 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1397 // the RET instruction and handled by the FP Stackifier.
1398 if (VA.getLocReg() == X86::ST0 ||
1399 VA.getLocReg() == X86::ST1) {
1400 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1401 // change the value to the FP stack register class.
1402 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1403 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1404 RetOps.push_back(ValToCopy);
1405 // Don't emit a copytoreg.
1409 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1410 // which is returned in RAX / RDX.
1411 if (Subtarget->is64Bit()) {
1412 if (ValVT == MVT::x86mmx) {
1413 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1414 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1415 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1417 // If we don't have SSE2 available, convert to v4f32 so the generated
1418 // register is legal.
1419 if (!Subtarget->hasSSE2())
1420 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1425 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1426 Flag = Chain.getValue(1);
1429 // The x86-64 ABI for returning structs by value requires that we copy
1430 // the sret argument into %rax for the return. We saved the argument into
1431 // a virtual register in the entry block, so now we copy the value out
1433 if (Subtarget->is64Bit() &&
1434 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1435 MachineFunction &MF = DAG.getMachineFunction();
1436 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1437 unsigned Reg = FuncInfo->getSRetReturnReg();
1439 "SRetReturnReg should have been set in LowerFormalArguments().");
1440 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1442 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1443 Flag = Chain.getValue(1);
1445 // RAX now acts like a return value.
1446 MRI.addLiveOut(X86::RAX);
1449 RetOps[0] = Chain; // Update chain.
1451 // Add the flag if we have it.
1453 RetOps.push_back(Flag);
1455 return DAG.getNode(X86ISD::RET_FLAG, dl,
1456 MVT::Other, &RetOps[0], RetOps.size());
1459 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1460 if (N->getNumValues() != 1)
1462 if (!N->hasNUsesOfValue(1, 0))
1465 SDNode *Copy = *N->use_begin();
1466 if (Copy->getOpcode() != ISD::CopyToReg &&
1467 Copy->getOpcode() != ISD::FP_EXTEND)
1470 bool HasRet = false;
1471 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1473 if (UI->getOpcode() != X86ISD::RET_FLAG)
1482 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1483 ISD::NodeType ExtendKind) const {
1485 // TODO: Is this also valid on 32-bit?
1486 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1487 ReturnMVT = MVT::i8;
1489 ReturnMVT = MVT::i32;
1491 EVT MinVT = getRegisterType(Context, ReturnMVT);
1492 return VT.bitsLT(MinVT) ? MinVT : VT;
1495 /// LowerCallResult - Lower the result values of a call into the
1496 /// appropriate copies out of appropriate physical registers.
1499 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1500 CallingConv::ID CallConv, bool isVarArg,
1501 const SmallVectorImpl<ISD::InputArg> &Ins,
1502 DebugLoc dl, SelectionDAG &DAG,
1503 SmallVectorImpl<SDValue> &InVals) const {
1505 // Assign locations to each value returned by this call.
1506 SmallVector<CCValAssign, 16> RVLocs;
1507 bool Is64Bit = Subtarget->is64Bit();
1508 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1509 getTargetMachine(), RVLocs, *DAG.getContext());
1510 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1512 // Copy all of the result registers out of their specified physreg.
1513 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1514 CCValAssign &VA = RVLocs[i];
1515 EVT CopyVT = VA.getValVT();
1517 // If this is x86-64, and we disabled SSE, we can't return FP values
1518 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1519 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1520 report_fatal_error("SSE register return with SSE disabled");
1525 // If this is a call to a function that returns an fp value on the floating
1526 // point stack, we must guarantee the the value is popped from the stack, so
1527 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1528 // if the return value is not used. We use the FpPOP_RETVAL instruction
1530 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1531 // If we prefer to use the value in xmm registers, copy it out as f80 and
1532 // use a truncate to move it from fp stack reg to xmm reg.
1533 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1534 SDValue Ops[] = { Chain, InFlag };
1535 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1536 MVT::Other, MVT::Glue, Ops, 2), 1);
1537 Val = Chain.getValue(0);
1539 // Round the f80 to the right size, which also moves it to the appropriate
1541 if (CopyVT != VA.getValVT())
1542 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1543 // This truncation won't change the value.
1544 DAG.getIntPtrConstant(1));
1546 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1547 CopyVT, InFlag).getValue(1);
1548 Val = Chain.getValue(0);
1550 InFlag = Chain.getValue(2);
1551 InVals.push_back(Val);
1558 //===----------------------------------------------------------------------===//
1559 // C & StdCall & Fast Calling Convention implementation
1560 //===----------------------------------------------------------------------===//
1561 // StdCall calling convention seems to be standard for many Windows' API
1562 // routines and around. It differs from C calling convention just a little:
1563 // callee should clean up the stack, not caller. Symbols should be also
1564 // decorated in some fancy way :) It doesn't support any vector arguments.
1565 // For info on fast calling convention see Fast Calling Convention (tail call)
1566 // implementation LowerX86_32FastCCCallTo.
1568 /// CallIsStructReturn - Determines whether a call uses struct return
1570 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1574 return Outs[0].Flags.isSRet();
1577 /// ArgsAreStructReturn - Determines whether a function uses struct
1578 /// return semantics.
1580 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1584 return Ins[0].Flags.isSRet();
1587 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1588 /// by "Src" to address "Dst" with size and alignment information specified by
1589 /// the specific parameter attribute. The copy will be passed as a byval
1590 /// function parameter.
1592 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1593 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1595 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1597 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1598 /*isVolatile*/false, /*AlwaysInline=*/true,
1599 MachinePointerInfo(), MachinePointerInfo());
1602 /// IsTailCallConvention - Return true if the calling convention is one that
1603 /// supports tail call optimization.
1604 static bool IsTailCallConvention(CallingConv::ID CC) {
1605 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1608 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1609 if (!CI->isTailCall())
1613 CallingConv::ID CalleeCC = CS.getCallingConv();
1614 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1620 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1621 /// a tailcall target by changing its ABI.
1622 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1623 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1627 X86TargetLowering::LowerMemArgument(SDValue Chain,
1628 CallingConv::ID CallConv,
1629 const SmallVectorImpl<ISD::InputArg> &Ins,
1630 DebugLoc dl, SelectionDAG &DAG,
1631 const CCValAssign &VA,
1632 MachineFrameInfo *MFI,
1634 // Create the nodes corresponding to a load from this parameter slot.
1635 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1636 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1637 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1640 // If value is passed by pointer we have address passed instead of the value
1642 if (VA.getLocInfo() == CCValAssign::Indirect)
1643 ValVT = VA.getLocVT();
1645 ValVT = VA.getValVT();
1647 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1648 // changed with more analysis.
1649 // In case of tail call optimization mark all arguments mutable. Since they
1650 // could be overwritten by lowering of arguments in case of a tail call.
1651 if (Flags.isByVal()) {
1652 unsigned Bytes = Flags.getByValSize();
1653 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1654 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1655 return DAG.getFrameIndex(FI, getPointerTy());
1657 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1658 VA.getLocMemOffset(), isImmutable);
1659 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1660 return DAG.getLoad(ValVT, dl, Chain, FIN,
1661 MachinePointerInfo::getFixedStack(FI),
1667 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1668 CallingConv::ID CallConv,
1670 const SmallVectorImpl<ISD::InputArg> &Ins,
1673 SmallVectorImpl<SDValue> &InVals)
1675 MachineFunction &MF = DAG.getMachineFunction();
1676 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1678 const Function* Fn = MF.getFunction();
1679 if (Fn->hasExternalLinkage() &&
1680 Subtarget->isTargetCygMing() &&
1681 Fn->getName() == "main")
1682 FuncInfo->setForceFramePointer(true);
1684 MachineFrameInfo *MFI = MF.getFrameInfo();
1685 bool Is64Bit = Subtarget->is64Bit();
1686 bool IsWin64 = Subtarget->isTargetWin64();
1688 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1689 "Var args not supported with calling convention fastcc or ghc");
1691 // Assign locations to all of the incoming arguments.
1692 SmallVector<CCValAssign, 16> ArgLocs;
1693 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1694 ArgLocs, *DAG.getContext());
1696 // Allocate shadow area for Win64
1698 CCInfo.AllocateStack(32, 8);
1701 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1703 unsigned LastVal = ~0U;
1705 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1706 CCValAssign &VA = ArgLocs[i];
1707 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1709 assert(VA.getValNo() != LastVal &&
1710 "Don't support value assigned to multiple locs yet");
1711 LastVal = VA.getValNo();
1713 if (VA.isRegLoc()) {
1714 EVT RegVT = VA.getLocVT();
1715 TargetRegisterClass *RC = NULL;
1716 if (RegVT == MVT::i32)
1717 RC = X86::GR32RegisterClass;
1718 else if (Is64Bit && RegVT == MVT::i64)
1719 RC = X86::GR64RegisterClass;
1720 else if (RegVT == MVT::f32)
1721 RC = X86::FR32RegisterClass;
1722 else if (RegVT == MVT::f64)
1723 RC = X86::FR64RegisterClass;
1724 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1725 RC = X86::VR256RegisterClass;
1726 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1727 RC = X86::VR128RegisterClass;
1728 else if (RegVT == MVT::x86mmx)
1729 RC = X86::VR64RegisterClass;
1731 llvm_unreachable("Unknown argument type!");
1733 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1734 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1736 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1737 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1739 if (VA.getLocInfo() == CCValAssign::SExt)
1740 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1741 DAG.getValueType(VA.getValVT()));
1742 else if (VA.getLocInfo() == CCValAssign::ZExt)
1743 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1744 DAG.getValueType(VA.getValVT()));
1745 else if (VA.getLocInfo() == CCValAssign::BCvt)
1746 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1748 if (VA.isExtInLoc()) {
1749 // Handle MMX values passed in XMM regs.
1750 if (RegVT.isVector()) {
1751 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1754 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1757 assert(VA.isMemLoc());
1758 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1761 // If value is passed via pointer - do a load.
1762 if (VA.getLocInfo() == CCValAssign::Indirect)
1763 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1764 MachinePointerInfo(), false, false, 0);
1766 InVals.push_back(ArgValue);
1769 // The x86-64 ABI for returning structs by value requires that we copy
1770 // the sret argument into %rax for the return. Save the argument into
1771 // a virtual register so that we can access it from the return points.
1772 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1773 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1774 unsigned Reg = FuncInfo->getSRetReturnReg();
1776 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1777 FuncInfo->setSRetReturnReg(Reg);
1779 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1780 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1783 unsigned StackSize = CCInfo.getNextStackOffset();
1784 // Align stack specially for tail calls.
1785 if (FuncIsMadeTailCallSafe(CallConv))
1786 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1788 // If the function takes variable number of arguments, make a frame index for
1789 // the start of the first vararg value... for expansion of llvm.va_start.
1791 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1792 CallConv != CallingConv::X86_ThisCall)) {
1793 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1796 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1798 // FIXME: We should really autogenerate these arrays
1799 static const unsigned GPR64ArgRegsWin64[] = {
1800 X86::RCX, X86::RDX, X86::R8, X86::R9
1802 static const unsigned GPR64ArgRegs64Bit[] = {
1803 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1805 static const unsigned XMMArgRegs64Bit[] = {
1806 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1807 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1809 const unsigned *GPR64ArgRegs;
1810 unsigned NumXMMRegs = 0;
1813 // The XMM registers which might contain var arg parameters are shadowed
1814 // in their paired GPR. So we only need to save the GPR to their home
1816 TotalNumIntRegs = 4;
1817 GPR64ArgRegs = GPR64ArgRegsWin64;
1819 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1820 GPR64ArgRegs = GPR64ArgRegs64Bit;
1822 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1824 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1827 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1828 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1829 "SSE register cannot be used when SSE is disabled!");
1830 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1831 "SSE register cannot be used when SSE is disabled!");
1832 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1833 // Kernel mode asks for SSE to be disabled, so don't push them
1835 TotalNumXMMRegs = 0;
1838 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1839 // Get to the caller-allocated home save location. Add 8 to account
1840 // for the return address.
1841 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1842 FuncInfo->setRegSaveFrameIndex(
1843 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1844 // Fixup to set vararg frame on shadow area (4 x i64).
1846 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1848 // For X86-64, if there are vararg parameters that are passed via
1849 // registers, then we must store them to their spots on the stack so they
1850 // may be loaded by deferencing the result of va_next.
1851 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1852 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1853 FuncInfo->setRegSaveFrameIndex(
1854 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1858 // Store the integer parameter registers.
1859 SmallVector<SDValue, 8> MemOps;
1860 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1862 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1863 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1864 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1865 DAG.getIntPtrConstant(Offset));
1866 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1867 X86::GR64RegisterClass);
1868 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1870 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1871 MachinePointerInfo::getFixedStack(
1872 FuncInfo->getRegSaveFrameIndex(), Offset),
1874 MemOps.push_back(Store);
1878 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1879 // Now store the XMM (fp + vector) parameter registers.
1880 SmallVector<SDValue, 11> SaveXMMOps;
1881 SaveXMMOps.push_back(Chain);
1883 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1884 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1885 SaveXMMOps.push_back(ALVal);
1887 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1888 FuncInfo->getRegSaveFrameIndex()));
1889 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1890 FuncInfo->getVarArgsFPOffset()));
1892 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1893 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1894 X86::VR128RegisterClass);
1895 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1896 SaveXMMOps.push_back(Val);
1898 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1900 &SaveXMMOps[0], SaveXMMOps.size()));
1903 if (!MemOps.empty())
1904 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1905 &MemOps[0], MemOps.size());
1909 // Some CCs need callee pop.
1910 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1911 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1913 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1914 // If this is an sret function, the return should pop the hidden pointer.
1915 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1916 FuncInfo->setBytesToPopOnReturn(4);
1920 // RegSaveFrameIndex is X86-64 only.
1921 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1922 if (CallConv == CallingConv::X86_FastCall ||
1923 CallConv == CallingConv::X86_ThisCall)
1924 // fastcc functions can't have varargs.
1925 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1932 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1933 SDValue StackPtr, SDValue Arg,
1934 DebugLoc dl, SelectionDAG &DAG,
1935 const CCValAssign &VA,
1936 ISD::ArgFlagsTy Flags) const {
1937 unsigned LocMemOffset = VA.getLocMemOffset();
1938 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1939 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1940 if (Flags.isByVal())
1941 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1943 return DAG.getStore(Chain, dl, Arg, PtrOff,
1944 MachinePointerInfo::getStack(LocMemOffset),
1948 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1949 /// optimization is performed and it is required.
1951 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1952 SDValue &OutRetAddr, SDValue Chain,
1953 bool IsTailCall, bool Is64Bit,
1954 int FPDiff, DebugLoc dl) const {
1955 // Adjust the Return address stack slot.
1956 EVT VT = getPointerTy();
1957 OutRetAddr = getReturnAddressFrameIndex(DAG);
1959 // Load the "old" Return address.
1960 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1962 return SDValue(OutRetAddr.getNode(), 1);
1965 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1966 /// optimization is performed and it is required (FPDiff!=0).
1968 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1969 SDValue Chain, SDValue RetAddrFrIdx,
1970 bool Is64Bit, int FPDiff, DebugLoc dl) {
1971 // Store the return address to the appropriate stack slot.
1972 if (!FPDiff) return Chain;
1973 // Calculate the new stack slot for the return address.
1974 int SlotSize = Is64Bit ? 8 : 4;
1975 int NewReturnAddrFI =
1976 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1977 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1978 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1979 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1980 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1986 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1987 CallingConv::ID CallConv, bool isVarArg,
1989 const SmallVectorImpl<ISD::OutputArg> &Outs,
1990 const SmallVectorImpl<SDValue> &OutVals,
1991 const SmallVectorImpl<ISD::InputArg> &Ins,
1992 DebugLoc dl, SelectionDAG &DAG,
1993 SmallVectorImpl<SDValue> &InVals) const {
1994 MachineFunction &MF = DAG.getMachineFunction();
1995 bool Is64Bit = Subtarget->is64Bit();
1996 bool IsWin64 = Subtarget->isTargetWin64();
1997 bool IsStructRet = CallIsStructReturn(Outs);
1998 bool IsSibcall = false;
2001 // Check if it's really possible to do a tail call.
2002 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2003 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2004 Outs, OutVals, Ins, DAG);
2006 // Sibcalls are automatically detected tailcalls which do not require
2008 if (!GuaranteedTailCallOpt && isTailCall)
2015 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2016 "Var args not supported with calling convention fastcc or ghc");
2018 // Analyze operands of the call, assigning locations to each operand.
2019 SmallVector<CCValAssign, 16> ArgLocs;
2020 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2021 ArgLocs, *DAG.getContext());
2023 // Allocate shadow area for Win64
2025 CCInfo.AllocateStack(32, 8);
2028 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2030 // Get a count of how many bytes are to be pushed on the stack.
2031 unsigned NumBytes = CCInfo.getNextStackOffset();
2033 // This is a sibcall. The memory operands are available in caller's
2034 // own caller's stack.
2036 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2037 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2040 if (isTailCall && !IsSibcall) {
2041 // Lower arguments at fp - stackoffset + fpdiff.
2042 unsigned NumBytesCallerPushed =
2043 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2044 FPDiff = NumBytesCallerPushed - NumBytes;
2046 // Set the delta of movement of the returnaddr stackslot.
2047 // But only set if delta is greater than previous delta.
2048 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2049 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2053 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2055 SDValue RetAddrFrIdx;
2056 // Load return address for tail calls.
2057 if (isTailCall && FPDiff)
2058 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2059 Is64Bit, FPDiff, dl);
2061 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2062 SmallVector<SDValue, 8> MemOpChains;
2065 // Walk the register/memloc assignments, inserting copies/loads. In the case
2066 // of tail call optimization arguments are handle later.
2067 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2068 CCValAssign &VA = ArgLocs[i];
2069 EVT RegVT = VA.getLocVT();
2070 SDValue Arg = OutVals[i];
2071 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2072 bool isByVal = Flags.isByVal();
2074 // Promote the value if needed.
2075 switch (VA.getLocInfo()) {
2076 default: llvm_unreachable("Unknown loc info!");
2077 case CCValAssign::Full: break;
2078 case CCValAssign::SExt:
2079 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2081 case CCValAssign::ZExt:
2082 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2084 case CCValAssign::AExt:
2085 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2086 // Special case: passing MMX values in XMM registers.
2087 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2088 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2089 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2091 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2093 case CCValAssign::BCvt:
2094 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2096 case CCValAssign::Indirect: {
2097 // Store the argument.
2098 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2099 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2100 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2101 MachinePointerInfo::getFixedStack(FI),
2108 if (VA.isRegLoc()) {
2109 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2110 if (isVarArg && IsWin64) {
2111 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2112 // shadow reg if callee is a varargs function.
2113 unsigned ShadowReg = 0;
2114 switch (VA.getLocReg()) {
2115 case X86::XMM0: ShadowReg = X86::RCX; break;
2116 case X86::XMM1: ShadowReg = X86::RDX; break;
2117 case X86::XMM2: ShadowReg = X86::R8; break;
2118 case X86::XMM3: ShadowReg = X86::R9; break;
2121 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2123 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2124 assert(VA.isMemLoc());
2125 if (StackPtr.getNode() == 0)
2126 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2127 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2128 dl, DAG, VA, Flags));
2132 if (!MemOpChains.empty())
2133 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2134 &MemOpChains[0], MemOpChains.size());
2136 // Build a sequence of copy-to-reg nodes chained together with token chain
2137 // and flag operands which copy the outgoing args into registers.
2139 // Tail call byval lowering might overwrite argument registers so in case of
2140 // tail call optimization the copies to registers are lowered later.
2142 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2143 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2144 RegsToPass[i].second, InFlag);
2145 InFlag = Chain.getValue(1);
2148 if (Subtarget->isPICStyleGOT()) {
2149 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2152 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2153 DAG.getNode(X86ISD::GlobalBaseReg,
2154 DebugLoc(), getPointerTy()),
2156 InFlag = Chain.getValue(1);
2158 // If we are tail calling and generating PIC/GOT style code load the
2159 // address of the callee into ECX. The value in ecx is used as target of
2160 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2161 // for tail calls on PIC/GOT architectures. Normally we would just put the
2162 // address of GOT into ebx and then call target@PLT. But for tail calls
2163 // ebx would be restored (since ebx is callee saved) before jumping to the
2166 // Note: The actual moving to ECX is done further down.
2167 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2168 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2169 !G->getGlobal()->hasProtectedVisibility())
2170 Callee = LowerGlobalAddress(Callee, DAG);
2171 else if (isa<ExternalSymbolSDNode>(Callee))
2172 Callee = LowerExternalSymbol(Callee, DAG);
2176 if (Is64Bit && isVarArg && !IsWin64) {
2177 // From AMD64 ABI document:
2178 // For calls that may call functions that use varargs or stdargs
2179 // (prototype-less calls or calls to functions containing ellipsis (...) in
2180 // the declaration) %al is used as hidden argument to specify the number
2181 // of SSE registers used. The contents of %al do not need to match exactly
2182 // the number of registers, but must be an ubound on the number of SSE
2183 // registers used and is in the range 0 - 8 inclusive.
2185 // Count the number of XMM registers allocated.
2186 static const unsigned XMMArgRegs[] = {
2187 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2188 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2190 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2191 assert((Subtarget->hasXMM() || !NumXMMRegs)
2192 && "SSE registers cannot be used when SSE is disabled");
2194 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2195 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2196 InFlag = Chain.getValue(1);
2200 // For tail calls lower the arguments to the 'real' stack slot.
2202 // Force all the incoming stack arguments to be loaded from the stack
2203 // before any new outgoing arguments are stored to the stack, because the
2204 // outgoing stack slots may alias the incoming argument stack slots, and
2205 // the alias isn't otherwise explicit. This is slightly more conservative
2206 // than necessary, because it means that each store effectively depends
2207 // on every argument instead of just those arguments it would clobber.
2208 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2210 SmallVector<SDValue, 8> MemOpChains2;
2213 // Do not flag preceding copytoreg stuff together with the following stuff.
2215 if (GuaranteedTailCallOpt) {
2216 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2217 CCValAssign &VA = ArgLocs[i];
2220 assert(VA.isMemLoc());
2221 SDValue Arg = OutVals[i];
2222 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2223 // Create frame index.
2224 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2225 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2226 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2227 FIN = DAG.getFrameIndex(FI, getPointerTy());
2229 if (Flags.isByVal()) {
2230 // Copy relative to framepointer.
2231 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2232 if (StackPtr.getNode() == 0)
2233 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2235 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2237 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2241 // Store relative to framepointer.
2242 MemOpChains2.push_back(
2243 DAG.getStore(ArgChain, dl, Arg, FIN,
2244 MachinePointerInfo::getFixedStack(FI),
2250 if (!MemOpChains2.empty())
2251 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2252 &MemOpChains2[0], MemOpChains2.size());
2254 // Copy arguments to their registers.
2255 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2256 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2257 RegsToPass[i].second, InFlag);
2258 InFlag = Chain.getValue(1);
2262 // Store the return address to the appropriate stack slot.
2263 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2267 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2268 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2269 // In the 64-bit large code model, we have to make all calls
2270 // through a register, since the call instruction's 32-bit
2271 // pc-relative offset may not be large enough to hold the whole
2273 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2274 // If the callee is a GlobalAddress node (quite common, every direct call
2275 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2278 // We should use extra load for direct calls to dllimported functions in
2280 const GlobalValue *GV = G->getGlobal();
2281 if (!GV->hasDLLImportLinkage()) {
2282 unsigned char OpFlags = 0;
2283 bool ExtraLoad = false;
2284 unsigned WrapperKind = ISD::DELETED_NODE;
2286 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2287 // external symbols most go through the PLT in PIC mode. If the symbol
2288 // has hidden or protected visibility, or if it is static or local, then
2289 // we don't need to use the PLT - we can directly call it.
2290 if (Subtarget->isTargetELF() &&
2291 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2292 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2293 OpFlags = X86II::MO_PLT;
2294 } else if (Subtarget->isPICStyleStubAny() &&
2295 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2296 (!Subtarget->getTargetTriple().isMacOSX() ||
2297 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2298 // PC-relative references to external symbols should go through $stub,
2299 // unless we're building with the leopard linker or later, which
2300 // automatically synthesizes these stubs.
2301 OpFlags = X86II::MO_DARWIN_STUB;
2302 } else if (Subtarget->isPICStyleRIPRel() &&
2303 isa<Function>(GV) &&
2304 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2305 // If the function is marked as non-lazy, generate an indirect call
2306 // which loads from the GOT directly. This avoids runtime overhead
2307 // at the cost of eager binding (and one extra byte of encoding).
2308 OpFlags = X86II::MO_GOTPCREL;
2309 WrapperKind = X86ISD::WrapperRIP;
2313 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2314 G->getOffset(), OpFlags);
2316 // Add a wrapper if needed.
2317 if (WrapperKind != ISD::DELETED_NODE)
2318 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2319 // Add extra indirection if needed.
2321 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2322 MachinePointerInfo::getGOT(),
2325 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2326 unsigned char OpFlags = 0;
2328 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2329 // external symbols should go through the PLT.
2330 if (Subtarget->isTargetELF() &&
2331 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2332 OpFlags = X86II::MO_PLT;
2333 } else if (Subtarget->isPICStyleStubAny() &&
2334 (!Subtarget->getTargetTriple().isMacOSX() ||
2335 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2336 // PC-relative references to external symbols should go through $stub,
2337 // unless we're building with the leopard linker or later, which
2338 // automatically synthesizes these stubs.
2339 OpFlags = X86II::MO_DARWIN_STUB;
2342 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2346 // Returns a chain & a flag for retval copy to use.
2347 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2348 SmallVector<SDValue, 8> Ops;
2350 if (!IsSibcall && isTailCall) {
2351 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2352 DAG.getIntPtrConstant(0, true), InFlag);
2353 InFlag = Chain.getValue(1);
2356 Ops.push_back(Chain);
2357 Ops.push_back(Callee);
2360 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2362 // Add argument registers to the end of the list so that they are known live
2364 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2365 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2366 RegsToPass[i].second.getValueType()));
2368 // Add an implicit use GOT pointer in EBX.
2369 if (!isTailCall && Subtarget->isPICStyleGOT())
2370 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2372 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2373 if (Is64Bit && isVarArg && !IsWin64)
2374 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2376 if (InFlag.getNode())
2377 Ops.push_back(InFlag);
2381 //// If this is the first return lowered for this function, add the regs
2382 //// to the liveout set for the function.
2383 // This isn't right, although it's probably harmless on x86; liveouts
2384 // should be computed from returns not tail calls. Consider a void
2385 // function making a tail call to a function returning int.
2386 return DAG.getNode(X86ISD::TC_RETURN, dl,
2387 NodeTys, &Ops[0], Ops.size());
2390 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2391 InFlag = Chain.getValue(1);
2393 // Create the CALLSEQ_END node.
2394 unsigned NumBytesForCalleeToPush;
2395 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2396 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2397 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2398 // If this is a call to a struct-return function, the callee
2399 // pops the hidden struct pointer, so we have to push it back.
2400 // This is common for Darwin/X86, Linux & Mingw32 targets.
2401 NumBytesForCalleeToPush = 4;
2403 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2405 // Returns a flag for retval copy to use.
2407 Chain = DAG.getCALLSEQ_END(Chain,
2408 DAG.getIntPtrConstant(NumBytes, true),
2409 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2412 InFlag = Chain.getValue(1);
2415 // Handle result values, copying them out of physregs into vregs that we
2417 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2418 Ins, dl, DAG, InVals);
2422 //===----------------------------------------------------------------------===//
2423 // Fast Calling Convention (tail call) implementation
2424 //===----------------------------------------------------------------------===//
2426 // Like std call, callee cleans arguments, convention except that ECX is
2427 // reserved for storing the tail called function address. Only 2 registers are
2428 // free for argument passing (inreg). Tail call optimization is performed
2430 // * tailcallopt is enabled
2431 // * caller/callee are fastcc
2432 // On X86_64 architecture with GOT-style position independent code only local
2433 // (within module) calls are supported at the moment.
2434 // To keep the stack aligned according to platform abi the function
2435 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2436 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2437 // If a tail called function callee has more arguments than the caller the
2438 // caller needs to make sure that there is room to move the RETADDR to. This is
2439 // achieved by reserving an area the size of the argument delta right after the
2440 // original REtADDR, but before the saved framepointer or the spilled registers
2441 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2453 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2454 /// for a 16 byte align requirement.
2456 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2457 SelectionDAG& DAG) const {
2458 MachineFunction &MF = DAG.getMachineFunction();
2459 const TargetMachine &TM = MF.getTarget();
2460 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2461 unsigned StackAlignment = TFI.getStackAlignment();
2462 uint64_t AlignMask = StackAlignment - 1;
2463 int64_t Offset = StackSize;
2464 uint64_t SlotSize = TD->getPointerSize();
2465 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2466 // Number smaller than 12 so just add the difference.
2467 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2469 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2470 Offset = ((~AlignMask) & Offset) + StackAlignment +
2471 (StackAlignment-SlotSize);
2476 /// MatchingStackOffset - Return true if the given stack call argument is
2477 /// already available in the same position (relatively) of the caller's
2478 /// incoming argument stack.
2480 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2481 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2482 const X86InstrInfo *TII) {
2483 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2485 if (Arg.getOpcode() == ISD::CopyFromReg) {
2486 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2487 if (!TargetRegisterInfo::isVirtualRegister(VR))
2489 MachineInstr *Def = MRI->getVRegDef(VR);
2492 if (!Flags.isByVal()) {
2493 if (!TII->isLoadFromStackSlot(Def, FI))
2496 unsigned Opcode = Def->getOpcode();
2497 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2498 Def->getOperand(1).isFI()) {
2499 FI = Def->getOperand(1).getIndex();
2500 Bytes = Flags.getByValSize();
2504 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2505 if (Flags.isByVal())
2506 // ByVal argument is passed in as a pointer but it's now being
2507 // dereferenced. e.g.
2508 // define @foo(%struct.X* %A) {
2509 // tail call @bar(%struct.X* byval %A)
2512 SDValue Ptr = Ld->getBasePtr();
2513 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2516 FI = FINode->getIndex();
2517 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2518 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2519 FI = FINode->getIndex();
2520 Bytes = Flags.getByValSize();
2524 assert(FI != INT_MAX);
2525 if (!MFI->isFixedObjectIndex(FI))
2527 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2530 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2531 /// for tail call optimization. Targets which want to do tail call
2532 /// optimization should implement this function.
2534 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2535 CallingConv::ID CalleeCC,
2537 bool isCalleeStructRet,
2538 bool isCallerStructRet,
2539 const SmallVectorImpl<ISD::OutputArg> &Outs,
2540 const SmallVectorImpl<SDValue> &OutVals,
2541 const SmallVectorImpl<ISD::InputArg> &Ins,
2542 SelectionDAG& DAG) const {
2543 if (!IsTailCallConvention(CalleeCC) &&
2544 CalleeCC != CallingConv::C)
2547 // If -tailcallopt is specified, make fastcc functions tail-callable.
2548 const MachineFunction &MF = DAG.getMachineFunction();
2549 const Function *CallerF = DAG.getMachineFunction().getFunction();
2550 CallingConv::ID CallerCC = CallerF->getCallingConv();
2551 bool CCMatch = CallerCC == CalleeCC;
2553 if (GuaranteedTailCallOpt) {
2554 if (IsTailCallConvention(CalleeCC) && CCMatch)
2559 // Look for obvious safe cases to perform tail call optimization that do not
2560 // require ABI changes. This is what gcc calls sibcall.
2562 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2563 // emit a special epilogue.
2564 if (RegInfo->needsStackRealignment(MF))
2567 // Also avoid sibcall optimization if either caller or callee uses struct
2568 // return semantics.
2569 if (isCalleeStructRet || isCallerStructRet)
2572 // An stdcall caller is expected to clean up its arguments; the callee
2573 // isn't going to do that.
2574 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2577 // Do not sibcall optimize vararg calls unless all arguments are passed via
2579 if (isVarArg && !Outs.empty()) {
2581 // Optimizing for varargs on Win64 is unlikely to be safe without
2582 // additional testing.
2583 if (Subtarget->isTargetWin64())
2586 SmallVector<CCValAssign, 16> ArgLocs;
2587 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2588 getTargetMachine(), ArgLocs, *DAG.getContext());
2590 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2591 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2592 if (!ArgLocs[i].isRegLoc())
2596 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2597 // Therefore if it's not used by the call it is not safe to optimize this into
2599 bool Unused = false;
2600 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2607 SmallVector<CCValAssign, 16> RVLocs;
2608 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2609 getTargetMachine(), RVLocs, *DAG.getContext());
2610 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2611 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2612 CCValAssign &VA = RVLocs[i];
2613 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2618 // If the calling conventions do not match, then we'd better make sure the
2619 // results are returned in the same way as what the caller expects.
2621 SmallVector<CCValAssign, 16> RVLocs1;
2622 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2623 getTargetMachine(), RVLocs1, *DAG.getContext());
2624 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2626 SmallVector<CCValAssign, 16> RVLocs2;
2627 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2628 getTargetMachine(), RVLocs2, *DAG.getContext());
2629 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2631 if (RVLocs1.size() != RVLocs2.size())
2633 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2634 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2636 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2638 if (RVLocs1[i].isRegLoc()) {
2639 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2642 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2648 // If the callee takes no arguments then go on to check the results of the
2650 if (!Outs.empty()) {
2651 // Check if stack adjustment is needed. For now, do not do this if any
2652 // argument is passed on the stack.
2653 SmallVector<CCValAssign, 16> ArgLocs;
2654 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2655 getTargetMachine(), ArgLocs, *DAG.getContext());
2657 // Allocate shadow area for Win64
2658 if (Subtarget->isTargetWin64()) {
2659 CCInfo.AllocateStack(32, 8);
2662 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2663 if (CCInfo.getNextStackOffset()) {
2664 MachineFunction &MF = DAG.getMachineFunction();
2665 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2668 // Check if the arguments are already laid out in the right way as
2669 // the caller's fixed stack objects.
2670 MachineFrameInfo *MFI = MF.getFrameInfo();
2671 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2672 const X86InstrInfo *TII =
2673 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2674 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2675 CCValAssign &VA = ArgLocs[i];
2676 SDValue Arg = OutVals[i];
2677 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2678 if (VA.getLocInfo() == CCValAssign::Indirect)
2680 if (!VA.isRegLoc()) {
2681 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2688 // If the tailcall address may be in a register, then make sure it's
2689 // possible to register allocate for it. In 32-bit, the call address can
2690 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2691 // callee-saved registers are restored. These happen to be the same
2692 // registers used to pass 'inreg' arguments so watch out for those.
2693 if (!Subtarget->is64Bit() &&
2694 !isa<GlobalAddressSDNode>(Callee) &&
2695 !isa<ExternalSymbolSDNode>(Callee)) {
2696 unsigned NumInRegs = 0;
2697 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2698 CCValAssign &VA = ArgLocs[i];
2701 unsigned Reg = VA.getLocReg();
2704 case X86::EAX: case X86::EDX: case X86::ECX:
2705 if (++NumInRegs == 3)
2717 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2718 return X86::createFastISel(funcInfo);
2722 //===----------------------------------------------------------------------===//
2723 // Other Lowering Hooks
2724 //===----------------------------------------------------------------------===//
2726 static bool MayFoldLoad(SDValue Op) {
2727 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2730 static bool MayFoldIntoStore(SDValue Op) {
2731 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2734 static bool isTargetShuffle(unsigned Opcode) {
2736 default: return false;
2737 case X86ISD::PSHUFD:
2738 case X86ISD::PSHUFHW:
2739 case X86ISD::PSHUFLW:
2740 case X86ISD::SHUFPD:
2741 case X86ISD::PALIGN:
2742 case X86ISD::SHUFPS:
2743 case X86ISD::MOVLHPS:
2744 case X86ISD::MOVLHPD:
2745 case X86ISD::MOVHLPS:
2746 case X86ISD::MOVLPS:
2747 case X86ISD::MOVLPD:
2748 case X86ISD::MOVSHDUP:
2749 case X86ISD::MOVSLDUP:
2750 case X86ISD::MOVDDUP:
2753 case X86ISD::UNPCKLPS:
2754 case X86ISD::UNPCKLPD:
2755 case X86ISD::VUNPCKLPSY:
2756 case X86ISD::VUNPCKLPDY:
2757 case X86ISD::PUNPCKLWD:
2758 case X86ISD::PUNPCKLBW:
2759 case X86ISD::PUNPCKLDQ:
2760 case X86ISD::PUNPCKLQDQ:
2761 case X86ISD::UNPCKHPS:
2762 case X86ISD::UNPCKHPD:
2763 case X86ISD::VUNPCKHPSY:
2764 case X86ISD::VUNPCKHPDY:
2765 case X86ISD::PUNPCKHWD:
2766 case X86ISD::PUNPCKHBW:
2767 case X86ISD::PUNPCKHDQ:
2768 case X86ISD::PUNPCKHQDQ:
2769 case X86ISD::VPERMILPS:
2770 case X86ISD::VPERMILPSY:
2771 case X86ISD::VPERMILPD:
2772 case X86ISD::VPERMILPDY:
2773 case X86ISD::VPERM2F128:
2779 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2780 SDValue V1, SelectionDAG &DAG) {
2782 default: llvm_unreachable("Unknown x86 shuffle node");
2783 case X86ISD::MOVSHDUP:
2784 case X86ISD::MOVSLDUP:
2785 case X86ISD::MOVDDUP:
2786 return DAG.getNode(Opc, dl, VT, V1);
2792 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2793 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2795 default: llvm_unreachable("Unknown x86 shuffle node");
2796 case X86ISD::PSHUFD:
2797 case X86ISD::PSHUFHW:
2798 case X86ISD::PSHUFLW:
2799 case X86ISD::VPERMILPS:
2800 case X86ISD::VPERMILPSY:
2801 case X86ISD::VPERMILPD:
2802 case X86ISD::VPERMILPDY:
2803 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2809 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2810 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2812 default: llvm_unreachable("Unknown x86 shuffle node");
2813 case X86ISD::PALIGN:
2814 case X86ISD::SHUFPD:
2815 case X86ISD::SHUFPS:
2816 case X86ISD::VPERM2F128:
2817 return DAG.getNode(Opc, dl, VT, V1, V2,
2818 DAG.getConstant(TargetMask, MVT::i8));
2823 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2824 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2826 default: llvm_unreachable("Unknown x86 shuffle node");
2827 case X86ISD::MOVLHPS:
2828 case X86ISD::MOVLHPD:
2829 case X86ISD::MOVHLPS:
2830 case X86ISD::MOVLPS:
2831 case X86ISD::MOVLPD:
2834 case X86ISD::UNPCKLPS:
2835 case X86ISD::UNPCKLPD:
2836 case X86ISD::VUNPCKLPSY:
2837 case X86ISD::VUNPCKLPDY:
2838 case X86ISD::PUNPCKLWD:
2839 case X86ISD::PUNPCKLBW:
2840 case X86ISD::PUNPCKLDQ:
2841 case X86ISD::PUNPCKLQDQ:
2842 case X86ISD::UNPCKHPS:
2843 case X86ISD::UNPCKHPD:
2844 case X86ISD::VUNPCKHPSY:
2845 case X86ISD::VUNPCKHPDY:
2846 case X86ISD::PUNPCKHWD:
2847 case X86ISD::PUNPCKHBW:
2848 case X86ISD::PUNPCKHDQ:
2849 case X86ISD::PUNPCKHQDQ:
2850 return DAG.getNode(Opc, dl, VT, V1, V2);
2855 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2856 MachineFunction &MF = DAG.getMachineFunction();
2857 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2858 int ReturnAddrIndex = FuncInfo->getRAIndex();
2860 if (ReturnAddrIndex == 0) {
2861 // Set up a frame object for the return address.
2862 uint64_t SlotSize = TD->getPointerSize();
2863 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2865 FuncInfo->setRAIndex(ReturnAddrIndex);
2868 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2872 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2873 bool hasSymbolicDisplacement) {
2874 // Offset should fit into 32 bit immediate field.
2875 if (!isInt<32>(Offset))
2878 // If we don't have a symbolic displacement - we don't have any extra
2880 if (!hasSymbolicDisplacement)
2883 // FIXME: Some tweaks might be needed for medium code model.
2884 if (M != CodeModel::Small && M != CodeModel::Kernel)
2887 // For small code model we assume that latest object is 16MB before end of 31
2888 // bits boundary. We may also accept pretty large negative constants knowing
2889 // that all objects are in the positive half of address space.
2890 if (M == CodeModel::Small && Offset < 16*1024*1024)
2893 // For kernel code model we know that all object resist in the negative half
2894 // of 32bits address space. We may not accept negative offsets, since they may
2895 // be just off and we may accept pretty large positive ones.
2896 if (M == CodeModel::Kernel && Offset > 0)
2902 /// isCalleePop - Determines whether the callee is required to pop its
2903 /// own arguments. Callee pop is necessary to support tail calls.
2904 bool X86::isCalleePop(CallingConv::ID CallingConv,
2905 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2909 switch (CallingConv) {
2912 case CallingConv::X86_StdCall:
2914 case CallingConv::X86_FastCall:
2916 case CallingConv::X86_ThisCall:
2918 case CallingConv::Fast:
2920 case CallingConv::GHC:
2925 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2926 /// specific condition code, returning the condition code and the LHS/RHS of the
2927 /// comparison to make.
2928 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2929 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2931 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2932 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2933 // X > -1 -> X == 0, jump !sign.
2934 RHS = DAG.getConstant(0, RHS.getValueType());
2935 return X86::COND_NS;
2936 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2937 // X < 0 -> X == 0, jump on sign.
2939 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2941 RHS = DAG.getConstant(0, RHS.getValueType());
2942 return X86::COND_LE;
2946 switch (SetCCOpcode) {
2947 default: llvm_unreachable("Invalid integer condition!");
2948 case ISD::SETEQ: return X86::COND_E;
2949 case ISD::SETGT: return X86::COND_G;
2950 case ISD::SETGE: return X86::COND_GE;
2951 case ISD::SETLT: return X86::COND_L;
2952 case ISD::SETLE: return X86::COND_LE;
2953 case ISD::SETNE: return X86::COND_NE;
2954 case ISD::SETULT: return X86::COND_B;
2955 case ISD::SETUGT: return X86::COND_A;
2956 case ISD::SETULE: return X86::COND_BE;
2957 case ISD::SETUGE: return X86::COND_AE;
2961 // First determine if it is required or is profitable to flip the operands.
2963 // If LHS is a foldable load, but RHS is not, flip the condition.
2964 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2965 !ISD::isNON_EXTLoad(RHS.getNode())) {
2966 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2967 std::swap(LHS, RHS);
2970 switch (SetCCOpcode) {
2976 std::swap(LHS, RHS);
2980 // On a floating point condition, the flags are set as follows:
2982 // 0 | 0 | 0 | X > Y
2983 // 0 | 0 | 1 | X < Y
2984 // 1 | 0 | 0 | X == Y
2985 // 1 | 1 | 1 | unordered
2986 switch (SetCCOpcode) {
2987 default: llvm_unreachable("Condcode should be pre-legalized away");
2989 case ISD::SETEQ: return X86::COND_E;
2990 case ISD::SETOLT: // flipped
2992 case ISD::SETGT: return X86::COND_A;
2993 case ISD::SETOLE: // flipped
2995 case ISD::SETGE: return X86::COND_AE;
2996 case ISD::SETUGT: // flipped
2998 case ISD::SETLT: return X86::COND_B;
2999 case ISD::SETUGE: // flipped
3001 case ISD::SETLE: return X86::COND_BE;
3003 case ISD::SETNE: return X86::COND_NE;
3004 case ISD::SETUO: return X86::COND_P;
3005 case ISD::SETO: return X86::COND_NP;
3007 case ISD::SETUNE: return X86::COND_INVALID;
3011 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3012 /// code. Current x86 isa includes the following FP cmov instructions:
3013 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3014 static bool hasFPCMov(unsigned X86CC) {
3030 /// isFPImmLegal - Returns true if the target can instruction select the
3031 /// specified FP immediate natively. If false, the legalizer will
3032 /// materialize the FP immediate as a load from a constant pool.
3033 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3034 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3035 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3041 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3042 /// the specified range (L, H].
3043 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3044 return (Val < 0) || (Val >= Low && Val < Hi);
3047 /// isUndefOrInRange - Return true if every element in Mask, begining
3048 /// from position Pos and ending in Pos+Size, falls within the specified
3049 /// range (L, L+Pos]. or is undef.
3050 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3051 int Pos, int Size, int Low, int Hi) {
3052 for (int i = Pos, e = Pos+Size; i != e; ++i)
3053 if (!isUndefOrInRange(Mask[i], Low, Hi))
3058 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3059 /// specified value.
3060 static bool isUndefOrEqual(int Val, int CmpVal) {
3061 if (Val < 0 || Val == CmpVal)
3066 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3067 /// from position Pos and ending in Pos+Size, falls within the specified
3068 /// sequential range (L, L+Pos]. or is undef.
3069 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3070 int Pos, int Size, int Low) {
3071 for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3072 if (!isUndefOrEqual(Mask[i], Low))
3077 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3078 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3079 /// the second operand.
3080 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3081 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3082 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3083 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3084 return (Mask[0] < 2 && Mask[1] < 2);
3088 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3089 SmallVector<int, 8> M;
3091 return ::isPSHUFDMask(M, N->getValueType(0));
3094 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3095 /// is suitable for input to PSHUFHW.
3096 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3097 if (VT != MVT::v8i16)
3100 // Lower quadword copied in order or undef.
3101 for (int i = 0; i != 4; ++i)
3102 if (Mask[i] >= 0 && Mask[i] != i)
3105 // Upper quadword shuffled.
3106 for (int i = 4; i != 8; ++i)
3107 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3113 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3114 SmallVector<int, 8> M;
3116 return ::isPSHUFHWMask(M, N->getValueType(0));
3119 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3120 /// is suitable for input to PSHUFLW.
3121 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3122 if (VT != MVT::v8i16)
3125 // Upper quadword copied in order.
3126 for (int i = 4; i != 8; ++i)
3127 if (Mask[i] >= 0 && Mask[i] != i)
3130 // Lower quadword shuffled.
3131 for (int i = 0; i != 4; ++i)
3138 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3139 SmallVector<int, 8> M;
3141 return ::isPSHUFLWMask(M, N->getValueType(0));
3144 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3145 /// is suitable for input to PALIGNR.
3146 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3148 int i, e = VT.getVectorNumElements();
3149 if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3152 // Do not handle v2i64 / v2f64 shuffles with palignr.
3153 if (e < 4 || !hasSSSE3)
3156 for (i = 0; i != e; ++i)
3160 // All undef, not a palignr.
3164 // Make sure we're shifting in the right direction.
3168 int s = Mask[i] - i;
3170 // Check the rest of the elements to see if they are consecutive.
3171 for (++i; i != e; ++i) {
3173 if (m >= 0 && m != s+i)
3179 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3180 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3181 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3182 int NumElems = VT.getVectorNumElements();
3183 if (NumElems != 2 && NumElems != 4)
3186 int Half = NumElems / 2;
3187 for (int i = 0; i < Half; ++i)
3188 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3190 for (int i = Half; i < NumElems; ++i)
3191 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3197 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3198 SmallVector<int, 8> M;
3200 return ::isSHUFPMask(M, N->getValueType(0));
3203 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3204 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3205 /// half elements to come from vector 1 (which would equal the dest.) and
3206 /// the upper half to come from vector 2.
3207 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3208 int NumElems = VT.getVectorNumElements();
3210 if (NumElems != 2 && NumElems != 4)
3213 int Half = NumElems / 2;
3214 for (int i = 0; i < Half; ++i)
3215 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3217 for (int i = Half; i < NumElems; ++i)
3218 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3223 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3224 SmallVector<int, 8> M;
3226 return isCommutedSHUFPMask(M, N->getValueType(0));
3229 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3230 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3231 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3232 EVT VT = N->getValueType(0);
3233 unsigned NumElems = VT.getVectorNumElements();
3235 if (VT.getSizeInBits() != 128)
3241 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3242 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3243 isUndefOrEqual(N->getMaskElt(1), 7) &&
3244 isUndefOrEqual(N->getMaskElt(2), 2) &&
3245 isUndefOrEqual(N->getMaskElt(3), 3);
3248 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3249 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3251 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3252 EVT VT = N->getValueType(0);
3253 unsigned NumElems = VT.getVectorNumElements();
3255 if (VT.getSizeInBits() != 128)
3261 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3262 isUndefOrEqual(N->getMaskElt(1), 3) &&
3263 isUndefOrEqual(N->getMaskElt(2), 2) &&
3264 isUndefOrEqual(N->getMaskElt(3), 3);
3267 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3268 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3269 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3270 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3272 if (NumElems != 2 && NumElems != 4)
3275 for (unsigned i = 0; i < NumElems/2; ++i)
3276 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3279 for (unsigned i = NumElems/2; i < NumElems; ++i)
3280 if (!isUndefOrEqual(N->getMaskElt(i), i))
3286 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3287 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3288 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3289 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3291 if ((NumElems != 2 && NumElems != 4)
3292 || N->getValueType(0).getSizeInBits() > 128)
3295 for (unsigned i = 0; i < NumElems/2; ++i)
3296 if (!isUndefOrEqual(N->getMaskElt(i), i))
3299 for (unsigned i = 0; i < NumElems/2; ++i)
3300 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3306 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3307 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3308 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3309 bool V2IsSplat = false) {
3310 int NumElts = VT.getVectorNumElements();
3312 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3313 "Unsupported vector type for unpckh");
3315 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3318 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3319 // independently on 128-bit lanes.
3320 unsigned NumLanes = VT.getSizeInBits()/128;
3321 unsigned NumLaneElts = NumElts/NumLanes;
3324 unsigned End = NumLaneElts;
3325 for (unsigned s = 0; s < NumLanes; ++s) {
3326 for (unsigned i = Start, j = s * NumLaneElts;
3330 int BitI1 = Mask[i+1];
3331 if (!isUndefOrEqual(BitI, j))
3334 if (!isUndefOrEqual(BitI1, NumElts))
3337 if (!isUndefOrEqual(BitI1, j + NumElts))
3341 // Process the next 128 bits.
3342 Start += NumLaneElts;
3349 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3350 SmallVector<int, 8> M;
3352 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3355 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3356 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3357 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3358 bool V2IsSplat = false) {
3359 int NumElts = VT.getVectorNumElements();
3361 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3362 "Unsupported vector type for unpckh");
3364 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3367 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3368 // independently on 128-bit lanes.
3369 unsigned NumLanes = VT.getSizeInBits()/128;
3370 unsigned NumLaneElts = NumElts/NumLanes;
3373 unsigned End = NumLaneElts;
3374 for (unsigned l = 0; l != NumLanes; ++l) {
3375 for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3376 i != End; i += 2, ++j) {
3378 int BitI1 = Mask[i+1];
3379 if (!isUndefOrEqual(BitI, j))
3382 if (isUndefOrEqual(BitI1, NumElts))
3385 if (!isUndefOrEqual(BitI1, j+NumElts))
3389 // Process the next 128 bits.
3390 Start += NumLaneElts;
3396 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3397 SmallVector<int, 8> M;
3399 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3402 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3403 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3405 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3406 int NumElems = VT.getVectorNumElements();
3407 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3410 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3411 // independently on 128-bit lanes.
3412 unsigned NumLanes = VT.getSizeInBits() / 128;
3413 unsigned NumLaneElts = NumElems / NumLanes;
3415 for (unsigned s = 0; s < NumLanes; ++s) {
3416 for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3417 i != NumLaneElts * (s + 1);
3420 int BitI1 = Mask[i+1];
3422 if (!isUndefOrEqual(BitI, j))
3424 if (!isUndefOrEqual(BitI1, j))
3432 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3433 SmallVector<int, 8> M;
3435 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3438 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3439 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3441 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3442 int NumElems = VT.getVectorNumElements();
3443 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3446 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3448 int BitI1 = Mask[i+1];
3449 if (!isUndefOrEqual(BitI, j))
3451 if (!isUndefOrEqual(BitI1, j))
3457 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3458 SmallVector<int, 8> M;
3460 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3463 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3464 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3465 /// MOVSD, and MOVD, i.e. setting the lowest element.
3466 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3467 if (VT.getVectorElementType().getSizeInBits() < 32)
3470 int NumElts = VT.getVectorNumElements();
3472 if (!isUndefOrEqual(Mask[0], NumElts))
3475 for (int i = 1; i < NumElts; ++i)
3476 if (!isUndefOrEqual(Mask[i], i))
3482 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3483 SmallVector<int, 8> M;
3485 return ::isMOVLMask(M, N->getValueType(0));
3488 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3489 /// as permutations between 128-bit chunks or halves. As an example: this
3491 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3492 /// The first half comes from the second half of V1 and the second half from the
3493 /// the second half of V2.
3494 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3495 const X86Subtarget *Subtarget) {
3496 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3499 // The shuffle result is divided into half A and half B. In total the two
3500 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3501 // B must come from C, D, E or F.
3502 int HalfSize = VT.getVectorNumElements()/2;
3503 bool MatchA = false, MatchB = false;
3505 // Check if A comes from one of C, D, E, F.
3506 for (int Half = 0; Half < 4; ++Half) {
3507 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3513 // Check if B comes from one of C, D, E, F.
3514 for (int Half = 0; Half < 4; ++Half) {
3515 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3521 return MatchA && MatchB;
3524 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3525 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3526 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3527 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3528 EVT VT = SVOp->getValueType(0);
3530 int HalfSize = VT.getVectorNumElements()/2;
3532 int FstHalf = 0, SndHalf = 0;
3533 for (int i = 0; i < HalfSize; ++i) {
3534 if (SVOp->getMaskElt(i) > 0) {
3535 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3539 for (int i = HalfSize; i < HalfSize*2; ++i) {
3540 if (SVOp->getMaskElt(i) > 0) {
3541 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3546 return (FstHalf | (SndHalf << 4));
3549 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3550 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3551 /// Note that VPERMIL mask matching is different depending whether theunderlying
3552 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3553 /// to the same elements of the low, but to the higher half of the source.
3554 /// In VPERMILPD the two lanes could be shuffled independently of each other
3555 /// with the same restriction that lanes can't be crossed.
3556 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3557 const X86Subtarget *Subtarget) {
3558 int NumElts = VT.getVectorNumElements();
3559 int NumLanes = VT.getSizeInBits()/128;
3561 if (!Subtarget->hasAVX())
3564 // Match any permutation of 128-bit vector with 64-bit types
3565 if (NumLanes == 1 && NumElts != 2)
3568 // Only match 256-bit with 32 types
3569 if (VT.getSizeInBits() == 256 && NumElts != 4)
3572 // The mask on the high lane is independent of the low. Both can match
3573 // any element in inside its own lane, but can't cross.
3574 int LaneSize = NumElts/NumLanes;
3575 for (int l = 0; l < NumLanes; ++l)
3576 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3577 int LaneStart = l*LaneSize;
3578 if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3585 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3586 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3587 /// Note that VPERMIL mask matching is different depending whether theunderlying
3588 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3589 /// to the same elements of the low, but to the higher half of the source.
3590 /// In VPERMILPD the two lanes could be shuffled independently of each other
3591 /// with the same restriction that lanes can't be crossed.
3592 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3593 const X86Subtarget *Subtarget) {
3594 unsigned NumElts = VT.getVectorNumElements();
3595 unsigned NumLanes = VT.getSizeInBits()/128;
3597 if (!Subtarget->hasAVX())
3600 // Match any permutation of 128-bit vector with 32-bit types
3601 if (NumLanes == 1 && NumElts != 4)
3604 // Only match 256-bit with 32 types
3605 if (VT.getSizeInBits() == 256 && NumElts != 8)
3608 // The mask on the high lane should be the same as the low. Actually,
3609 // they can differ if any of the corresponding index in a lane is undef
3610 // and the other stays in range.
3611 int LaneSize = NumElts/NumLanes;
3612 for (int i = 0; i < LaneSize; ++i) {
3613 int HighElt = i+LaneSize;
3614 bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3615 bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3617 if (!HighValid || !LowValid)
3619 if (Mask[i] < 0 || Mask[HighElt] < 0)
3621 if (Mask[HighElt]-Mask[i] != LaneSize)
3628 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3629 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3630 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3631 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3632 EVT VT = SVOp->getValueType(0);
3634 int NumElts = VT.getVectorNumElements();
3635 int NumLanes = VT.getSizeInBits()/128;
3636 int LaneSize = NumElts/NumLanes;
3638 // Although the mask is equal for both lanes do it twice to get the cases
3639 // where a mask will match because the same mask element is undef on the
3640 // first half but valid on the second. This would get pathological cases
3641 // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3643 for (int l = 0; l < NumLanes; ++l) {
3644 for (int i = 0; i < LaneSize; ++i) {
3645 int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3648 if (MaskElt >= LaneSize)
3649 MaskElt -= LaneSize;
3650 Mask |= MaskElt << (i*2);
3657 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3658 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3659 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3660 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3661 EVT VT = SVOp->getValueType(0);
3663 int NumElts = VT.getVectorNumElements();
3664 int NumLanes = VT.getSizeInBits()/128;
3667 int LaneSize = NumElts/NumLanes;
3668 for (int l = 0; l < NumLanes; ++l)
3669 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3670 int MaskElt = SVOp->getMaskElt(i);
3673 Mask |= (MaskElt-l*LaneSize) << i;
3679 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3680 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3681 /// element of vector 2 and the other elements to come from vector 1 in order.
3682 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3683 bool V2IsSplat = false, bool V2IsUndef = false) {
3684 int NumOps = VT.getVectorNumElements();
3685 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3688 if (!isUndefOrEqual(Mask[0], 0))
3691 for (int i = 1; i < NumOps; ++i)
3692 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3693 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3694 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3700 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3701 bool V2IsUndef = false) {
3702 SmallVector<int, 8> M;
3704 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3707 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3708 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3709 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3710 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3711 const X86Subtarget *Subtarget) {
3712 if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3715 // The second vector must be undef
3716 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3719 EVT VT = N->getValueType(0);
3720 unsigned NumElems = VT.getVectorNumElements();
3722 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3723 (VT.getSizeInBits() == 256 && NumElems != 8))
3726 // "i+1" is the value the indexed mask element must have
3727 for (unsigned i = 0; i < NumElems; i += 2)
3728 if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3729 !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3735 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3736 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3737 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3738 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3739 const X86Subtarget *Subtarget) {
3740 if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3743 // The second vector must be undef
3744 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3747 EVT VT = N->getValueType(0);
3748 unsigned NumElems = VT.getVectorNumElements();
3750 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3751 (VT.getSizeInBits() == 256 && NumElems != 8))
3754 // "i" is the value the indexed mask element must have
3755 for (unsigned i = 0; i < NumElems; i += 2)
3756 if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3757 !isUndefOrEqual(N->getMaskElt(i+1), i))
3763 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3764 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3765 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3766 int e = N->getValueType(0).getVectorNumElements() / 2;
3768 for (int i = 0; i < e; ++i)
3769 if (!isUndefOrEqual(N->getMaskElt(i), i))
3771 for (int i = 0; i < e; ++i)
3772 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3777 /// isVEXTRACTF128Index - Return true if the specified
3778 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3779 /// suitable for input to VEXTRACTF128.
3780 bool X86::isVEXTRACTF128Index(SDNode *N) {
3781 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3784 // The index should be aligned on a 128-bit boundary.
3786 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3788 unsigned VL = N->getValueType(0).getVectorNumElements();
3789 unsigned VBits = N->getValueType(0).getSizeInBits();
3790 unsigned ElSize = VBits / VL;
3791 bool Result = (Index * ElSize) % 128 == 0;
3796 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3797 /// operand specifies a subvector insert that is suitable for input to
3799 bool X86::isVINSERTF128Index(SDNode *N) {
3800 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3803 // The index should be aligned on a 128-bit boundary.
3805 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3807 unsigned VL = N->getValueType(0).getVectorNumElements();
3808 unsigned VBits = N->getValueType(0).getSizeInBits();
3809 unsigned ElSize = VBits / VL;
3810 bool Result = (Index * ElSize) % 128 == 0;
3815 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3816 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3817 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3818 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3819 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3821 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3823 for (int i = 0; i < NumOperands; ++i) {
3824 int Val = SVOp->getMaskElt(NumOperands-i-1);
3825 if (Val < 0) Val = 0;
3826 if (Val >= NumOperands) Val -= NumOperands;
3828 if (i != NumOperands - 1)
3834 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3835 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3836 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3837 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3839 // 8 nodes, but we only care about the last 4.
3840 for (unsigned i = 7; i >= 4; --i) {
3841 int Val = SVOp->getMaskElt(i);
3850 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3851 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3852 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3853 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3855 // 8 nodes, but we only care about the first 4.
3856 for (int i = 3; i >= 0; --i) {
3857 int Val = SVOp->getMaskElt(i);
3866 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3867 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3868 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3869 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3870 EVT VVT = N->getValueType(0);
3871 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3875 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3876 Val = SVOp->getMaskElt(i);
3880 assert(Val - i > 0 && "PALIGNR imm should be positive");
3881 return (Val - i) * EltSize;
3884 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3885 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3887 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3888 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3889 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3892 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3894 EVT VecVT = N->getOperand(0).getValueType();
3895 EVT ElVT = VecVT.getVectorElementType();
3897 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3898 return Index / NumElemsPerChunk;
3901 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3902 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3904 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3905 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3906 llvm_unreachable("Illegal insert subvector for VINSERTF128");
3909 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3911 EVT VecVT = N->getValueType(0);
3912 EVT ElVT = VecVT.getVectorElementType();
3914 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3915 return Index / NumElemsPerChunk;
3918 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3920 bool X86::isZeroNode(SDValue Elt) {
3921 return ((isa<ConstantSDNode>(Elt) &&
3922 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3923 (isa<ConstantFPSDNode>(Elt) &&
3924 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3927 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3928 /// their permute mask.
3929 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3930 SelectionDAG &DAG) {
3931 EVT VT = SVOp->getValueType(0);
3932 unsigned NumElems = VT.getVectorNumElements();
3933 SmallVector<int, 8> MaskVec;
3935 for (unsigned i = 0; i != NumElems; ++i) {
3936 int idx = SVOp->getMaskElt(i);
3938 MaskVec.push_back(idx);
3939 else if (idx < (int)NumElems)
3940 MaskVec.push_back(idx + NumElems);
3942 MaskVec.push_back(idx - NumElems);
3944 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3945 SVOp->getOperand(0), &MaskVec[0]);
3948 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3949 /// the two vector operands have swapped position.
3950 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3951 unsigned NumElems = VT.getVectorNumElements();
3952 for (unsigned i = 0; i != NumElems; ++i) {
3956 else if (idx < (int)NumElems)
3957 Mask[i] = idx + NumElems;
3959 Mask[i] = idx - NumElems;
3963 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3964 /// match movhlps. The lower half elements should come from upper half of
3965 /// V1 (and in order), and the upper half elements should come from the upper
3966 /// half of V2 (and in order).
3967 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3968 EVT VT = Op->getValueType(0);
3969 if (VT.getSizeInBits() != 128)
3971 if (VT.getVectorNumElements() != 4)
3973 for (unsigned i = 0, e = 2; i != e; ++i)
3974 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3976 for (unsigned i = 2; i != 4; ++i)
3977 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3982 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3983 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3985 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3986 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3988 N = N->getOperand(0).getNode();
3989 if (!ISD::isNON_EXTLoad(N))
3992 *LD = cast<LoadSDNode>(N);
3996 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3997 /// match movlp{s|d}. The lower half elements should come from lower half of
3998 /// V1 (and in order), and the upper half elements should come from the upper
3999 /// half of V2 (and in order). And since V1 will become the source of the
4000 /// MOVLP, it must be either a vector load or a scalar load to vector.
4001 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4002 ShuffleVectorSDNode *Op) {
4003 EVT VT = Op->getValueType(0);
4004 if (VT.getSizeInBits() != 128)
4007 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4009 // Is V2 is a vector load, don't do this transformation. We will try to use
4010 // load folding shufps op.
4011 if (ISD::isNON_EXTLoad(V2))
4014 unsigned NumElems = VT.getVectorNumElements();
4016 if (NumElems != 2 && NumElems != 4)
4018 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4019 if (!isUndefOrEqual(Op->getMaskElt(i), i))
4021 for (unsigned i = NumElems/2; i != NumElems; ++i)
4022 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4027 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4029 static bool isSplatVector(SDNode *N) {
4030 if (N->getOpcode() != ISD::BUILD_VECTOR)
4033 SDValue SplatValue = N->getOperand(0);
4034 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4035 if (N->getOperand(i) != SplatValue)
4040 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4041 /// to an zero vector.
4042 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4043 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4044 SDValue V1 = N->getOperand(0);
4045 SDValue V2 = N->getOperand(1);
4046 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4047 for (unsigned i = 0; i != NumElems; ++i) {
4048 int Idx = N->getMaskElt(i);
4049 if (Idx >= (int)NumElems) {
4050 unsigned Opc = V2.getOpcode();
4051 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4053 if (Opc != ISD::BUILD_VECTOR ||
4054 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4056 } else if (Idx >= 0) {
4057 unsigned Opc = V1.getOpcode();
4058 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4060 if (Opc != ISD::BUILD_VECTOR ||
4061 !X86::isZeroNode(V1.getOperand(Idx)))
4068 /// getZeroVector - Returns a vector of specified type with all zero elements.
4070 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
4072 assert(VT.isVector() && "Expected a vector type");
4074 // Always build SSE zero vectors as <4 x i32> bitcasted
4075 // to their dest type. This ensures they get CSE'd.
4077 if (VT.getSizeInBits() == 128) { // SSE
4078 if (HasSSE2) { // SSE2
4079 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4080 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4082 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4083 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4085 } else if (VT.getSizeInBits() == 256) { // AVX
4086 // 256-bit logic and arithmetic instructions in AVX are
4087 // all floating-point, no support for integer ops. Default
4088 // to emitting fp zeroed vectors then.
4089 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4090 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4091 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4093 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4096 /// getOnesVector - Returns a vector of specified type with all bits set.
4097 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4098 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4099 /// original type, ensuring they get CSE'd.
4100 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4101 assert(VT.isVector() && "Expected a vector type");
4102 assert((VT.is128BitVector() || VT.is256BitVector())
4103 && "Expected a 128-bit or 256-bit vector type");
4105 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4106 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4107 Cst, Cst, Cst, Cst);
4109 if (VT.is256BitVector()) {
4110 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4111 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4112 Vec = Insert128BitVector(InsV, Vec,
4113 DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4116 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4119 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4120 /// that point to V2 points to its first element.
4121 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4122 EVT VT = SVOp->getValueType(0);
4123 unsigned NumElems = VT.getVectorNumElements();
4125 bool Changed = false;
4126 SmallVector<int, 8> MaskVec;
4127 SVOp->getMask(MaskVec);
4129 for (unsigned i = 0; i != NumElems; ++i) {
4130 if (MaskVec[i] > (int)NumElems) {
4131 MaskVec[i] = NumElems;
4136 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4137 SVOp->getOperand(1), &MaskVec[0]);
4138 return SDValue(SVOp, 0);
4141 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4142 /// operation of specified width.
4143 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4145 unsigned NumElems = VT.getVectorNumElements();
4146 SmallVector<int, 8> Mask;
4147 Mask.push_back(NumElems);
4148 for (unsigned i = 1; i != NumElems; ++i)
4150 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4153 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4154 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4156 unsigned NumElems = VT.getVectorNumElements();
4157 SmallVector<int, 8> Mask;
4158 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4160 Mask.push_back(i + NumElems);
4162 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4165 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4166 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4168 unsigned NumElems = VT.getVectorNumElements();
4169 unsigned Half = NumElems/2;
4170 SmallVector<int, 8> Mask;
4171 for (unsigned i = 0; i != Half; ++i) {
4172 Mask.push_back(i + Half);
4173 Mask.push_back(i + NumElems + Half);
4175 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4178 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4179 // a generic shuffle instruction because the target has no such instructions.
4180 // Generate shuffles which repeat i16 and i8 several times until they can be
4181 // represented by v4f32 and then be manipulated by target suported shuffles.
4182 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4183 EVT VT = V.getValueType();
4184 int NumElems = VT.getVectorNumElements();
4185 DebugLoc dl = V.getDebugLoc();
4187 while (NumElems > 4) {
4188 if (EltNo < NumElems/2) {
4189 V = getUnpackl(DAG, dl, VT, V, V);
4191 V = getUnpackh(DAG, dl, VT, V, V);
4192 EltNo -= NumElems/2;
4199 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4200 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4201 EVT VT = V.getValueType();
4202 DebugLoc dl = V.getDebugLoc();
4203 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4204 && "Vector size not supported");
4206 if (VT.getSizeInBits() == 128) {
4207 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4208 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4209 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4212 // To use VPERMILPS to splat scalars, the second half of indicies must
4213 // refer to the higher part, which is a duplication of the lower one,
4214 // because VPERMILPS can only handle in-lane permutations.
4215 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4216 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4218 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4219 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4223 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4226 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4227 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4228 EVT SrcVT = SV->getValueType(0);
4229 SDValue V1 = SV->getOperand(0);
4230 DebugLoc dl = SV->getDebugLoc();
4232 int EltNo = SV->getSplatIndex();
4233 int NumElems = SrcVT.getVectorNumElements();
4234 unsigned Size = SrcVT.getSizeInBits();
4236 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4237 "Unknown how to promote splat for type");
4239 // Extract the 128-bit part containing the splat element and update
4240 // the splat element index when it refers to the higher register.
4242 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4243 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4245 EltNo -= NumElems/2;
4248 // All i16 and i8 vector types can't be used directly by a generic shuffle
4249 // instruction because the target has no such instruction. Generate shuffles
4250 // which repeat i16 and i8 several times until they fit in i32, and then can
4251 // be manipulated by target suported shuffles.
4252 EVT EltVT = SrcVT.getVectorElementType();
4253 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4254 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4256 // Recreate the 256-bit vector and place the same 128-bit vector
4257 // into the low and high part. This is necessary because we want
4258 // to use VPERM* to shuffle the vectors
4260 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4261 DAG.getConstant(0, MVT::i32), DAG, dl);
4262 V1 = Insert128BitVector(InsV, V1,
4263 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4266 return getLegalSplat(DAG, V1, EltNo);
4269 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4270 /// vector of zero or undef vector. This produces a shuffle where the low
4271 /// element of V2 is swizzled into the zero/undef vector, landing at element
4272 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4273 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4274 bool isZero, bool HasSSE2,
4275 SelectionDAG &DAG) {
4276 EVT VT = V2.getValueType();
4278 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4279 unsigned NumElems = VT.getVectorNumElements();
4280 SmallVector<int, 16> MaskVec;
4281 for (unsigned i = 0; i != NumElems; ++i)
4282 // If this is the insertion idx, put the low elt of V2 here.
4283 MaskVec.push_back(i == Idx ? NumElems : i);
4284 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4287 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4288 /// element of the result of the vector shuffle.
4289 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4292 return SDValue(); // Limit search depth.
4294 SDValue V = SDValue(N, 0);
4295 EVT VT = V.getValueType();
4296 unsigned Opcode = V.getOpcode();
4298 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4299 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4300 Index = SV->getMaskElt(Index);
4303 return DAG.getUNDEF(VT.getVectorElementType());
4305 int NumElems = VT.getVectorNumElements();
4306 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4307 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4310 // Recurse into target specific vector shuffles to find scalars.
4311 if (isTargetShuffle(Opcode)) {
4312 int NumElems = VT.getVectorNumElements();
4313 SmallVector<unsigned, 16> ShuffleMask;
4317 case X86ISD::SHUFPS:
4318 case X86ISD::SHUFPD:
4319 ImmN = N->getOperand(N->getNumOperands()-1);
4320 DecodeSHUFPSMask(NumElems,
4321 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4324 case X86ISD::PUNPCKHBW:
4325 case X86ISD::PUNPCKHWD:
4326 case X86ISD::PUNPCKHDQ:
4327 case X86ISD::PUNPCKHQDQ:
4328 DecodePUNPCKHMask(NumElems, ShuffleMask);
4330 case X86ISD::UNPCKHPS:
4331 case X86ISD::UNPCKHPD:
4332 case X86ISD::VUNPCKHPSY:
4333 case X86ISD::VUNPCKHPDY:
4334 DecodeUNPCKHPMask(NumElems, ShuffleMask);
4336 case X86ISD::PUNPCKLBW:
4337 case X86ISD::PUNPCKLWD:
4338 case X86ISD::PUNPCKLDQ:
4339 case X86ISD::PUNPCKLQDQ:
4340 DecodePUNPCKLMask(VT, ShuffleMask);
4342 case X86ISD::UNPCKLPS:
4343 case X86ISD::UNPCKLPD:
4344 case X86ISD::VUNPCKLPSY:
4345 case X86ISD::VUNPCKLPDY:
4346 DecodeUNPCKLPMask(VT, ShuffleMask);
4348 case X86ISD::MOVHLPS:
4349 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4351 case X86ISD::MOVLHPS:
4352 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4354 case X86ISD::PSHUFD:
4355 ImmN = N->getOperand(N->getNumOperands()-1);
4356 DecodePSHUFMask(NumElems,
4357 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4360 case X86ISD::PSHUFHW:
4361 ImmN = N->getOperand(N->getNumOperands()-1);
4362 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4365 case X86ISD::PSHUFLW:
4366 ImmN = N->getOperand(N->getNumOperands()-1);
4367 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4371 case X86ISD::MOVSD: {
4372 // The index 0 always comes from the first element of the second source,
4373 // this is why MOVSS and MOVSD are used in the first place. The other
4374 // elements come from the other positions of the first source vector.
4375 unsigned OpNum = (Index == 0) ? 1 : 0;
4376 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4379 case X86ISD::VPERMILPS:
4380 ImmN = N->getOperand(N->getNumOperands()-1);
4381 DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4384 case X86ISD::VPERMILPSY:
4385 ImmN = N->getOperand(N->getNumOperands()-1);
4386 DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4389 case X86ISD::VPERMILPD:
4390 ImmN = N->getOperand(N->getNumOperands()-1);
4391 DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4394 case X86ISD::VPERMILPDY:
4395 ImmN = N->getOperand(N->getNumOperands()-1);
4396 DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4399 case X86ISD::VPERM2F128:
4400 ImmN = N->getOperand(N->getNumOperands()-1);
4401 DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4405 assert("not implemented for target shuffle node");
4409 Index = ShuffleMask[Index];
4411 return DAG.getUNDEF(VT.getVectorElementType());
4413 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4414 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4418 // Actual nodes that may contain scalar elements
4419 if (Opcode == ISD::BITCAST) {
4420 V = V.getOperand(0);
4421 EVT SrcVT = V.getValueType();
4422 unsigned NumElems = VT.getVectorNumElements();
4424 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4428 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4429 return (Index == 0) ? V.getOperand(0)
4430 : DAG.getUNDEF(VT.getVectorElementType());
4432 if (V.getOpcode() == ISD::BUILD_VECTOR)
4433 return V.getOperand(Index);
4438 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4439 /// shuffle operation which come from a consecutively from a zero. The
4440 /// search can start in two different directions, from left or right.
4442 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4443 bool ZerosFromLeft, SelectionDAG &DAG) {
4446 while (i < NumElems) {
4447 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4448 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4449 if (!(Elt.getNode() &&
4450 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4458 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4459 /// MaskE correspond consecutively to elements from one of the vector operands,
4460 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4462 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4463 int OpIdx, int NumElems, unsigned &OpNum) {
4464 bool SeenV1 = false;
4465 bool SeenV2 = false;
4467 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4468 int Idx = SVOp->getMaskElt(i);
4469 // Ignore undef indicies
4478 // Only accept consecutive elements from the same vector
4479 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4483 OpNum = SeenV1 ? 0 : 1;
4487 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4488 /// logical left shift of a vector.
4489 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4490 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4491 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4492 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4493 false /* check zeros from right */, DAG);
4499 // Considering the elements in the mask that are not consecutive zeros,
4500 // check if they consecutively come from only one of the source vectors.
4502 // V1 = {X, A, B, C} 0
4504 // vector_shuffle V1, V2 <1, 2, 3, X>
4506 if (!isShuffleMaskConsecutive(SVOp,
4507 0, // Mask Start Index
4508 NumElems-NumZeros-1, // Mask End Index
4509 NumZeros, // Where to start looking in the src vector
4510 NumElems, // Number of elements in vector
4511 OpSrc)) // Which source operand ?
4516 ShVal = SVOp->getOperand(OpSrc);
4520 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4521 /// logical left shift of a vector.
4522 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4523 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4524 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4525 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4526 true /* check zeros from left */, DAG);
4532 // Considering the elements in the mask that are not consecutive zeros,
4533 // check if they consecutively come from only one of the source vectors.
4535 // 0 { A, B, X, X } = V2
4537 // vector_shuffle V1, V2 <X, X, 4, 5>
4539 if (!isShuffleMaskConsecutive(SVOp,
4540 NumZeros, // Mask Start Index
4541 NumElems-1, // Mask End Index
4542 0, // Where to start looking in the src vector
4543 NumElems, // Number of elements in vector
4544 OpSrc)) // Which source operand ?
4549 ShVal = SVOp->getOperand(OpSrc);
4553 /// isVectorShift - Returns true if the shuffle can be implemented as a
4554 /// logical left or right shift of a vector.
4555 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4556 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4557 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4558 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4564 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4566 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4567 unsigned NumNonZero, unsigned NumZero,
4569 const TargetLowering &TLI) {
4573 DebugLoc dl = Op.getDebugLoc();
4576 for (unsigned i = 0; i < 16; ++i) {
4577 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4578 if (ThisIsNonZero && First) {
4580 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4582 V = DAG.getUNDEF(MVT::v8i16);
4587 SDValue ThisElt(0, 0), LastElt(0, 0);
4588 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4589 if (LastIsNonZero) {
4590 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4591 MVT::i16, Op.getOperand(i-1));
4593 if (ThisIsNonZero) {
4594 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4595 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4596 ThisElt, DAG.getConstant(8, MVT::i8));
4598 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4602 if (ThisElt.getNode())
4603 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4604 DAG.getIntPtrConstant(i/2));
4608 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4611 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4613 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4614 unsigned NumNonZero, unsigned NumZero,
4616 const TargetLowering &TLI) {
4620 DebugLoc dl = Op.getDebugLoc();
4623 for (unsigned i = 0; i < 8; ++i) {
4624 bool isNonZero = (NonZeros & (1 << i)) != 0;
4628 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4630 V = DAG.getUNDEF(MVT::v8i16);
4633 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4634 MVT::v8i16, V, Op.getOperand(i),
4635 DAG.getIntPtrConstant(i));
4642 /// getVShift - Return a vector logical shift node.
4644 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4645 unsigned NumBits, SelectionDAG &DAG,
4646 const TargetLowering &TLI, DebugLoc dl) {
4647 EVT ShVT = MVT::v2i64;
4648 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4649 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4650 return DAG.getNode(ISD::BITCAST, dl, VT,
4651 DAG.getNode(Opc, dl, ShVT, SrcOp,
4652 DAG.getConstant(NumBits,
4653 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4657 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4658 SelectionDAG &DAG) const {
4660 // Check if the scalar load can be widened into a vector load. And if
4661 // the address is "base + cst" see if the cst can be "absorbed" into
4662 // the shuffle mask.
4663 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4664 SDValue Ptr = LD->getBasePtr();
4665 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4667 EVT PVT = LD->getValueType(0);
4668 if (PVT != MVT::i32 && PVT != MVT::f32)
4673 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4674 FI = FINode->getIndex();
4676 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4677 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4678 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4679 Offset = Ptr.getConstantOperandVal(1);
4680 Ptr = Ptr.getOperand(0);
4685 // FIXME: 256-bit vector instructions don't require a strict alignment,
4686 // improve this code to support it better.
4687 unsigned RequiredAlign = VT.getSizeInBits()/8;
4688 SDValue Chain = LD->getChain();
4689 // Make sure the stack object alignment is at least 16 or 32.
4690 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4691 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4692 if (MFI->isFixedObjectIndex(FI)) {
4693 // Can't change the alignment. FIXME: It's possible to compute
4694 // the exact stack offset and reference FI + adjust offset instead.
4695 // If someone *really* cares about this. That's the way to implement it.
4698 MFI->setObjectAlignment(FI, RequiredAlign);
4702 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4703 // Ptr + (Offset & ~15).
4706 if ((Offset % RequiredAlign) & 3)
4708 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4710 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4711 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4713 int EltNo = (Offset - StartOffset) >> 2;
4714 int NumElems = VT.getVectorNumElements();
4716 EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4717 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4718 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4719 LD->getPointerInfo().getWithOffset(StartOffset),
4722 // Canonicalize it to a v4i32 or v8i32 shuffle.
4723 SmallVector<int, 8> Mask;
4724 for (int i = 0; i < NumElems; ++i)
4725 Mask.push_back(EltNo);
4727 V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4728 return DAG.getNode(ISD::BITCAST, dl, NVT,
4729 DAG.getVectorShuffle(CanonVT, dl, V1,
4730 DAG.getUNDEF(CanonVT),&Mask[0]));
4736 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4737 /// vector of type 'VT', see if the elements can be replaced by a single large
4738 /// load which has the same value as a build_vector whose operands are 'elts'.
4740 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4742 /// FIXME: we'd also like to handle the case where the last elements are zero
4743 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4744 /// There's even a handy isZeroNode for that purpose.
4745 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4746 DebugLoc &DL, SelectionDAG &DAG) {
4747 EVT EltVT = VT.getVectorElementType();
4748 unsigned NumElems = Elts.size();
4750 LoadSDNode *LDBase = NULL;
4751 unsigned LastLoadedElt = -1U;
4753 // For each element in the initializer, see if we've found a load or an undef.
4754 // If we don't find an initial load element, or later load elements are
4755 // non-consecutive, bail out.
4756 for (unsigned i = 0; i < NumElems; ++i) {
4757 SDValue Elt = Elts[i];
4759 if (!Elt.getNode() ||
4760 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4763 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4765 LDBase = cast<LoadSDNode>(Elt.getNode());
4769 if (Elt.getOpcode() == ISD::UNDEF)
4772 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4773 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4778 // If we have found an entire vector of loads and undefs, then return a large
4779 // load of the entire vector width starting at the base pointer. If we found
4780 // consecutive loads for the low half, generate a vzext_load node.
4781 if (LastLoadedElt == NumElems - 1) {
4782 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4783 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4784 LDBase->getPointerInfo(),
4785 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4786 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4787 LDBase->getPointerInfo(),
4788 LDBase->isVolatile(), LDBase->isNonTemporal(),
4789 LDBase->getAlignment());
4790 } else if (NumElems == 4 && LastLoadedElt == 1 &&
4791 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4792 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4793 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4794 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4796 LDBase->getMemOperand());
4797 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4803 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4804 DebugLoc dl = Op.getDebugLoc();
4806 EVT VT = Op.getValueType();
4807 EVT ExtVT = VT.getVectorElementType();
4808 unsigned NumElems = Op.getNumOperands();
4810 // Vectors containing all zeros can be matched by pxor and xorps later
4811 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
4812 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
4813 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
4814 if (Op.getValueType() == MVT::v4i32 ||
4815 Op.getValueType() == MVT::v8i32)
4818 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4821 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
4822 // vectors or broken into v4i32 operations on 256-bit vectors.
4823 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
4824 if (Op.getValueType() == MVT::v4i32)
4827 return getOnesVector(Op.getValueType(), DAG, dl);
4830 unsigned EVTBits = ExtVT.getSizeInBits();
4832 unsigned NumZero = 0;
4833 unsigned NumNonZero = 0;
4834 unsigned NonZeros = 0;
4835 bool IsAllConstants = true;
4836 SmallSet<SDValue, 8> Values;
4837 for (unsigned i = 0; i < NumElems; ++i) {
4838 SDValue Elt = Op.getOperand(i);
4839 if (Elt.getOpcode() == ISD::UNDEF)
4842 if (Elt.getOpcode() != ISD::Constant &&
4843 Elt.getOpcode() != ISD::ConstantFP)
4844 IsAllConstants = false;
4845 if (X86::isZeroNode(Elt))
4848 NonZeros |= (1 << i);
4853 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4854 if (NumNonZero == 0)
4855 return DAG.getUNDEF(VT);
4857 // Special case for single non-zero, non-undef, element.
4858 if (NumNonZero == 1) {
4859 unsigned Idx = CountTrailingZeros_32(NonZeros);
4860 SDValue Item = Op.getOperand(Idx);
4862 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4863 // the value are obviously zero, truncate the value to i32 and do the
4864 // insertion that way. Only do this if the value is non-constant or if the
4865 // value is a constant being inserted into element 0. It is cheaper to do
4866 // a constant pool load than it is to do a movd + shuffle.
4867 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4868 (!IsAllConstants || Idx == 0)) {
4869 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4871 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4872 EVT VecVT = MVT::v4i32;
4873 unsigned VecElts = 4;
4875 // Truncate the value (which may itself be a constant) to i32, and
4876 // convert it to a vector with movd (S2V+shuffle to zero extend).
4877 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4878 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4879 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4880 Subtarget->hasSSE2(), DAG);
4882 // Now we have our 32-bit value zero extended in the low element of
4883 // a vector. If Idx != 0, swizzle it into place.
4885 SmallVector<int, 4> Mask;
4886 Mask.push_back(Idx);
4887 for (unsigned i = 1; i != VecElts; ++i)
4889 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4890 DAG.getUNDEF(Item.getValueType()),
4893 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4897 // If we have a constant or non-constant insertion into the low element of
4898 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4899 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4900 // depending on what the source datatype is.
4903 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4904 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4905 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4906 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4907 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4908 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4910 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4911 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4912 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4913 EVT MiddleVT = MVT::v4i32;
4914 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4915 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4916 Subtarget->hasSSE2(), DAG);
4917 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4921 // Is it a vector logical left shift?
4922 if (NumElems == 2 && Idx == 1 &&
4923 X86::isZeroNode(Op.getOperand(0)) &&
4924 !X86::isZeroNode(Op.getOperand(1))) {
4925 unsigned NumBits = VT.getSizeInBits();
4926 return getVShift(true, VT,
4927 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4928 VT, Op.getOperand(1)),
4929 NumBits/2, DAG, *this, dl);
4932 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4935 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4936 // is a non-constant being inserted into an element other than the low one,
4937 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4938 // movd/movss) to move this into the low element, then shuffle it into
4940 if (EVTBits == 32) {
4941 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4943 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4944 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4945 Subtarget->hasSSE2(), DAG);
4946 SmallVector<int, 8> MaskVec;
4947 for (unsigned i = 0; i < NumElems; i++)
4948 MaskVec.push_back(i == Idx ? 0 : 1);
4949 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4953 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4954 if (Values.size() == 1) {
4955 if (EVTBits == 32) {
4956 // Instead of a shuffle like this:
4957 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4958 // Check if it's possible to issue this instead.
4959 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4960 unsigned Idx = CountTrailingZeros_32(NonZeros);
4961 SDValue Item = Op.getOperand(Idx);
4962 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4963 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4968 // A vector full of immediates; various special cases are already
4969 // handled, so this is best done with a single constant-pool load.
4973 // For AVX-length vectors, build the individual 128-bit pieces and use
4974 // shuffles to put them in place.
4975 if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
4976 SmallVector<SDValue, 32> V;
4977 for (unsigned i = 0; i < NumElems; ++i)
4978 V.push_back(Op.getOperand(i));
4980 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4982 // Build both the lower and upper subvector.
4983 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4984 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4987 // Recreate the wider vector with the lower and upper part.
4988 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
4989 DAG.getConstant(0, MVT::i32), DAG, dl);
4990 return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
4994 // Let legalizer expand 2-wide build_vectors.
4995 if (EVTBits == 64) {
4996 if (NumNonZero == 1) {
4997 // One half is zero or undef.
4998 unsigned Idx = CountTrailingZeros_32(NonZeros);
4999 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5000 Op.getOperand(Idx));
5001 return getShuffleVectorZeroOrUndef(V2, Idx, true,
5002 Subtarget->hasSSE2(), DAG);
5007 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5008 if (EVTBits == 8 && NumElems == 16) {
5009 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5011 if (V.getNode()) return V;
5014 if (EVTBits == 16 && NumElems == 8) {
5015 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5017 if (V.getNode()) return V;
5020 // If element VT is == 32 bits, turn it into a number of shuffles.
5021 SmallVector<SDValue, 8> V;
5023 if (NumElems == 4 && NumZero > 0) {
5024 for (unsigned i = 0; i < 4; ++i) {
5025 bool isZero = !(NonZeros & (1 << i));
5027 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5029 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5032 for (unsigned i = 0; i < 2; ++i) {
5033 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5036 V[i] = V[i*2]; // Must be a zero vector.
5039 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5042 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5045 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5050 SmallVector<int, 8> MaskVec;
5051 bool Reverse = (NonZeros & 0x3) == 2;
5052 for (unsigned i = 0; i < 2; ++i)
5053 MaskVec.push_back(Reverse ? 1-i : i);
5054 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5055 for (unsigned i = 0; i < 2; ++i)
5056 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5057 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5060 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5061 // Check for a build vector of consecutive loads.
5062 for (unsigned i = 0; i < NumElems; ++i)
5063 V[i] = Op.getOperand(i);
5065 // Check for elements which are consecutive loads.
5066 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5070 // For SSE 4.1, use insertps to put the high elements into the low element.
5071 if (getSubtarget()->hasSSE41()) {
5073 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5074 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5076 Result = DAG.getUNDEF(VT);
5078 for (unsigned i = 1; i < NumElems; ++i) {
5079 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5080 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5081 Op.getOperand(i), DAG.getIntPtrConstant(i));
5086 // Otherwise, expand into a number of unpckl*, start by extending each of
5087 // our (non-undef) elements to the full vector width with the element in the
5088 // bottom slot of the vector (which generates no code for SSE).
5089 for (unsigned i = 0; i < NumElems; ++i) {
5090 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5091 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5093 V[i] = DAG.getUNDEF(VT);
5096 // Next, we iteratively mix elements, e.g. for v4f32:
5097 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5098 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5099 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5100 unsigned EltStride = NumElems >> 1;
5101 while (EltStride != 0) {
5102 for (unsigned i = 0; i < EltStride; ++i) {
5103 // If V[i+EltStride] is undef and this is the first round of mixing,
5104 // then it is safe to just drop this shuffle: V[i] is already in the
5105 // right place, the one element (since it's the first round) being
5106 // inserted as undef can be dropped. This isn't safe for successive
5107 // rounds because they will permute elements within both vectors.
5108 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5109 EltStride == NumElems/2)
5112 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5121 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5122 // them in a MMX register. This is better than doing a stack convert.
5123 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5124 DebugLoc dl = Op.getDebugLoc();
5125 EVT ResVT = Op.getValueType();
5127 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5128 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5130 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5131 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5132 InVec = Op.getOperand(1);
5133 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5134 unsigned NumElts = ResVT.getVectorNumElements();
5135 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5136 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5137 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5139 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5140 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5141 Mask[0] = 0; Mask[1] = 2;
5142 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5144 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5147 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5148 // to create 256-bit vectors from two other 128-bit ones.
5149 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5150 DebugLoc dl = Op.getDebugLoc();
5151 EVT ResVT = Op.getValueType();
5153 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5155 SDValue V1 = Op.getOperand(0);
5156 SDValue V2 = Op.getOperand(1);
5157 unsigned NumElems = ResVT.getVectorNumElements();
5159 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5160 DAG.getConstant(0, MVT::i32), DAG, dl);
5161 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5166 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5167 EVT ResVT = Op.getValueType();
5169 assert(Op.getNumOperands() == 2);
5170 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5171 "Unsupported CONCAT_VECTORS for value type");
5173 // We support concatenate two MMX registers and place them in a MMX register.
5174 // This is better than doing a stack convert.
5175 if (ResVT.is128BitVector())
5176 return LowerMMXCONCAT_VECTORS(Op, DAG);
5178 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5179 // from two other 128-bit ones.
5180 return LowerAVXCONCAT_VECTORS(Op, DAG);
5183 // v8i16 shuffles - Prefer shuffles in the following order:
5184 // 1. [all] pshuflw, pshufhw, optional move
5185 // 2. [ssse3] 1 x pshufb
5186 // 3. [ssse3] 2 x pshufb + 1 x por
5187 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5189 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5190 SelectionDAG &DAG) const {
5191 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5192 SDValue V1 = SVOp->getOperand(0);
5193 SDValue V2 = SVOp->getOperand(1);
5194 DebugLoc dl = SVOp->getDebugLoc();
5195 SmallVector<int, 8> MaskVals;
5197 // Determine if more than 1 of the words in each of the low and high quadwords
5198 // of the result come from the same quadword of one of the two inputs. Undef
5199 // mask values count as coming from any quadword, for better codegen.
5200 SmallVector<unsigned, 4> LoQuad(4);
5201 SmallVector<unsigned, 4> HiQuad(4);
5202 BitVector InputQuads(4);
5203 for (unsigned i = 0; i < 8; ++i) {
5204 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
5205 int EltIdx = SVOp->getMaskElt(i);
5206 MaskVals.push_back(EltIdx);
5215 InputQuads.set(EltIdx / 4);
5218 int BestLoQuad = -1;
5219 unsigned MaxQuad = 1;
5220 for (unsigned i = 0; i < 4; ++i) {
5221 if (LoQuad[i] > MaxQuad) {
5223 MaxQuad = LoQuad[i];
5227 int BestHiQuad = -1;
5229 for (unsigned i = 0; i < 4; ++i) {
5230 if (HiQuad[i] > MaxQuad) {
5232 MaxQuad = HiQuad[i];
5236 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5237 // of the two input vectors, shuffle them into one input vector so only a
5238 // single pshufb instruction is necessary. If There are more than 2 input
5239 // quads, disable the next transformation since it does not help SSSE3.
5240 bool V1Used = InputQuads[0] || InputQuads[1];
5241 bool V2Used = InputQuads[2] || InputQuads[3];
5242 if (Subtarget->hasSSSE3()) {
5243 if (InputQuads.count() == 2 && V1Used && V2Used) {
5244 BestLoQuad = InputQuads.find_first();
5245 BestHiQuad = InputQuads.find_next(BestLoQuad);
5247 if (InputQuads.count() > 2) {
5253 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5254 // the shuffle mask. If a quad is scored as -1, that means that it contains
5255 // words from all 4 input quadwords.
5257 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5258 SmallVector<int, 8> MaskV;
5259 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5260 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5261 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5262 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5263 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5264 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5266 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5267 // source words for the shuffle, to aid later transformations.
5268 bool AllWordsInNewV = true;
5269 bool InOrder[2] = { true, true };
5270 for (unsigned i = 0; i != 8; ++i) {
5271 int idx = MaskVals[i];
5273 InOrder[i/4] = false;
5274 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5276 AllWordsInNewV = false;
5280 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5281 if (AllWordsInNewV) {
5282 for (int i = 0; i != 8; ++i) {
5283 int idx = MaskVals[i];
5286 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5287 if ((idx != i) && idx < 4)
5289 if ((idx != i) && idx > 3)
5298 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5299 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5300 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5301 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5302 unsigned TargetMask = 0;
5303 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5304 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5305 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5306 X86::getShufflePSHUFLWImmediate(NewV.getNode());
5307 V1 = NewV.getOperand(0);
5308 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5312 // If we have SSSE3, and all words of the result are from 1 input vector,
5313 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5314 // is present, fall back to case 4.
5315 if (Subtarget->hasSSSE3()) {
5316 SmallVector<SDValue,16> pshufbMask;
5318 // If we have elements from both input vectors, set the high bit of the
5319 // shuffle mask element to zero out elements that come from V2 in the V1
5320 // mask, and elements that come from V1 in the V2 mask, so that the two
5321 // results can be OR'd together.
5322 bool TwoInputs = V1Used && V2Used;
5323 for (unsigned i = 0; i != 8; ++i) {
5324 int EltIdx = MaskVals[i] * 2;
5325 if (TwoInputs && (EltIdx >= 16)) {
5326 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5327 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5330 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5331 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5333 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5334 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5335 DAG.getNode(ISD::BUILD_VECTOR, dl,
5336 MVT::v16i8, &pshufbMask[0], 16));
5338 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5340 // Calculate the shuffle mask for the second input, shuffle it, and
5341 // OR it with the first shuffled input.
5343 for (unsigned i = 0; i != 8; ++i) {
5344 int EltIdx = MaskVals[i] * 2;
5346 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5347 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5350 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5351 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5353 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5354 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5355 DAG.getNode(ISD::BUILD_VECTOR, dl,
5356 MVT::v16i8, &pshufbMask[0], 16));
5357 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5358 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5361 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5362 // and update MaskVals with new element order.
5363 BitVector InOrder(8);
5364 if (BestLoQuad >= 0) {
5365 SmallVector<int, 8> MaskV;
5366 for (int i = 0; i != 4; ++i) {
5367 int idx = MaskVals[i];
5369 MaskV.push_back(-1);
5371 } else if ((idx / 4) == BestLoQuad) {
5372 MaskV.push_back(idx & 3);
5375 MaskV.push_back(-1);
5378 for (unsigned i = 4; i != 8; ++i)
5380 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5383 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5384 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5386 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5390 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5391 // and update MaskVals with the new element order.
5392 if (BestHiQuad >= 0) {
5393 SmallVector<int, 8> MaskV;
5394 for (unsigned i = 0; i != 4; ++i)
5396 for (unsigned i = 4; i != 8; ++i) {
5397 int idx = MaskVals[i];
5399 MaskV.push_back(-1);
5401 } else if ((idx / 4) == BestHiQuad) {
5402 MaskV.push_back((idx & 3) + 4);
5405 MaskV.push_back(-1);
5408 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5411 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5412 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5414 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5418 // In case BestHi & BestLo were both -1, which means each quadword has a word
5419 // from each of the four input quadwords, calculate the InOrder bitvector now
5420 // before falling through to the insert/extract cleanup.
5421 if (BestLoQuad == -1 && BestHiQuad == -1) {
5423 for (int i = 0; i != 8; ++i)
5424 if (MaskVals[i] < 0 || MaskVals[i] == i)
5428 // The other elements are put in the right place using pextrw and pinsrw.
5429 for (unsigned i = 0; i != 8; ++i) {
5432 int EltIdx = MaskVals[i];
5435 SDValue ExtOp = (EltIdx < 8)
5436 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5437 DAG.getIntPtrConstant(EltIdx))
5438 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5439 DAG.getIntPtrConstant(EltIdx - 8));
5440 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5441 DAG.getIntPtrConstant(i));
5446 // v16i8 shuffles - Prefer shuffles in the following order:
5447 // 1. [ssse3] 1 x pshufb
5448 // 2. [ssse3] 2 x pshufb + 1 x por
5449 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5451 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5453 const X86TargetLowering &TLI) {
5454 SDValue V1 = SVOp->getOperand(0);
5455 SDValue V2 = SVOp->getOperand(1);
5456 DebugLoc dl = SVOp->getDebugLoc();
5457 SmallVector<int, 16> MaskVals;
5458 SVOp->getMask(MaskVals);
5460 // If we have SSSE3, case 1 is generated when all result bytes come from
5461 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5462 // present, fall back to case 3.
5463 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5466 for (unsigned i = 0; i < 16; ++i) {
5467 int EltIdx = MaskVals[i];
5476 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5477 if (TLI.getSubtarget()->hasSSSE3()) {
5478 SmallVector<SDValue,16> pshufbMask;
5480 // If all result elements are from one input vector, then only translate
5481 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5483 // Otherwise, we have elements from both input vectors, and must zero out
5484 // elements that come from V2 in the first mask, and V1 in the second mask
5485 // so that we can OR them together.
5486 bool TwoInputs = !(V1Only || V2Only);
5487 for (unsigned i = 0; i != 16; ++i) {
5488 int EltIdx = MaskVals[i];
5489 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5490 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5493 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5495 // If all the elements are from V2, assign it to V1 and return after
5496 // building the first pshufb.
5499 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5500 DAG.getNode(ISD::BUILD_VECTOR, dl,
5501 MVT::v16i8, &pshufbMask[0], 16));
5505 // Calculate the shuffle mask for the second input, shuffle it, and
5506 // OR it with the first shuffled input.
5508 for (unsigned i = 0; i != 16; ++i) {
5509 int EltIdx = MaskVals[i];
5511 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5514 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5516 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5517 DAG.getNode(ISD::BUILD_VECTOR, dl,
5518 MVT::v16i8, &pshufbMask[0], 16));
5519 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5522 // No SSSE3 - Calculate in place words and then fix all out of place words
5523 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5524 // the 16 different words that comprise the two doublequadword input vectors.
5525 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5526 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5527 SDValue NewV = V2Only ? V2 : V1;
5528 for (int i = 0; i != 8; ++i) {
5529 int Elt0 = MaskVals[i*2];
5530 int Elt1 = MaskVals[i*2+1];
5532 // This word of the result is all undef, skip it.
5533 if (Elt0 < 0 && Elt1 < 0)
5536 // This word of the result is already in the correct place, skip it.
5537 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5539 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5542 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5543 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5546 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5547 // using a single extract together, load it and store it.
5548 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5549 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5550 DAG.getIntPtrConstant(Elt1 / 2));
5551 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5552 DAG.getIntPtrConstant(i));
5556 // If Elt1 is defined, extract it from the appropriate source. If the
5557 // source byte is not also odd, shift the extracted word left 8 bits
5558 // otherwise clear the bottom 8 bits if we need to do an or.
5560 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5561 DAG.getIntPtrConstant(Elt1 / 2));
5562 if ((Elt1 & 1) == 0)
5563 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5565 TLI.getShiftAmountTy(InsElt.getValueType())));
5567 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5568 DAG.getConstant(0xFF00, MVT::i16));
5570 // If Elt0 is defined, extract it from the appropriate source. If the
5571 // source byte is not also even, shift the extracted word right 8 bits. If
5572 // Elt1 was also defined, OR the extracted values together before
5573 // inserting them in the result.
5575 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5576 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5577 if ((Elt0 & 1) != 0)
5578 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5580 TLI.getShiftAmountTy(InsElt0.getValueType())));
5582 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5583 DAG.getConstant(0x00FF, MVT::i16));
5584 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5587 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5588 DAG.getIntPtrConstant(i));
5590 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5593 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5594 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5595 /// done when every pair / quad of shuffle mask elements point to elements in
5596 /// the right sequence. e.g.
5597 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5599 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5600 SelectionDAG &DAG, DebugLoc dl) {
5601 EVT VT = SVOp->getValueType(0);
5602 SDValue V1 = SVOp->getOperand(0);
5603 SDValue V2 = SVOp->getOperand(1);
5604 unsigned NumElems = VT.getVectorNumElements();
5605 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5607 switch (VT.getSimpleVT().SimpleTy) {
5608 default: assert(false && "Unexpected!");
5609 case MVT::v4f32: NewVT = MVT::v2f64; break;
5610 case MVT::v4i32: NewVT = MVT::v2i64; break;
5611 case MVT::v8i16: NewVT = MVT::v4i32; break;
5612 case MVT::v16i8: NewVT = MVT::v4i32; break;
5615 int Scale = NumElems / NewWidth;
5616 SmallVector<int, 8> MaskVec;
5617 for (unsigned i = 0; i < NumElems; i += Scale) {
5619 for (int j = 0; j < Scale; ++j) {
5620 int EltIdx = SVOp->getMaskElt(i+j);
5624 StartIdx = EltIdx - (EltIdx % Scale);
5625 if (EltIdx != StartIdx + j)
5629 MaskVec.push_back(-1);
5631 MaskVec.push_back(StartIdx / Scale);
5634 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5635 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5636 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5639 /// getVZextMovL - Return a zero-extending vector move low node.
5641 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5642 SDValue SrcOp, SelectionDAG &DAG,
5643 const X86Subtarget *Subtarget, DebugLoc dl) {
5644 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5645 LoadSDNode *LD = NULL;
5646 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5647 LD = dyn_cast<LoadSDNode>(SrcOp);
5649 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5651 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5652 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5653 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5654 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5655 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5657 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5658 return DAG.getNode(ISD::BITCAST, dl, VT,
5659 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5660 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5668 return DAG.getNode(ISD::BITCAST, dl, VT,
5669 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5670 DAG.getNode(ISD::BITCAST, dl,
5674 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5675 /// shuffle node referes to only one lane in the sources.
5676 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5677 EVT VT = SVOp->getValueType(0);
5678 int NumElems = VT.getVectorNumElements();
5679 int HalfSize = NumElems/2;
5680 SmallVector<int, 16> M;
5682 bool MatchA = false, MatchB = false;
5684 for (int l = 0; l < NumElems*2; l += HalfSize) {
5685 if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5691 for (int l = 0; l < NumElems*2; l += HalfSize) {
5692 if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5698 return MatchA && MatchB;
5701 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5702 /// which could not be matched by any known target speficic shuffle
5704 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5705 if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5706 // If each half of a vector shuffle node referes to only one lane in the
5707 // source vectors, extract each used 128-bit lane and shuffle them using
5708 // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5709 // the work to the legalizer.
5710 DebugLoc dl = SVOp->getDebugLoc();
5711 EVT VT = SVOp->getValueType(0);
5712 int NumElems = VT.getVectorNumElements();
5713 int HalfSize = NumElems/2;
5715 // Extract the reference for each half
5716 int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5717 int FstVecOpNum = 0, SndVecOpNum = 0;
5718 for (int i = 0; i < HalfSize; ++i) {
5719 int Elt = SVOp->getMaskElt(i);
5720 if (SVOp->getMaskElt(i) < 0)
5722 FstVecOpNum = Elt/NumElems;
5723 FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5726 for (int i = HalfSize; i < NumElems; ++i) {
5727 int Elt = SVOp->getMaskElt(i);
5728 if (SVOp->getMaskElt(i) < 0)
5730 SndVecOpNum = Elt/NumElems;
5731 SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5735 // Extract the subvectors
5736 SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5737 DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5738 SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5739 DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5741 // Generate 128-bit shuffles
5742 SmallVector<int, 16> MaskV1, MaskV2;
5743 for (int i = 0; i < HalfSize; ++i) {
5744 int Elt = SVOp->getMaskElt(i);
5745 MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5747 for (int i = HalfSize; i < NumElems; ++i) {
5748 int Elt = SVOp->getMaskElt(i);
5749 MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5752 EVT NVT = V1.getValueType();
5753 V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5754 V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
5756 // Concatenate the result back
5757 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
5758 DAG.getConstant(0, MVT::i32), DAG, dl);
5759 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5766 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
5767 /// 4 elements, and match them with several different shuffle types.
5769 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5770 SDValue V1 = SVOp->getOperand(0);
5771 SDValue V2 = SVOp->getOperand(1);
5772 DebugLoc dl = SVOp->getDebugLoc();
5773 EVT VT = SVOp->getValueType(0);
5775 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
5777 SmallVector<std::pair<int, int>, 8> Locs;
5779 SmallVector<int, 8> Mask1(4U, -1);
5780 SmallVector<int, 8> PermMask;
5781 SVOp->getMask(PermMask);
5785 for (unsigned i = 0; i != 4; ++i) {
5786 int Idx = PermMask[i];
5788 Locs[i] = std::make_pair(-1, -1);
5790 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5792 Locs[i] = std::make_pair(0, NumLo);
5796 Locs[i] = std::make_pair(1, NumHi);
5798 Mask1[2+NumHi] = Idx;
5804 if (NumLo <= 2 && NumHi <= 2) {
5805 // If no more than two elements come from either vector. This can be
5806 // implemented with two shuffles. First shuffle gather the elements.
5807 // The second shuffle, which takes the first shuffle as both of its
5808 // vector operands, put the elements into the right order.
5809 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5811 SmallVector<int, 8> Mask2(4U, -1);
5813 for (unsigned i = 0; i != 4; ++i) {
5814 if (Locs[i].first == -1)
5817 unsigned Idx = (i < 2) ? 0 : 4;
5818 Idx += Locs[i].first * 2 + Locs[i].second;
5823 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5824 } else if (NumLo == 3 || NumHi == 3) {
5825 // Otherwise, we must have three elements from one vector, call it X, and
5826 // one element from the other, call it Y. First, use a shufps to build an
5827 // intermediate vector with the one element from Y and the element from X
5828 // that will be in the same half in the final destination (the indexes don't
5829 // matter). Then, use a shufps to build the final vector, taking the half
5830 // containing the element from Y from the intermediate, and the other half
5833 // Normalize it so the 3 elements come from V1.
5834 CommuteVectorShuffleMask(PermMask, VT);
5838 // Find the element from V2.
5840 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5841 int Val = PermMask[HiIndex];
5848 Mask1[0] = PermMask[HiIndex];
5850 Mask1[2] = PermMask[HiIndex^1];
5852 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5855 Mask1[0] = PermMask[0];
5856 Mask1[1] = PermMask[1];
5857 Mask1[2] = HiIndex & 1 ? 6 : 4;
5858 Mask1[3] = HiIndex & 1 ? 4 : 6;
5859 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5861 Mask1[0] = HiIndex & 1 ? 2 : 0;
5862 Mask1[1] = HiIndex & 1 ? 0 : 2;
5863 Mask1[2] = PermMask[2];
5864 Mask1[3] = PermMask[3];
5869 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5873 // Break it into (shuffle shuffle_hi, shuffle_lo).
5876 SmallVector<int,8> LoMask(4U, -1);
5877 SmallVector<int,8> HiMask(4U, -1);
5879 SmallVector<int,8> *MaskPtr = &LoMask;
5880 unsigned MaskIdx = 0;
5883 for (unsigned i = 0; i != 4; ++i) {
5890 int Idx = PermMask[i];
5892 Locs[i] = std::make_pair(-1, -1);
5893 } else if (Idx < 4) {
5894 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5895 (*MaskPtr)[LoIdx] = Idx;
5898 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5899 (*MaskPtr)[HiIdx] = Idx;
5904 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5905 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5906 SmallVector<int, 8> MaskOps;
5907 for (unsigned i = 0; i != 4; ++i) {
5908 if (Locs[i].first == -1) {
5909 MaskOps.push_back(-1);
5911 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5912 MaskOps.push_back(Idx);
5915 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5918 static bool MayFoldVectorLoad(SDValue V) {
5919 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5920 V = V.getOperand(0);
5921 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5922 V = V.getOperand(0);
5928 // FIXME: the version above should always be used. Since there's
5929 // a bug where several vector shuffles can't be folded because the
5930 // DAG is not updated during lowering and a node claims to have two
5931 // uses while it only has one, use this version, and let isel match
5932 // another instruction if the load really happens to have more than
5933 // one use. Remove this version after this bug get fixed.
5934 // rdar://8434668, PR8156
5935 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5936 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5937 V = V.getOperand(0);
5938 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5939 V = V.getOperand(0);
5940 if (ISD::isNormalLoad(V.getNode()))
5945 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5946 /// a vector extract, and if both can be later optimized into a single load.
5947 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5948 /// here because otherwise a target specific shuffle node is going to be
5949 /// emitted for this shuffle, and the optimization not done.
5950 /// FIXME: This is probably not the best approach, but fix the problem
5951 /// until the right path is decided.
5953 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5954 const TargetLowering &TLI) {
5955 EVT VT = V.getValueType();
5956 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5958 // Be sure that the vector shuffle is present in a pattern like this:
5959 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5963 SDNode *N = *V.getNode()->use_begin();
5964 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5967 SDValue EltNo = N->getOperand(1);
5968 if (!isa<ConstantSDNode>(EltNo))
5971 // If the bit convert changed the number of elements, it is unsafe
5972 // to examine the mask.
5973 bool HasShuffleIntoBitcast = false;
5974 if (V.getOpcode() == ISD::BITCAST) {
5975 EVT SrcVT = V.getOperand(0).getValueType();
5976 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5978 V = V.getOperand(0);
5979 HasShuffleIntoBitcast = true;
5982 // Select the input vector, guarding against out of range extract vector.
5983 unsigned NumElems = VT.getVectorNumElements();
5984 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5985 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5986 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5988 // Skip one more bit_convert if necessary
5989 if (V.getOpcode() == ISD::BITCAST)
5990 V = V.getOperand(0);
5992 if (ISD::isNormalLoad(V.getNode())) {
5993 // Is the original load suitable?
5994 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5996 // FIXME: avoid the multi-use bug that is preventing lots of
5997 // of foldings to be detected, this is still wrong of course, but
5998 // give the temporary desired behavior, and if it happens that
5999 // the load has real more uses, during isel it will not fold, and
6000 // will generate poor code.
6001 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6004 if (!HasShuffleIntoBitcast)
6007 // If there's a bitcast before the shuffle, check if the load type and
6008 // alignment is valid.
6009 unsigned Align = LN0->getAlignment();
6011 TLI.getTargetData()->getABITypeAlignment(
6012 VT.getTypeForEVT(*DAG.getContext()));
6014 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6022 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6023 EVT VT = Op.getValueType();
6025 // Canonizalize to v2f64.
6026 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6027 return DAG.getNode(ISD::BITCAST, dl, VT,
6028 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6033 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6035 SDValue V1 = Op.getOperand(0);
6036 SDValue V2 = Op.getOperand(1);
6037 EVT VT = Op.getValueType();
6039 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6041 if (HasSSE2 && VT == MVT::v2f64)
6042 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6045 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
6049 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6050 SDValue V1 = Op.getOperand(0);
6051 SDValue V2 = Op.getOperand(1);
6052 EVT VT = Op.getValueType();
6054 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6055 "unsupported shuffle type");
6057 if (V2.getOpcode() == ISD::UNDEF)
6061 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6065 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6066 SDValue V1 = Op.getOperand(0);
6067 SDValue V2 = Op.getOperand(1);
6068 EVT VT = Op.getValueType();
6069 unsigned NumElems = VT.getVectorNumElements();
6071 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6072 // operand of these instructions is only memory, so check if there's a
6073 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6075 bool CanFoldLoad = false;
6077 // Trivial case, when V2 comes from a load.
6078 if (MayFoldVectorLoad(V2))
6081 // When V1 is a load, it can be folded later into a store in isel, example:
6082 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6084 // (MOVLPSmr addr:$src1, VR128:$src2)
6085 // So, recognize this potential and also use MOVLPS or MOVLPD
6086 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6089 // Both of them can't be memory operations though.
6090 if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
6091 CanFoldLoad = false;
6094 if (HasSSE2 && NumElems == 2)
6095 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6098 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6101 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6102 // movl and movlp will both match v2i64, but v2i64 is never matched by
6103 // movl earlier because we make it strict to avoid messing with the movlp load
6104 // folding logic (see the code above getMOVLP call). Match it here then,
6105 // this is horrible, but will stay like this until we move all shuffle
6106 // matching to x86 specific nodes. Note that for the 1st condition all
6107 // types are matched with movsd.
6108 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
6109 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6111 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6114 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6116 // Invert the operand order and use SHUFPS to match it.
6117 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
6118 X86::getShuffleSHUFImmediate(SVOp), DAG);
6121 static inline unsigned getUNPCKLOpcode(EVT VT) {
6122 switch(VT.getSimpleVT().SimpleTy) {
6123 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6124 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6125 case MVT::v4f32: return X86ISD::UNPCKLPS;
6126 case MVT::v2f64: return X86ISD::UNPCKLPD;
6127 case MVT::v8i32: // Use fp unit for int unpack.
6128 case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6129 case MVT::v4i64: // Use fp unit for int unpack.
6130 case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6131 case MVT::v16i8: return X86ISD::PUNPCKLBW;
6132 case MVT::v8i16: return X86ISD::PUNPCKLWD;
6134 llvm_unreachable("Unknown type for unpckl");
6139 static inline unsigned getUNPCKHOpcode(EVT VT) {
6140 switch(VT.getSimpleVT().SimpleTy) {
6141 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6142 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6143 case MVT::v4f32: return X86ISD::UNPCKHPS;
6144 case MVT::v2f64: return X86ISD::UNPCKHPD;
6145 case MVT::v8i32: // Use fp unit for int unpack.
6146 case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6147 case MVT::v4i64: // Use fp unit for int unpack.
6148 case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6149 case MVT::v16i8: return X86ISD::PUNPCKHBW;
6150 case MVT::v8i16: return X86ISD::PUNPCKHWD;
6152 llvm_unreachable("Unknown type for unpckh");
6157 static inline unsigned getVPERMILOpcode(EVT VT) {
6158 switch(VT.getSimpleVT().SimpleTy) {
6160 case MVT::v4f32: return X86ISD::VPERMILPS;
6162 case MVT::v2f64: return X86ISD::VPERMILPD;
6164 case MVT::v8f32: return X86ISD::VPERMILPSY;
6166 case MVT::v4f64: return X86ISD::VPERMILPDY;
6168 llvm_unreachable("Unknown type for vpermil");
6173 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
6174 /// a vbroadcast node. The nodes are suitable whenever we can fold a load coming
6175 /// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
6176 static bool isVectorBroadcast(SDValue &Op) {
6177 EVT VT = Op.getValueType();
6178 bool Is256 = VT.getSizeInBits() == 256;
6180 assert((VT.getSizeInBits() == 128 || Is256) &&
6181 "Unsupported type for vbroadcast node");
6184 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6185 V = V.getOperand(0);
6187 if (Is256 && !(V.hasOneUse() &&
6188 V.getOpcode() == ISD::INSERT_SUBVECTOR &&
6189 V.getOperand(0).getOpcode() == ISD::UNDEF))
6193 V = V.getOperand(1);
6194 if (V.hasOneUse() && V.getOpcode() != ISD::SCALAR_TO_VECTOR)
6197 // Check the source scalar_to_vector type. 256-bit broadcasts are
6198 // supported for 32/64-bit sizes, while 128-bit ones are only supported
6199 // for 32-bit scalars.
6200 unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits();
6201 if (ScalarSize != 32 && ScalarSize != 64)
6203 if (!Is256 && ScalarSize == 64)
6206 V = V.getOperand(0);
6207 if (!MayFoldLoad(V))
6210 // Return the load node
6216 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6217 const TargetLowering &TLI,
6218 const X86Subtarget *Subtarget) {
6219 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6220 EVT VT = Op.getValueType();
6221 DebugLoc dl = Op.getDebugLoc();
6222 SDValue V1 = Op.getOperand(0);
6223 SDValue V2 = Op.getOperand(1);
6225 if (isZeroShuffle(SVOp))
6226 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
6228 // Handle splat operations
6229 if (SVOp->isSplat()) {
6230 unsigned NumElem = VT.getVectorNumElements();
6231 int Size = VT.getSizeInBits();
6232 // Special case, this is the only place now where it's allowed to return
6233 // a vector_shuffle operation without using a target specific node, because
6234 // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6235 // this be moved to DAGCombine instead?
6236 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6239 // Use vbroadcast whenever the splat comes from a foldable load
6240 if (Subtarget->hasAVX() && isVectorBroadcast(V1))
6241 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
6243 // Handle splats by matching through known shuffle masks
6244 if ((Size == 128 && NumElem <= 4) ||
6245 (Size == 256 && NumElem < 8))
6248 // All remaning splats are promoted to target supported vector shuffles.
6249 return PromoteSplat(SVOp, DAG);
6252 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6254 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6255 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6256 if (NewOp.getNode())
6257 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6258 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6259 // FIXME: Figure out a cleaner way to do this.
6260 // Try to make use of movq to zero out the top part.
6261 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6262 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6263 if (NewOp.getNode()) {
6264 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6265 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6266 DAG, Subtarget, dl);
6268 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6269 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6270 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6271 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6272 DAG, Subtarget, dl);
6279 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6280 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6281 SDValue V1 = Op.getOperand(0);
6282 SDValue V2 = Op.getOperand(1);
6283 EVT VT = Op.getValueType();
6284 DebugLoc dl = Op.getDebugLoc();
6285 unsigned NumElems = VT.getVectorNumElements();
6286 bool isMMX = VT.getSizeInBits() == 64;
6287 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6288 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6289 bool V1IsSplat = false;
6290 bool V2IsSplat = false;
6291 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
6292 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
6293 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
6294 MachineFunction &MF = DAG.getMachineFunction();
6295 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6297 // Shuffle operations on MMX not supported.
6301 // Vector shuffle lowering takes 3 steps:
6303 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6304 // narrowing and commutation of operands should be handled.
6305 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6307 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6308 // so the shuffle can be broken into other shuffles and the legalizer can
6309 // try the lowering again.
6311 // The general ideia is that no vector_shuffle operation should be left to
6312 // be matched during isel, all of them must be converted to a target specific
6315 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6316 // narrowing and commutation of operands should be handled. The actual code
6317 // doesn't include all of those, work in progress...
6318 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6319 if (NewOp.getNode())
6322 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6323 // unpckh_undef). Only use pshufd if speed is more important than size.
6324 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6325 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6326 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6327 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6329 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
6330 RelaxedMayFoldVectorLoad(V1))
6331 return getMOVDDup(Op, dl, V1, DAG);
6333 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6334 return getMOVHighToLow(Op, dl, DAG);
6336 // Use to match splats
6337 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6338 (VT == MVT::v2f64 || VT == MVT::v2i64))
6339 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6341 if (X86::isPSHUFDMask(SVOp)) {
6342 // The actual implementation will match the mask in the if above and then
6343 // during isel it can match several different instructions, not only pshufd
6344 // as its name says, sad but true, emulate the behavior for now...
6345 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6346 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6348 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6350 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6351 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6353 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6354 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
6357 if (VT == MVT::v4f32)
6358 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
6362 // Check if this can be converted into a logical shift.
6363 bool isLeft = false;
6366 bool isShift = getSubtarget()->hasSSE2() &&
6367 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6368 if (isShift && ShVal.hasOneUse()) {
6369 // If the shifted value has multiple uses, it may be cheaper to use
6370 // v_set0 + movlhps or movhlps, etc.
6371 EVT EltVT = VT.getVectorElementType();
6372 ShAmt *= EltVT.getSizeInBits();
6373 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6376 if (X86::isMOVLMask(SVOp)) {
6379 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6380 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6381 if (!X86::isMOVLPMask(SVOp)) {
6382 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6383 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6385 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6386 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6390 // FIXME: fold these into legal mask.
6391 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6392 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6394 if (X86::isMOVHLPSMask(SVOp))
6395 return getMOVHighToLow(Op, dl, DAG);
6397 if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6398 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6400 if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6401 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6403 if (X86::isMOVLPMask(SVOp))
6404 return getMOVLP(Op, dl, DAG, HasSSE2);
6406 if (ShouldXformToMOVHLPS(SVOp) ||
6407 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6408 return CommuteVectorShuffle(SVOp, DAG);
6411 // No better options. Use a vshl / vsrl.
6412 EVT EltVT = VT.getVectorElementType();
6413 ShAmt *= EltVT.getSizeInBits();
6414 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6417 bool Commuted = false;
6418 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6419 // 1,1,1,1 -> v8i16 though.
6420 V1IsSplat = isSplatVector(V1.getNode());
6421 V2IsSplat = isSplatVector(V2.getNode());
6423 // Canonicalize the splat or undef, if present, to be on the RHS.
6424 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6425 Op = CommuteVectorShuffle(SVOp, DAG);
6426 SVOp = cast<ShuffleVectorSDNode>(Op);
6427 V1 = SVOp->getOperand(0);
6428 V2 = SVOp->getOperand(1);
6429 std::swap(V1IsSplat, V2IsSplat);
6430 std::swap(V1IsUndef, V2IsUndef);
6434 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6435 // Shuffling low element of v1 into undef, just return v1.
6438 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6439 // the instruction selector will not match, so get a canonical MOVL with
6440 // swapped operands to undo the commute.
6441 return getMOVL(DAG, dl, VT, V2, V1);
6444 if (X86::isUNPCKLMask(SVOp))
6445 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6447 if (X86::isUNPCKHMask(SVOp))
6448 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6451 // Normalize mask so all entries that point to V2 points to its first
6452 // element then try to match unpck{h|l} again. If match, return a
6453 // new vector_shuffle with the corrected mask.
6454 SDValue NewMask = NormalizeMask(SVOp, DAG);
6455 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6456 if (NSVOp != SVOp) {
6457 if (X86::isUNPCKLMask(NSVOp, true)) {
6459 } else if (X86::isUNPCKHMask(NSVOp, true)) {
6466 // Commute is back and try unpck* again.
6467 // FIXME: this seems wrong.
6468 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6469 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6471 if (X86::isUNPCKLMask(NewSVOp))
6472 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6474 if (X86::isUNPCKHMask(NewSVOp))
6475 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6478 // Normalize the node to match x86 shuffle ops if needed
6479 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6480 return CommuteVectorShuffle(SVOp, DAG);
6482 // The checks below are all present in isShuffleMaskLegal, but they are
6483 // inlined here right now to enable us to directly emit target specific
6484 // nodes, and remove one by one until they don't return Op anymore.
6485 SmallVector<int, 16> M;
6488 if (isPALIGNRMask(M, VT, HasSSSE3))
6489 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6490 X86::getShufflePALIGNRImmediate(SVOp),
6493 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6494 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6495 if (VT == MVT::v2f64)
6496 return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6497 if (VT == MVT::v2i64)
6498 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6501 if (isPSHUFHWMask(M, VT))
6502 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6503 X86::getShufflePSHUFHWImmediate(SVOp),
6506 if (isPSHUFLWMask(M, VT))
6507 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6508 X86::getShufflePSHUFLWImmediate(SVOp),
6511 if (isSHUFPMask(M, VT)) {
6512 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6513 if (VT == MVT::v4f32 || VT == MVT::v4i32)
6514 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
6516 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6517 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
6521 if (X86::isUNPCKL_v_undef_Mask(SVOp))
6522 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6523 if (X86::isUNPCKH_v_undef_Mask(SVOp))
6524 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6526 //===--------------------------------------------------------------------===//
6527 // Generate target specific nodes for 128 or 256-bit shuffles only
6528 // supported in the AVX instruction set.
6531 // Handle VPERMILPS* permutations
6532 if (isVPERMILPSMask(M, VT, Subtarget))
6533 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6534 getShuffleVPERMILPSImmediate(SVOp), DAG);
6536 // Handle VPERMILPD* permutations
6537 if (isVPERMILPDMask(M, VT, Subtarget))
6538 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6539 getShuffleVPERMILPDImmediate(SVOp), DAG);
6541 // Handle VPERM2F128 permutations
6542 if (isVPERM2F128Mask(M, VT, Subtarget))
6543 return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6544 getShuffleVPERM2F128Immediate(SVOp), DAG);
6546 //===--------------------------------------------------------------------===//
6547 // Since no target specific shuffle was selected for this generic one,
6548 // lower it into other known shuffles. FIXME: this isn't true yet, but
6549 // this is the plan.
6552 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6553 if (VT == MVT::v8i16) {
6554 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6555 if (NewOp.getNode())
6559 if (VT == MVT::v16i8) {
6560 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6561 if (NewOp.getNode())
6565 // Handle all 128-bit wide vectors with 4 elements, and match them with
6566 // several different shuffle types.
6567 if (NumElems == 4 && VT.getSizeInBits() == 128)
6568 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6570 // Handle general 256-bit shuffles
6571 if (VT.is256BitVector())
6572 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6578 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6579 SelectionDAG &DAG) const {
6580 EVT VT = Op.getValueType();
6581 DebugLoc dl = Op.getDebugLoc();
6583 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6586 if (VT.getSizeInBits() == 8) {
6587 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6588 Op.getOperand(0), Op.getOperand(1));
6589 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6590 DAG.getValueType(VT));
6591 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6592 } else if (VT.getSizeInBits() == 16) {
6593 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6594 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6596 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6597 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6598 DAG.getNode(ISD::BITCAST, dl,
6602 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6603 Op.getOperand(0), Op.getOperand(1));
6604 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6605 DAG.getValueType(VT));
6606 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6607 } else if (VT == MVT::f32) {
6608 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6609 // the result back to FR32 register. It's only worth matching if the
6610 // result has a single use which is a store or a bitcast to i32. And in
6611 // the case of a store, it's not worth it if the index is a constant 0,
6612 // because a MOVSSmr can be used instead, which is smaller and faster.
6613 if (!Op.hasOneUse())
6615 SDNode *User = *Op.getNode()->use_begin();
6616 if ((User->getOpcode() != ISD::STORE ||
6617 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6618 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6619 (User->getOpcode() != ISD::BITCAST ||
6620 User->getValueType(0) != MVT::i32))
6622 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6623 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6626 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6627 } else if (VT == MVT::i32) {
6628 // ExtractPS works with constant index.
6629 if (isa<ConstantSDNode>(Op.getOperand(1)))
6637 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6638 SelectionDAG &DAG) const {
6639 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6642 SDValue Vec = Op.getOperand(0);
6643 EVT VecVT = Vec.getValueType();
6645 // If this is a 256-bit vector result, first extract the 128-bit vector and
6646 // then extract the element from the 128-bit vector.
6647 if (VecVT.getSizeInBits() == 256) {
6648 DebugLoc dl = Op.getNode()->getDebugLoc();
6649 unsigned NumElems = VecVT.getVectorNumElements();
6650 SDValue Idx = Op.getOperand(1);
6651 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6653 // Get the 128-bit vector.
6654 bool Upper = IdxVal >= NumElems/2;
6655 Vec = Extract128BitVector(Vec,
6656 DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6658 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6659 Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6662 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6664 if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
6665 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6670 EVT VT = Op.getValueType();
6671 DebugLoc dl = Op.getDebugLoc();
6672 // TODO: handle v16i8.
6673 if (VT.getSizeInBits() == 16) {
6674 SDValue Vec = Op.getOperand(0);
6675 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6677 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6678 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6679 DAG.getNode(ISD::BITCAST, dl,
6682 // Transform it so it match pextrw which produces a 32-bit result.
6683 EVT EltVT = MVT::i32;
6684 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6685 Op.getOperand(0), Op.getOperand(1));
6686 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6687 DAG.getValueType(VT));
6688 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6689 } else if (VT.getSizeInBits() == 32) {
6690 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6694 // SHUFPS the element to the lowest double word, then movss.
6695 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6696 EVT VVT = Op.getOperand(0).getValueType();
6697 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6698 DAG.getUNDEF(VVT), Mask);
6699 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6700 DAG.getIntPtrConstant(0));
6701 } else if (VT.getSizeInBits() == 64) {
6702 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6703 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6704 // to match extract_elt for f64.
6705 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6709 // UNPCKHPD the element to the lowest double word, then movsd.
6710 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6711 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6712 int Mask[2] = { 1, -1 };
6713 EVT VVT = Op.getOperand(0).getValueType();
6714 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6715 DAG.getUNDEF(VVT), Mask);
6716 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6717 DAG.getIntPtrConstant(0));
6724 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6725 SelectionDAG &DAG) const {
6726 EVT VT = Op.getValueType();
6727 EVT EltVT = VT.getVectorElementType();
6728 DebugLoc dl = Op.getDebugLoc();
6730 SDValue N0 = Op.getOperand(0);
6731 SDValue N1 = Op.getOperand(1);
6732 SDValue N2 = Op.getOperand(2);
6734 if (VT.getSizeInBits() == 256)
6737 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6738 isa<ConstantSDNode>(N2)) {
6740 if (VT == MVT::v8i16)
6741 Opc = X86ISD::PINSRW;
6742 else if (VT == MVT::v16i8)
6743 Opc = X86ISD::PINSRB;
6745 Opc = X86ISD::PINSRB;
6747 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6749 if (N1.getValueType() != MVT::i32)
6750 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6751 if (N2.getValueType() != MVT::i32)
6752 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6753 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6754 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6755 // Bits [7:6] of the constant are the source select. This will always be
6756 // zero here. The DAG Combiner may combine an extract_elt index into these
6757 // bits. For example (insert (extract, 3), 2) could be matched by putting
6758 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6759 // Bits [5:4] of the constant are the destination select. This is the
6760 // value of the incoming immediate.
6761 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6762 // combine either bitwise AND or insert of float 0.0 to set these bits.
6763 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6764 // Create this as a scalar to vector..
6765 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6766 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6767 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6768 // PINSR* works with constant index.
6775 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6776 EVT VT = Op.getValueType();
6777 EVT EltVT = VT.getVectorElementType();
6779 DebugLoc dl = Op.getDebugLoc();
6780 SDValue N0 = Op.getOperand(0);
6781 SDValue N1 = Op.getOperand(1);
6782 SDValue N2 = Op.getOperand(2);
6784 // If this is a 256-bit vector result, first extract the 128-bit vector,
6785 // insert the element into the extracted half and then place it back.
6786 if (VT.getSizeInBits() == 256) {
6787 if (!isa<ConstantSDNode>(N2))
6790 // Get the desired 128-bit vector half.
6791 unsigned NumElems = VT.getVectorNumElements();
6792 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6793 bool Upper = IdxVal >= NumElems/2;
6794 SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
6795 SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
6797 // Insert the element into the desired half.
6798 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
6799 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
6801 // Insert the changed part back to the 256-bit vector
6802 return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
6805 if (Subtarget->hasSSE41() || Subtarget->hasAVX())
6806 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6808 if (EltVT == MVT::i8)
6811 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6812 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6813 // as its second argument.
6814 if (N1.getValueType() != MVT::i32)
6815 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6816 if (N2.getValueType() != MVT::i32)
6817 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6818 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6824 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6825 LLVMContext *Context = DAG.getContext();
6826 DebugLoc dl = Op.getDebugLoc();
6827 EVT OpVT = Op.getValueType();
6829 // If this is a 256-bit vector result, first insert into a 128-bit
6830 // vector and then insert into the 256-bit vector.
6831 if (OpVT.getSizeInBits() > 128) {
6832 // Insert into a 128-bit vector.
6833 EVT VT128 = EVT::getVectorVT(*Context,
6834 OpVT.getVectorElementType(),
6835 OpVT.getVectorNumElements() / 2);
6837 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6839 // Insert the 128-bit vector.
6840 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6841 DAG.getConstant(0, MVT::i32),
6845 if (Op.getValueType() == MVT::v1i64 &&
6846 Op.getOperand(0).getValueType() == MVT::i64)
6847 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6849 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6850 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6851 "Expected an SSE type!");
6852 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6853 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6856 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
6857 // a simple subregister reference or explicit instructions to grab
6858 // upper bits of a vector.
6860 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6861 if (Subtarget->hasAVX()) {
6862 DebugLoc dl = Op.getNode()->getDebugLoc();
6863 SDValue Vec = Op.getNode()->getOperand(0);
6864 SDValue Idx = Op.getNode()->getOperand(1);
6866 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6867 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6868 return Extract128BitVector(Vec, Idx, DAG, dl);
6874 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
6875 // simple superregister reference or explicit instructions to insert
6876 // the upper bits of a vector.
6878 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6879 if (Subtarget->hasAVX()) {
6880 DebugLoc dl = Op.getNode()->getDebugLoc();
6881 SDValue Vec = Op.getNode()->getOperand(0);
6882 SDValue SubVec = Op.getNode()->getOperand(1);
6883 SDValue Idx = Op.getNode()->getOperand(2);
6885 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6886 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6887 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6893 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6894 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6895 // one of the above mentioned nodes. It has to be wrapped because otherwise
6896 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6897 // be used to form addressing mode. These wrapped nodes will be selected
6900 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6901 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6903 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6905 unsigned char OpFlag = 0;
6906 unsigned WrapperKind = X86ISD::Wrapper;
6907 CodeModel::Model M = getTargetMachine().getCodeModel();
6909 if (Subtarget->isPICStyleRIPRel() &&
6910 (M == CodeModel::Small || M == CodeModel::Kernel))
6911 WrapperKind = X86ISD::WrapperRIP;
6912 else if (Subtarget->isPICStyleGOT())
6913 OpFlag = X86II::MO_GOTOFF;
6914 else if (Subtarget->isPICStyleStubPIC())
6915 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6917 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6919 CP->getOffset(), OpFlag);
6920 DebugLoc DL = CP->getDebugLoc();
6921 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6922 // With PIC, the address is actually $g + Offset.
6924 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6925 DAG.getNode(X86ISD::GlobalBaseReg,
6926 DebugLoc(), getPointerTy()),
6933 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6934 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6936 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6938 unsigned char OpFlag = 0;
6939 unsigned WrapperKind = X86ISD::Wrapper;
6940 CodeModel::Model M = getTargetMachine().getCodeModel();
6942 if (Subtarget->isPICStyleRIPRel() &&
6943 (M == CodeModel::Small || M == CodeModel::Kernel))
6944 WrapperKind = X86ISD::WrapperRIP;
6945 else if (Subtarget->isPICStyleGOT())
6946 OpFlag = X86II::MO_GOTOFF;
6947 else if (Subtarget->isPICStyleStubPIC())
6948 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6950 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6952 DebugLoc DL = JT->getDebugLoc();
6953 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6955 // With PIC, the address is actually $g + Offset.
6957 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6958 DAG.getNode(X86ISD::GlobalBaseReg,
6959 DebugLoc(), getPointerTy()),
6966 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6967 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6969 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6971 unsigned char OpFlag = 0;
6972 unsigned WrapperKind = X86ISD::Wrapper;
6973 CodeModel::Model M = getTargetMachine().getCodeModel();
6975 if (Subtarget->isPICStyleRIPRel() &&
6976 (M == CodeModel::Small || M == CodeModel::Kernel)) {
6977 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
6978 OpFlag = X86II::MO_GOTPCREL;
6979 WrapperKind = X86ISD::WrapperRIP;
6980 } else if (Subtarget->isPICStyleGOT()) {
6981 OpFlag = X86II::MO_GOT;
6982 } else if (Subtarget->isPICStyleStubPIC()) {
6983 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
6984 } else if (Subtarget->isPICStyleStubNoDynamic()) {
6985 OpFlag = X86II::MO_DARWIN_NONLAZY;
6988 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6990 DebugLoc DL = Op.getDebugLoc();
6991 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6994 // With PIC, the address is actually $g + Offset.
6995 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6996 !Subtarget->is64Bit()) {
6997 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6998 DAG.getNode(X86ISD::GlobalBaseReg,
6999 DebugLoc(), getPointerTy()),
7003 // For symbols that require a load from a stub to get the address, emit the
7005 if (isGlobalStubReference(OpFlag))
7006 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7007 MachinePointerInfo::getGOT(), false, false, 0);
7013 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7014 // Create the TargetBlockAddressAddress node.
7015 unsigned char OpFlags =
7016 Subtarget->ClassifyBlockAddressReference();
7017 CodeModel::Model M = getTargetMachine().getCodeModel();
7018 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7019 DebugLoc dl = Op.getDebugLoc();
7020 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7021 /*isTarget=*/true, OpFlags);
7023 if (Subtarget->isPICStyleRIPRel() &&
7024 (M == CodeModel::Small || M == CodeModel::Kernel))
7025 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7027 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7029 // With PIC, the address is actually $g + Offset.
7030 if (isGlobalRelativeToPICBase(OpFlags)) {
7031 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7032 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7040 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7042 SelectionDAG &DAG) const {
7043 // Create the TargetGlobalAddress node, folding in the constant
7044 // offset if it is legal.
7045 unsigned char OpFlags =
7046 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7047 CodeModel::Model M = getTargetMachine().getCodeModel();
7049 if (OpFlags == X86II::MO_NO_FLAG &&
7050 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7051 // A direct static reference to a global.
7052 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7055 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7058 if (Subtarget->isPICStyleRIPRel() &&
7059 (M == CodeModel::Small || M == CodeModel::Kernel))
7060 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7062 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7064 // With PIC, the address is actually $g + Offset.
7065 if (isGlobalRelativeToPICBase(OpFlags)) {
7066 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7067 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7071 // For globals that require a load from a stub to get the address, emit the
7073 if (isGlobalStubReference(OpFlags))
7074 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7075 MachinePointerInfo::getGOT(), false, false, 0);
7077 // If there was a non-zero offset that we didn't fold, create an explicit
7080 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7081 DAG.getConstant(Offset, getPointerTy()));
7087 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7088 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7089 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7090 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7094 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7095 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7096 unsigned char OperandFlags) {
7097 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7098 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7099 DebugLoc dl = GA->getDebugLoc();
7100 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7101 GA->getValueType(0),
7105 SDValue Ops[] = { Chain, TGA, *InFlag };
7106 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7108 SDValue Ops[] = { Chain, TGA };
7109 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7112 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7113 MFI->setAdjustsStack(true);
7115 SDValue Flag = Chain.getValue(1);
7116 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7119 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7121 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7124 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7125 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7126 DAG.getNode(X86ISD::GlobalBaseReg,
7127 DebugLoc(), PtrVT), InFlag);
7128 InFlag = Chain.getValue(1);
7130 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7133 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7135 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7137 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7138 X86::RAX, X86II::MO_TLSGD);
7141 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7142 // "local exec" model.
7143 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7144 const EVT PtrVT, TLSModel::Model model,
7146 DebugLoc dl = GA->getDebugLoc();
7148 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7149 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7150 is64Bit ? 257 : 256));
7152 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7153 DAG.getIntPtrConstant(0),
7154 MachinePointerInfo(Ptr), false, false, 0);
7156 unsigned char OperandFlags = 0;
7157 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7159 unsigned WrapperKind = X86ISD::Wrapper;
7160 if (model == TLSModel::LocalExec) {
7161 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7162 } else if (is64Bit) {
7163 assert(model == TLSModel::InitialExec);
7164 OperandFlags = X86II::MO_GOTTPOFF;
7165 WrapperKind = X86ISD::WrapperRIP;
7167 assert(model == TLSModel::InitialExec);
7168 OperandFlags = X86II::MO_INDNTPOFF;
7171 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7173 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7174 GA->getValueType(0),
7175 GA->getOffset(), OperandFlags);
7176 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7178 if (model == TLSModel::InitialExec)
7179 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7180 MachinePointerInfo::getGOT(), false, false, 0);
7182 // The address of the thread local variable is the add of the thread
7183 // pointer with the offset of the variable.
7184 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7188 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7190 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7191 const GlobalValue *GV = GA->getGlobal();
7193 if (Subtarget->isTargetELF()) {
7194 // TODO: implement the "local dynamic" model
7195 // TODO: implement the "initial exec"model for pic executables
7197 // If GV is an alias then use the aliasee for determining
7198 // thread-localness.
7199 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7200 GV = GA->resolveAliasedGlobal(false);
7202 TLSModel::Model model
7203 = getTLSModel(GV, getTargetMachine().getRelocationModel());
7206 case TLSModel::GeneralDynamic:
7207 case TLSModel::LocalDynamic: // not implemented
7208 if (Subtarget->is64Bit())
7209 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7210 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7212 case TLSModel::InitialExec:
7213 case TLSModel::LocalExec:
7214 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7215 Subtarget->is64Bit());
7217 } else if (Subtarget->isTargetDarwin()) {
7218 // Darwin only has one model of TLS. Lower to that.
7219 unsigned char OpFlag = 0;
7220 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7221 X86ISD::WrapperRIP : X86ISD::Wrapper;
7223 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7225 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7226 !Subtarget->is64Bit();
7228 OpFlag = X86II::MO_TLVP_PIC_BASE;
7230 OpFlag = X86II::MO_TLVP;
7231 DebugLoc DL = Op.getDebugLoc();
7232 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7233 GA->getValueType(0),
7234 GA->getOffset(), OpFlag);
7235 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7237 // With PIC32, the address is actually $g + Offset.
7239 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7240 DAG.getNode(X86ISD::GlobalBaseReg,
7241 DebugLoc(), getPointerTy()),
7244 // Lowering the machine isd will make sure everything is in the right
7246 SDValue Chain = DAG.getEntryNode();
7247 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7248 SDValue Args[] = { Chain, Offset };
7249 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7251 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7252 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7253 MFI->setAdjustsStack(true);
7255 // And our return value (tls address) is in the standard call return value
7257 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7258 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
7262 "TLS not implemented for this target.");
7264 llvm_unreachable("Unreachable");
7269 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7270 /// take a 2 x i32 value to shift plus a shift amount.
7271 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7272 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7273 EVT VT = Op.getValueType();
7274 unsigned VTBits = VT.getSizeInBits();
7275 DebugLoc dl = Op.getDebugLoc();
7276 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7277 SDValue ShOpLo = Op.getOperand(0);
7278 SDValue ShOpHi = Op.getOperand(1);
7279 SDValue ShAmt = Op.getOperand(2);
7280 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7281 DAG.getConstant(VTBits - 1, MVT::i8))
7282 : DAG.getConstant(0, VT);
7285 if (Op.getOpcode() == ISD::SHL_PARTS) {
7286 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7287 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7289 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7290 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7293 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7294 DAG.getConstant(VTBits, MVT::i8));
7295 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7296 AndNode, DAG.getConstant(0, MVT::i8));
7299 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7300 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7301 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7303 if (Op.getOpcode() == ISD::SHL_PARTS) {
7304 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7305 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7307 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7308 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7311 SDValue Ops[2] = { Lo, Hi };
7312 return DAG.getMergeValues(Ops, 2, dl);
7315 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7316 SelectionDAG &DAG) const {
7317 EVT SrcVT = Op.getOperand(0).getValueType();
7319 if (SrcVT.isVector())
7322 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7323 "Unknown SINT_TO_FP to lower!");
7325 // These are really Legal; return the operand so the caller accepts it as
7327 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7329 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7330 Subtarget->is64Bit()) {
7334 DebugLoc dl = Op.getDebugLoc();
7335 unsigned Size = SrcVT.getSizeInBits()/8;
7336 MachineFunction &MF = DAG.getMachineFunction();
7337 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7338 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7339 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7341 MachinePointerInfo::getFixedStack(SSFI),
7343 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7346 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7348 SelectionDAG &DAG) const {
7350 DebugLoc DL = Op.getDebugLoc();
7352 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7354 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7356 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7358 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7360 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7361 MachineMemOperand *MMO;
7363 int SSFI = FI->getIndex();
7365 DAG.getMachineFunction()
7366 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7367 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7369 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7370 StackSlot = StackSlot.getOperand(1);
7372 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7373 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7375 Tys, Ops, array_lengthof(Ops),
7379 Chain = Result.getValue(1);
7380 SDValue InFlag = Result.getValue(2);
7382 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7383 // shouldn't be necessary except that RFP cannot be live across
7384 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7385 MachineFunction &MF = DAG.getMachineFunction();
7386 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7387 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7388 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7389 Tys = DAG.getVTList(MVT::Other);
7391 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7393 MachineMemOperand *MMO =
7394 DAG.getMachineFunction()
7395 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7396 MachineMemOperand::MOStore, SSFISize, SSFISize);
7398 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7399 Ops, array_lengthof(Ops),
7400 Op.getValueType(), MMO);
7401 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7402 MachinePointerInfo::getFixedStack(SSFI),
7409 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7410 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7411 SelectionDAG &DAG) const {
7412 // This algorithm is not obvious. Here it is in C code, more or less:
7414 double uint64_to_double( uint32_t hi, uint32_t lo ) {
7415 static const __m128i exp = { 0x4330000045300000ULL, 0 };
7416 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7418 // Copy ints to xmm registers.
7419 __m128i xh = _mm_cvtsi32_si128( hi );
7420 __m128i xl = _mm_cvtsi32_si128( lo );
7422 // Combine into low half of a single xmm register.
7423 __m128i x = _mm_unpacklo_epi32( xh, xl );
7427 // Merge in appropriate exponents to give the integer bits the right
7429 x = _mm_unpacklo_epi32( x, exp );
7431 // Subtract away the biases to deal with the IEEE-754 double precision
7433 d = _mm_sub_pd( (__m128d) x, bias );
7435 // All conversions up to here are exact. The correctly rounded result is
7436 // calculated using the current rounding mode using the following
7438 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7439 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
7440 // store doesn't really need to be here (except
7441 // maybe to zero the other double)
7446 DebugLoc dl = Op.getDebugLoc();
7447 LLVMContext *Context = DAG.getContext();
7449 // Build some magic constants.
7450 std::vector<Constant*> CV0;
7451 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7452 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7453 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7454 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7455 Constant *C0 = ConstantVector::get(CV0);
7456 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7458 std::vector<Constant*> CV1;
7460 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7462 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7463 Constant *C1 = ConstantVector::get(CV1);
7464 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7466 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7467 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7469 DAG.getIntPtrConstant(1)));
7470 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7471 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7473 DAG.getIntPtrConstant(0)));
7474 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7475 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7476 MachinePointerInfo::getConstantPool(),
7478 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7479 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7480 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7481 MachinePointerInfo::getConstantPool(),
7483 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7485 // Add the halves; easiest way is to swap them into another reg first.
7486 int ShufMask[2] = { 1, -1 };
7487 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7488 DAG.getUNDEF(MVT::v2f64), ShufMask);
7489 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7490 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7491 DAG.getIntPtrConstant(0));
7494 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7495 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7496 SelectionDAG &DAG) const {
7497 DebugLoc dl = Op.getDebugLoc();
7498 // FP constant to bias correct the final result.
7499 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7502 // Load the 32-bit value into an XMM register.
7503 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7506 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7507 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7508 DAG.getIntPtrConstant(0));
7510 // Or the load with the bias.
7511 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7512 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7513 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7515 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7516 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7517 MVT::v2f64, Bias)));
7518 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7519 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7520 DAG.getIntPtrConstant(0));
7522 // Subtract the bias.
7523 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7525 // Handle final rounding.
7526 EVT DestVT = Op.getValueType();
7528 if (DestVT.bitsLT(MVT::f64)) {
7529 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7530 DAG.getIntPtrConstant(0));
7531 } else if (DestVT.bitsGT(MVT::f64)) {
7532 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7535 // Handle final rounding.
7539 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7540 SelectionDAG &DAG) const {
7541 SDValue N0 = Op.getOperand(0);
7542 DebugLoc dl = Op.getDebugLoc();
7544 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7545 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7546 // the optimization here.
7547 if (DAG.SignBitIsZero(N0))
7548 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7550 EVT SrcVT = N0.getValueType();
7551 EVT DstVT = Op.getValueType();
7552 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7553 return LowerUINT_TO_FP_i64(Op, DAG);
7554 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7555 return LowerUINT_TO_FP_i32(Op, DAG);
7557 // Make a 64-bit buffer, and use it to build an FILD.
7558 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7559 if (SrcVT == MVT::i32) {
7560 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7561 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7562 getPointerTy(), StackSlot, WordOff);
7563 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7564 StackSlot, MachinePointerInfo(),
7566 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7567 OffsetSlot, MachinePointerInfo(),
7569 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7573 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7574 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7575 StackSlot, MachinePointerInfo(),
7577 // For i64 source, we need to add the appropriate power of 2 if the input
7578 // was negative. This is the same as the optimization in
7579 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7580 // we must be careful to do the computation in x87 extended precision, not
7581 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7582 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7583 MachineMemOperand *MMO =
7584 DAG.getMachineFunction()
7585 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7586 MachineMemOperand::MOLoad, 8, 8);
7588 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7589 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7590 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7593 APInt FF(32, 0x5F800000ULL);
7595 // Check whether the sign bit is set.
7596 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7597 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7600 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7601 SDValue FudgePtr = DAG.getConstantPool(
7602 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7605 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7606 SDValue Zero = DAG.getIntPtrConstant(0);
7607 SDValue Four = DAG.getIntPtrConstant(4);
7608 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7610 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7612 // Load the value out, extending it from f32 to f80.
7613 // FIXME: Avoid the extend by constructing the right constant pool?
7614 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7615 FudgePtr, MachinePointerInfo::getConstantPool(),
7616 MVT::f32, false, false, 4);
7617 // Extend everything to 80 bits to force it to be done on x87.
7618 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7619 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7622 std::pair<SDValue,SDValue> X86TargetLowering::
7623 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7624 DebugLoc DL = Op.getDebugLoc();
7626 EVT DstTy = Op.getValueType();
7629 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7633 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7634 DstTy.getSimpleVT() >= MVT::i16 &&
7635 "Unknown FP_TO_SINT to lower!");
7637 // These are really Legal.
7638 if (DstTy == MVT::i32 &&
7639 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7640 return std::make_pair(SDValue(), SDValue());
7641 if (Subtarget->is64Bit() &&
7642 DstTy == MVT::i64 &&
7643 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7644 return std::make_pair(SDValue(), SDValue());
7646 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7648 MachineFunction &MF = DAG.getMachineFunction();
7649 unsigned MemSize = DstTy.getSizeInBits()/8;
7650 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7651 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7656 switch (DstTy.getSimpleVT().SimpleTy) {
7657 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7658 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7659 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7660 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7663 SDValue Chain = DAG.getEntryNode();
7664 SDValue Value = Op.getOperand(0);
7665 EVT TheVT = Op.getOperand(0).getValueType();
7666 if (isScalarFPTypeInSSEReg(TheVT)) {
7667 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7668 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7669 MachinePointerInfo::getFixedStack(SSFI),
7671 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7673 Chain, StackSlot, DAG.getValueType(TheVT)
7676 MachineMemOperand *MMO =
7677 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7678 MachineMemOperand::MOLoad, MemSize, MemSize);
7679 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7681 Chain = Value.getValue(1);
7682 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7683 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7686 MachineMemOperand *MMO =
7687 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7688 MachineMemOperand::MOStore, MemSize, MemSize);
7690 // Build the FP_TO_INT*_IN_MEM
7691 SDValue Ops[] = { Chain, Value, StackSlot };
7692 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7693 Ops, 3, DstTy, MMO);
7695 return std::make_pair(FIST, StackSlot);
7698 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7699 SelectionDAG &DAG) const {
7700 if (Op.getValueType().isVector())
7703 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7704 SDValue FIST = Vals.first, StackSlot = Vals.second;
7705 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7706 if (FIST.getNode() == 0) return Op;
7709 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7710 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7713 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7714 SelectionDAG &DAG) const {
7715 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7716 SDValue FIST = Vals.first, StackSlot = Vals.second;
7717 assert(FIST.getNode() && "Unexpected failure");
7720 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7721 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7724 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7725 SelectionDAG &DAG) const {
7726 LLVMContext *Context = DAG.getContext();
7727 DebugLoc dl = Op.getDebugLoc();
7728 EVT VT = Op.getValueType();
7731 EltVT = VT.getVectorElementType();
7732 std::vector<Constant*> CV;
7733 if (EltVT == MVT::f64) {
7734 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7738 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7744 Constant *C = ConstantVector::get(CV);
7745 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7746 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7747 MachinePointerInfo::getConstantPool(),
7749 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7752 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7753 LLVMContext *Context = DAG.getContext();
7754 DebugLoc dl = Op.getDebugLoc();
7755 EVT VT = Op.getValueType();
7758 EltVT = VT.getVectorElementType();
7759 std::vector<Constant*> CV;
7760 if (EltVT == MVT::f64) {
7761 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7765 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7771 Constant *C = ConstantVector::get(CV);
7772 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7773 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7774 MachinePointerInfo::getConstantPool(),
7776 if (VT.isVector()) {
7777 return DAG.getNode(ISD::BITCAST, dl, VT,
7778 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7779 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7781 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7783 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7787 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7788 LLVMContext *Context = DAG.getContext();
7789 SDValue Op0 = Op.getOperand(0);
7790 SDValue Op1 = Op.getOperand(1);
7791 DebugLoc dl = Op.getDebugLoc();
7792 EVT VT = Op.getValueType();
7793 EVT SrcVT = Op1.getValueType();
7795 // If second operand is smaller, extend it first.
7796 if (SrcVT.bitsLT(VT)) {
7797 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7800 // And if it is bigger, shrink it first.
7801 if (SrcVT.bitsGT(VT)) {
7802 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7806 // At this point the operands and the result should have the same
7807 // type, and that won't be f80 since that is not custom lowered.
7809 // First get the sign bit of second operand.
7810 std::vector<Constant*> CV;
7811 if (SrcVT == MVT::f64) {
7812 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7813 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7815 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7816 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7817 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7818 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7820 Constant *C = ConstantVector::get(CV);
7821 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7822 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7823 MachinePointerInfo::getConstantPool(),
7825 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7827 // Shift sign bit right or left if the two operands have different types.
7828 if (SrcVT.bitsGT(VT)) {
7829 // Op0 is MVT::f32, Op1 is MVT::f64.
7830 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7831 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7832 DAG.getConstant(32, MVT::i32));
7833 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7834 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7835 DAG.getIntPtrConstant(0));
7838 // Clear first operand sign bit.
7840 if (VT == MVT::f64) {
7841 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7842 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7844 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7845 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7846 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7847 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7849 C = ConstantVector::get(CV);
7850 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7851 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7852 MachinePointerInfo::getConstantPool(),
7854 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7856 // Or the value with the sign bit.
7857 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7860 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7861 SDValue N0 = Op.getOperand(0);
7862 DebugLoc dl = Op.getDebugLoc();
7863 EVT VT = Op.getValueType();
7865 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7866 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7867 DAG.getConstant(1, VT));
7868 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7871 /// Emit nodes that will be selected as "test Op0,Op0", or something
7873 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7874 SelectionDAG &DAG) const {
7875 DebugLoc dl = Op.getDebugLoc();
7877 // CF and OF aren't always set the way we want. Determine which
7878 // of these we need.
7879 bool NeedCF = false;
7880 bool NeedOF = false;
7883 case X86::COND_A: case X86::COND_AE:
7884 case X86::COND_B: case X86::COND_BE:
7887 case X86::COND_G: case X86::COND_GE:
7888 case X86::COND_L: case X86::COND_LE:
7889 case X86::COND_O: case X86::COND_NO:
7894 // See if we can use the EFLAGS value from the operand instead of
7895 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7896 // we prove that the arithmetic won't overflow, we can't use OF or CF.
7897 if (Op.getResNo() != 0 || NeedOF || NeedCF)
7898 // Emit a CMP with 0, which is the TEST pattern.
7899 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7900 DAG.getConstant(0, Op.getValueType()));
7902 unsigned Opcode = 0;
7903 unsigned NumOperands = 0;
7904 switch (Op.getNode()->getOpcode()) {
7906 // Due to an isel shortcoming, be conservative if this add is likely to be
7907 // selected as part of a load-modify-store instruction. When the root node
7908 // in a match is a store, isel doesn't know how to remap non-chain non-flag
7909 // uses of other nodes in the match, such as the ADD in this case. This
7910 // leads to the ADD being left around and reselected, with the result being
7911 // two adds in the output. Alas, even if none our users are stores, that
7912 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
7913 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
7914 // climbing the DAG back to the root, and it doesn't seem to be worth the
7916 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7917 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7918 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7921 if (ConstantSDNode *C =
7922 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7923 // An add of one will be selected as an INC.
7924 if (C->getAPIntValue() == 1) {
7925 Opcode = X86ISD::INC;
7930 // An add of negative one (subtract of one) will be selected as a DEC.
7931 if (C->getAPIntValue().isAllOnesValue()) {
7932 Opcode = X86ISD::DEC;
7938 // Otherwise use a regular EFLAGS-setting add.
7939 Opcode = X86ISD::ADD;
7943 // If the primary and result isn't used, don't bother using X86ISD::AND,
7944 // because a TEST instruction will be better.
7945 bool NonFlagUse = false;
7946 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7947 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7949 unsigned UOpNo = UI.getOperandNo();
7950 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7951 // Look pass truncate.
7952 UOpNo = User->use_begin().getOperandNo();
7953 User = *User->use_begin();
7956 if (User->getOpcode() != ISD::BRCOND &&
7957 User->getOpcode() != ISD::SETCC &&
7958 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7971 // Due to the ISEL shortcoming noted above, be conservative if this op is
7972 // likely to be selected as part of a load-modify-store instruction.
7973 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7974 UE = Op.getNode()->use_end(); UI != UE; ++UI)
7975 if (UI->getOpcode() == ISD::STORE)
7978 // Otherwise use a regular EFLAGS-setting instruction.
7979 switch (Op.getNode()->getOpcode()) {
7980 default: llvm_unreachable("unexpected operator!");
7981 case ISD::SUB: Opcode = X86ISD::SUB; break;
7982 case ISD::OR: Opcode = X86ISD::OR; break;
7983 case ISD::XOR: Opcode = X86ISD::XOR; break;
7984 case ISD::AND: Opcode = X86ISD::AND; break;
7996 return SDValue(Op.getNode(), 1);
8003 // Emit a CMP with 0, which is the TEST pattern.
8004 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8005 DAG.getConstant(0, Op.getValueType()));
8007 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8008 SmallVector<SDValue, 4> Ops;
8009 for (unsigned i = 0; i != NumOperands; ++i)
8010 Ops.push_back(Op.getOperand(i));
8012 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8013 DAG.ReplaceAllUsesWith(Op, New);
8014 return SDValue(New.getNode(), 1);
8017 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8019 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8020 SelectionDAG &DAG) const {
8021 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8022 if (C->getAPIntValue() == 0)
8023 return EmitTest(Op0, X86CC, DAG);
8025 DebugLoc dl = Op0.getDebugLoc();
8026 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8029 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8030 /// if it's possible.
8031 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8032 DebugLoc dl, SelectionDAG &DAG) const {
8033 SDValue Op0 = And.getOperand(0);
8034 SDValue Op1 = And.getOperand(1);
8035 if (Op0.getOpcode() == ISD::TRUNCATE)
8036 Op0 = Op0.getOperand(0);
8037 if (Op1.getOpcode() == ISD::TRUNCATE)
8038 Op1 = Op1.getOperand(0);
8041 if (Op1.getOpcode() == ISD::SHL)
8042 std::swap(Op0, Op1);
8043 if (Op0.getOpcode() == ISD::SHL) {
8044 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8045 if (And00C->getZExtValue() == 1) {
8046 // If we looked past a truncate, check that it's only truncating away
8048 unsigned BitWidth = Op0.getValueSizeInBits();
8049 unsigned AndBitWidth = And.getValueSizeInBits();
8050 if (BitWidth > AndBitWidth) {
8051 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8052 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8053 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8057 RHS = Op0.getOperand(1);
8059 } else if (Op1.getOpcode() == ISD::Constant) {
8060 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8061 SDValue AndLHS = Op0;
8062 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8063 LHS = AndLHS.getOperand(0);
8064 RHS = AndLHS.getOperand(1);
8068 if (LHS.getNode()) {
8069 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8070 // instruction. Since the shift amount is in-range-or-undefined, we know
8071 // that doing a bittest on the i32 value is ok. We extend to i32 because
8072 // the encoding for the i16 version is larger than the i32 version.
8073 // Also promote i16 to i32 for performance / code size reason.
8074 if (LHS.getValueType() == MVT::i8 ||
8075 LHS.getValueType() == MVT::i16)
8076 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8078 // If the operand types disagree, extend the shift amount to match. Since
8079 // BT ignores high bits (like shifts) we can use anyextend.
8080 if (LHS.getValueType() != RHS.getValueType())
8081 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8083 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8084 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8085 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8086 DAG.getConstant(Cond, MVT::i8), BT);
8092 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8093 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8094 SDValue Op0 = Op.getOperand(0);
8095 SDValue Op1 = Op.getOperand(1);
8096 DebugLoc dl = Op.getDebugLoc();
8097 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8099 // Optimize to BT if possible.
8100 // Lower (X & (1 << N)) == 0 to BT(X, N).
8101 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8102 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8103 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8104 Op1.getOpcode() == ISD::Constant &&
8105 cast<ConstantSDNode>(Op1)->isNullValue() &&
8106 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8107 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8108 if (NewSetCC.getNode())
8112 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8114 if (Op1.getOpcode() == ISD::Constant &&
8115 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8116 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8117 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8119 // If the input is a setcc, then reuse the input setcc or use a new one with
8120 // the inverted condition.
8121 if (Op0.getOpcode() == X86ISD::SETCC) {
8122 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8123 bool Invert = (CC == ISD::SETNE) ^
8124 cast<ConstantSDNode>(Op1)->isNullValue();
8125 if (!Invert) return Op0;
8127 CCode = X86::GetOppositeBranchCondition(CCode);
8128 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8129 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8133 bool isFP = Op1.getValueType().isFloatingPoint();
8134 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8135 if (X86CC == X86::COND_INVALID)
8138 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8139 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8140 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8143 // Lower256IntVETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8144 // ones, and then concatenate the result back.
8145 static SDValue Lower256IntVETCC(SDValue Op, SelectionDAG &DAG) {
8146 EVT VT = Op.getValueType();
8148 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::VSETCC &&
8149 "Unsupported value type for operation");
8151 int NumElems = VT.getVectorNumElements();
8152 DebugLoc dl = Op.getDebugLoc();
8153 SDValue CC = Op.getOperand(2);
8154 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8155 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8157 // Extract the LHS vectors
8158 SDValue LHS = Op.getOperand(0);
8159 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8160 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8162 // Extract the RHS vectors
8163 SDValue RHS = Op.getOperand(1);
8164 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8165 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8167 // Issue the operation on the smaller types and concatenate the result back
8168 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8169 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8170 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8171 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8172 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8176 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8178 SDValue Op0 = Op.getOperand(0);
8179 SDValue Op1 = Op.getOperand(1);
8180 SDValue CC = Op.getOperand(2);
8181 EVT VT = Op.getValueType();
8182 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8183 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8184 DebugLoc dl = Op.getDebugLoc();
8188 EVT EltVT = Op0.getValueType().getVectorElementType();
8189 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8191 unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8194 switch (SetCCOpcode) {
8197 case ISD::SETEQ: SSECC = 0; break;
8199 case ISD::SETGT: Swap = true; // Fallthrough
8201 case ISD::SETOLT: SSECC = 1; break;
8203 case ISD::SETGE: Swap = true; // Fallthrough
8205 case ISD::SETOLE: SSECC = 2; break;
8206 case ISD::SETUO: SSECC = 3; break;
8208 case ISD::SETNE: SSECC = 4; break;
8209 case ISD::SETULE: Swap = true;
8210 case ISD::SETUGE: SSECC = 5; break;
8211 case ISD::SETULT: Swap = true;
8212 case ISD::SETUGT: SSECC = 6; break;
8213 case ISD::SETO: SSECC = 7; break;
8216 std::swap(Op0, Op1);
8218 // In the two special cases we can't handle, emit two comparisons.
8220 if (SetCCOpcode == ISD::SETUEQ) {
8222 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8223 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8224 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8226 else if (SetCCOpcode == ISD::SETONE) {
8228 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8229 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8230 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8232 llvm_unreachable("Illegal FP comparison");
8234 // Handle all other FP comparisons here.
8235 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8238 // Break 256-bit integer vector compare into smaller ones.
8239 if (!isFP && VT.getSizeInBits() == 256)
8240 return Lower256IntVETCC(Op, DAG);
8242 // We are handling one of the integer comparisons here. Since SSE only has
8243 // GT and EQ comparisons for integer, swapping operands and multiple
8244 // operations may be required for some comparisons.
8245 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8246 bool Swap = false, Invert = false, FlipSigns = false;
8248 switch (VT.getSimpleVT().SimpleTy) {
8250 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8251 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8252 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8253 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8256 switch (SetCCOpcode) {
8258 case ISD::SETNE: Invert = true;
8259 case ISD::SETEQ: Opc = EQOpc; break;
8260 case ISD::SETLT: Swap = true;
8261 case ISD::SETGT: Opc = GTOpc; break;
8262 case ISD::SETGE: Swap = true;
8263 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
8264 case ISD::SETULT: Swap = true;
8265 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8266 case ISD::SETUGE: Swap = true;
8267 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8270 std::swap(Op0, Op1);
8272 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8273 // bits of the inputs before performing those operations.
8275 EVT EltVT = VT.getVectorElementType();
8276 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8278 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8279 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8281 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8282 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8285 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8287 // If the logical-not of the result is required, perform that now.
8289 Result = DAG.getNOT(dl, Result, VT);
8294 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8295 static bool isX86LogicalCmp(SDValue Op) {
8296 unsigned Opc = Op.getNode()->getOpcode();
8297 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8299 if (Op.getResNo() == 1 &&
8300 (Opc == X86ISD::ADD ||
8301 Opc == X86ISD::SUB ||
8302 Opc == X86ISD::ADC ||
8303 Opc == X86ISD::SBB ||
8304 Opc == X86ISD::SMUL ||
8305 Opc == X86ISD::UMUL ||
8306 Opc == X86ISD::INC ||
8307 Opc == X86ISD::DEC ||
8308 Opc == X86ISD::OR ||
8309 Opc == X86ISD::XOR ||
8310 Opc == X86ISD::AND))
8313 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8319 static bool isZero(SDValue V) {
8320 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8321 return C && C->isNullValue();
8324 static bool isAllOnes(SDValue V) {
8325 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8326 return C && C->isAllOnesValue();
8329 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8330 bool addTest = true;
8331 SDValue Cond = Op.getOperand(0);
8332 SDValue Op1 = Op.getOperand(1);
8333 SDValue Op2 = Op.getOperand(2);
8334 DebugLoc DL = Op.getDebugLoc();
8337 if (Cond.getOpcode() == ISD::SETCC) {
8338 SDValue NewCond = LowerSETCC(Cond, DAG);
8339 if (NewCond.getNode())
8343 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8344 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8345 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8346 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8347 if (Cond.getOpcode() == X86ISD::SETCC &&
8348 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8349 isZero(Cond.getOperand(1).getOperand(1))) {
8350 SDValue Cmp = Cond.getOperand(1);
8352 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8354 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8355 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8356 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8358 SDValue CmpOp0 = Cmp.getOperand(0);
8359 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8360 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8362 SDValue Res = // Res = 0 or -1.
8363 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8364 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8366 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8367 Res = DAG.getNOT(DL, Res, Res.getValueType());
8369 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8370 if (N2C == 0 || !N2C->isNullValue())
8371 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8376 // Look past (and (setcc_carry (cmp ...)), 1).
8377 if (Cond.getOpcode() == ISD::AND &&
8378 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8379 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8380 if (C && C->getAPIntValue() == 1)
8381 Cond = Cond.getOperand(0);
8384 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8385 // setting operand in place of the X86ISD::SETCC.
8386 if (Cond.getOpcode() == X86ISD::SETCC ||
8387 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8388 CC = Cond.getOperand(0);
8390 SDValue Cmp = Cond.getOperand(1);
8391 unsigned Opc = Cmp.getOpcode();
8392 EVT VT = Op.getValueType();
8394 bool IllegalFPCMov = false;
8395 if (VT.isFloatingPoint() && !VT.isVector() &&
8396 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8397 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8399 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8400 Opc == X86ISD::BT) { // FIXME
8407 // Look pass the truncate.
8408 if (Cond.getOpcode() == ISD::TRUNCATE)
8409 Cond = Cond.getOperand(0);
8411 // We know the result of AND is compared against zero. Try to match
8413 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8414 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8415 if (NewSetCC.getNode()) {
8416 CC = NewSetCC.getOperand(0);
8417 Cond = NewSetCC.getOperand(1);
8424 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8425 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8428 // a < b ? -1 : 0 -> RES = ~setcc_carry
8429 // a < b ? 0 : -1 -> RES = setcc_carry
8430 // a >= b ? -1 : 0 -> RES = setcc_carry
8431 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8432 if (Cond.getOpcode() == X86ISD::CMP) {
8433 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8435 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8436 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8437 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8438 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8439 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8440 return DAG.getNOT(DL, Res, Res.getValueType());
8445 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8446 // condition is true.
8447 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8448 SDValue Ops[] = { Op2, Op1, CC, Cond };
8449 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8452 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8453 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8454 // from the AND / OR.
8455 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8456 Opc = Op.getOpcode();
8457 if (Opc != ISD::OR && Opc != ISD::AND)
8459 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8460 Op.getOperand(0).hasOneUse() &&
8461 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8462 Op.getOperand(1).hasOneUse());
8465 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8466 // 1 and that the SETCC node has a single use.
8467 static bool isXor1OfSetCC(SDValue Op) {
8468 if (Op.getOpcode() != ISD::XOR)
8470 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8471 if (N1C && N1C->getAPIntValue() == 1) {
8472 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8473 Op.getOperand(0).hasOneUse();
8478 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8479 bool addTest = true;
8480 SDValue Chain = Op.getOperand(0);
8481 SDValue Cond = Op.getOperand(1);
8482 SDValue Dest = Op.getOperand(2);
8483 DebugLoc dl = Op.getDebugLoc();
8486 if (Cond.getOpcode() == ISD::SETCC) {
8487 SDValue NewCond = LowerSETCC(Cond, DAG);
8488 if (NewCond.getNode())
8492 // FIXME: LowerXALUO doesn't handle these!!
8493 else if (Cond.getOpcode() == X86ISD::ADD ||
8494 Cond.getOpcode() == X86ISD::SUB ||
8495 Cond.getOpcode() == X86ISD::SMUL ||
8496 Cond.getOpcode() == X86ISD::UMUL)
8497 Cond = LowerXALUO(Cond, DAG);
8500 // Look pass (and (setcc_carry (cmp ...)), 1).
8501 if (Cond.getOpcode() == ISD::AND &&
8502 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8503 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8504 if (C && C->getAPIntValue() == 1)
8505 Cond = Cond.getOperand(0);
8508 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8509 // setting operand in place of the X86ISD::SETCC.
8510 if (Cond.getOpcode() == X86ISD::SETCC ||
8511 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8512 CC = Cond.getOperand(0);
8514 SDValue Cmp = Cond.getOperand(1);
8515 unsigned Opc = Cmp.getOpcode();
8516 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8517 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8521 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8525 // These can only come from an arithmetic instruction with overflow,
8526 // e.g. SADDO, UADDO.
8527 Cond = Cond.getNode()->getOperand(1);
8534 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8535 SDValue Cmp = Cond.getOperand(0).getOperand(1);
8536 if (CondOpc == ISD::OR) {
8537 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8538 // two branches instead of an explicit OR instruction with a
8540 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8541 isX86LogicalCmp(Cmp)) {
8542 CC = Cond.getOperand(0).getOperand(0);
8543 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8544 Chain, Dest, CC, Cmp);
8545 CC = Cond.getOperand(1).getOperand(0);
8549 } else { // ISD::AND
8550 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8551 // two branches instead of an explicit AND instruction with a
8552 // separate test. However, we only do this if this block doesn't
8553 // have a fall-through edge, because this requires an explicit
8554 // jmp when the condition is false.
8555 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8556 isX86LogicalCmp(Cmp) &&
8557 Op.getNode()->hasOneUse()) {
8558 X86::CondCode CCode =
8559 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8560 CCode = X86::GetOppositeBranchCondition(CCode);
8561 CC = DAG.getConstant(CCode, MVT::i8);
8562 SDNode *User = *Op.getNode()->use_begin();
8563 // Look for an unconditional branch following this conditional branch.
8564 // We need this because we need to reverse the successors in order
8565 // to implement FCMP_OEQ.
8566 if (User->getOpcode() == ISD::BR) {
8567 SDValue FalseBB = User->getOperand(1);
8569 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8570 assert(NewBR == User);
8574 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8575 Chain, Dest, CC, Cmp);
8576 X86::CondCode CCode =
8577 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8578 CCode = X86::GetOppositeBranchCondition(CCode);
8579 CC = DAG.getConstant(CCode, MVT::i8);
8585 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8586 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8587 // It should be transformed during dag combiner except when the condition
8588 // is set by a arithmetics with overflow node.
8589 X86::CondCode CCode =
8590 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8591 CCode = X86::GetOppositeBranchCondition(CCode);
8592 CC = DAG.getConstant(CCode, MVT::i8);
8593 Cond = Cond.getOperand(0).getOperand(1);
8599 // Look pass the truncate.
8600 if (Cond.getOpcode() == ISD::TRUNCATE)
8601 Cond = Cond.getOperand(0);
8603 // We know the result of AND is compared against zero. Try to match
8605 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8606 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8607 if (NewSetCC.getNode()) {
8608 CC = NewSetCC.getOperand(0);
8609 Cond = NewSetCC.getOperand(1);
8616 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8617 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8619 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8620 Chain, Dest, CC, Cond);
8624 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8625 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8626 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8627 // that the guard pages used by the OS virtual memory manager are allocated in
8628 // correct sequence.
8630 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8631 SelectionDAG &DAG) const {
8632 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8633 "This should be used only on Windows targets");
8634 assert(!Subtarget->isTargetEnvMacho());
8635 DebugLoc dl = Op.getDebugLoc();
8638 SDValue Chain = Op.getOperand(0);
8639 SDValue Size = Op.getOperand(1);
8640 // FIXME: Ensure alignment here
8644 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8645 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8647 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8648 Flag = Chain.getValue(1);
8650 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8652 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8653 Flag = Chain.getValue(1);
8655 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8657 SDValue Ops1[2] = { Chain.getValue(0), Chain };
8658 return DAG.getMergeValues(Ops1, 2, dl);
8661 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8662 MachineFunction &MF = DAG.getMachineFunction();
8663 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8665 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8666 DebugLoc DL = Op.getDebugLoc();
8668 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8669 // vastart just stores the address of the VarArgsFrameIndex slot into the
8670 // memory location argument.
8671 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8673 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8674 MachinePointerInfo(SV), false, false, 0);
8678 // gp_offset (0 - 6 * 8)
8679 // fp_offset (48 - 48 + 8 * 16)
8680 // overflow_arg_area (point to parameters coming in memory).
8682 SmallVector<SDValue, 8> MemOps;
8683 SDValue FIN = Op.getOperand(1);
8685 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8686 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8688 FIN, MachinePointerInfo(SV), false, false, 0);
8689 MemOps.push_back(Store);
8692 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8693 FIN, DAG.getIntPtrConstant(4));
8694 Store = DAG.getStore(Op.getOperand(0), DL,
8695 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8697 FIN, MachinePointerInfo(SV, 4), false, false, 0);
8698 MemOps.push_back(Store);
8700 // Store ptr to overflow_arg_area
8701 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8702 FIN, DAG.getIntPtrConstant(4));
8703 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8705 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8706 MachinePointerInfo(SV, 8),
8708 MemOps.push_back(Store);
8710 // Store ptr to reg_save_area.
8711 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8712 FIN, DAG.getIntPtrConstant(8));
8713 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8715 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8716 MachinePointerInfo(SV, 16), false, false, 0);
8717 MemOps.push_back(Store);
8718 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8719 &MemOps[0], MemOps.size());
8722 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8723 assert(Subtarget->is64Bit() &&
8724 "LowerVAARG only handles 64-bit va_arg!");
8725 assert((Subtarget->isTargetLinux() ||
8726 Subtarget->isTargetDarwin()) &&
8727 "Unhandled target in LowerVAARG");
8728 assert(Op.getNode()->getNumOperands() == 4);
8729 SDValue Chain = Op.getOperand(0);
8730 SDValue SrcPtr = Op.getOperand(1);
8731 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8732 unsigned Align = Op.getConstantOperandVal(3);
8733 DebugLoc dl = Op.getDebugLoc();
8735 EVT ArgVT = Op.getNode()->getValueType(0);
8736 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8737 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8740 // Decide which area this value should be read from.
8741 // TODO: Implement the AMD64 ABI in its entirety. This simple
8742 // selection mechanism works only for the basic types.
8743 if (ArgVT == MVT::f80) {
8744 llvm_unreachable("va_arg for f80 not yet implemented");
8745 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8746 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
8747 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8748 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
8750 llvm_unreachable("Unhandled argument type in LowerVAARG");
8754 // Sanity Check: Make sure using fp_offset makes sense.
8755 assert(!UseSoftFloat &&
8756 !(DAG.getMachineFunction()
8757 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8758 Subtarget->hasXMM());
8761 // Insert VAARG_64 node into the DAG
8762 // VAARG_64 returns two values: Variable Argument Address, Chain
8763 SmallVector<SDValue, 11> InstOps;
8764 InstOps.push_back(Chain);
8765 InstOps.push_back(SrcPtr);
8766 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8767 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8768 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8769 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8770 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8771 VTs, &InstOps[0], InstOps.size(),
8773 MachinePointerInfo(SV),
8778 Chain = VAARG.getValue(1);
8780 // Load the next argument and return it
8781 return DAG.getLoad(ArgVT, dl,
8784 MachinePointerInfo(),
8788 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8789 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8790 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8791 SDValue Chain = Op.getOperand(0);
8792 SDValue DstPtr = Op.getOperand(1);
8793 SDValue SrcPtr = Op.getOperand(2);
8794 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8795 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8796 DebugLoc DL = Op.getDebugLoc();
8798 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8799 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8801 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8805 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8806 DebugLoc dl = Op.getDebugLoc();
8807 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8809 default: return SDValue(); // Don't custom lower most intrinsics.
8810 // Comparison intrinsics.
8811 case Intrinsic::x86_sse_comieq_ss:
8812 case Intrinsic::x86_sse_comilt_ss:
8813 case Intrinsic::x86_sse_comile_ss:
8814 case Intrinsic::x86_sse_comigt_ss:
8815 case Intrinsic::x86_sse_comige_ss:
8816 case Intrinsic::x86_sse_comineq_ss:
8817 case Intrinsic::x86_sse_ucomieq_ss:
8818 case Intrinsic::x86_sse_ucomilt_ss:
8819 case Intrinsic::x86_sse_ucomile_ss:
8820 case Intrinsic::x86_sse_ucomigt_ss:
8821 case Intrinsic::x86_sse_ucomige_ss:
8822 case Intrinsic::x86_sse_ucomineq_ss:
8823 case Intrinsic::x86_sse2_comieq_sd:
8824 case Intrinsic::x86_sse2_comilt_sd:
8825 case Intrinsic::x86_sse2_comile_sd:
8826 case Intrinsic::x86_sse2_comigt_sd:
8827 case Intrinsic::x86_sse2_comige_sd:
8828 case Intrinsic::x86_sse2_comineq_sd:
8829 case Intrinsic::x86_sse2_ucomieq_sd:
8830 case Intrinsic::x86_sse2_ucomilt_sd:
8831 case Intrinsic::x86_sse2_ucomile_sd:
8832 case Intrinsic::x86_sse2_ucomigt_sd:
8833 case Intrinsic::x86_sse2_ucomige_sd:
8834 case Intrinsic::x86_sse2_ucomineq_sd: {
8836 ISD::CondCode CC = ISD::SETCC_INVALID;
8839 case Intrinsic::x86_sse_comieq_ss:
8840 case Intrinsic::x86_sse2_comieq_sd:
8844 case Intrinsic::x86_sse_comilt_ss:
8845 case Intrinsic::x86_sse2_comilt_sd:
8849 case Intrinsic::x86_sse_comile_ss:
8850 case Intrinsic::x86_sse2_comile_sd:
8854 case Intrinsic::x86_sse_comigt_ss:
8855 case Intrinsic::x86_sse2_comigt_sd:
8859 case Intrinsic::x86_sse_comige_ss:
8860 case Intrinsic::x86_sse2_comige_sd:
8864 case Intrinsic::x86_sse_comineq_ss:
8865 case Intrinsic::x86_sse2_comineq_sd:
8869 case Intrinsic::x86_sse_ucomieq_ss:
8870 case Intrinsic::x86_sse2_ucomieq_sd:
8871 Opc = X86ISD::UCOMI;
8874 case Intrinsic::x86_sse_ucomilt_ss:
8875 case Intrinsic::x86_sse2_ucomilt_sd:
8876 Opc = X86ISD::UCOMI;
8879 case Intrinsic::x86_sse_ucomile_ss:
8880 case Intrinsic::x86_sse2_ucomile_sd:
8881 Opc = X86ISD::UCOMI;
8884 case Intrinsic::x86_sse_ucomigt_ss:
8885 case Intrinsic::x86_sse2_ucomigt_sd:
8886 Opc = X86ISD::UCOMI;
8889 case Intrinsic::x86_sse_ucomige_ss:
8890 case Intrinsic::x86_sse2_ucomige_sd:
8891 Opc = X86ISD::UCOMI;
8894 case Intrinsic::x86_sse_ucomineq_ss:
8895 case Intrinsic::x86_sse2_ucomineq_sd:
8896 Opc = X86ISD::UCOMI;
8901 SDValue LHS = Op.getOperand(1);
8902 SDValue RHS = Op.getOperand(2);
8903 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8904 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8905 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8906 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8907 DAG.getConstant(X86CC, MVT::i8), Cond);
8908 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8910 // ptest and testp intrinsics. The intrinsic these come from are designed to
8911 // return an integer value, not just an instruction so lower it to the ptest
8912 // or testp pattern and a setcc for the result.
8913 case Intrinsic::x86_sse41_ptestz:
8914 case Intrinsic::x86_sse41_ptestc:
8915 case Intrinsic::x86_sse41_ptestnzc:
8916 case Intrinsic::x86_avx_ptestz_256:
8917 case Intrinsic::x86_avx_ptestc_256:
8918 case Intrinsic::x86_avx_ptestnzc_256:
8919 case Intrinsic::x86_avx_vtestz_ps:
8920 case Intrinsic::x86_avx_vtestc_ps:
8921 case Intrinsic::x86_avx_vtestnzc_ps:
8922 case Intrinsic::x86_avx_vtestz_pd:
8923 case Intrinsic::x86_avx_vtestc_pd:
8924 case Intrinsic::x86_avx_vtestnzc_pd:
8925 case Intrinsic::x86_avx_vtestz_ps_256:
8926 case Intrinsic::x86_avx_vtestc_ps_256:
8927 case Intrinsic::x86_avx_vtestnzc_ps_256:
8928 case Intrinsic::x86_avx_vtestz_pd_256:
8929 case Intrinsic::x86_avx_vtestc_pd_256:
8930 case Intrinsic::x86_avx_vtestnzc_pd_256: {
8931 bool IsTestPacked = false;
8934 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8935 case Intrinsic::x86_avx_vtestz_ps:
8936 case Intrinsic::x86_avx_vtestz_pd:
8937 case Intrinsic::x86_avx_vtestz_ps_256:
8938 case Intrinsic::x86_avx_vtestz_pd_256:
8939 IsTestPacked = true; // Fallthrough
8940 case Intrinsic::x86_sse41_ptestz:
8941 case Intrinsic::x86_avx_ptestz_256:
8943 X86CC = X86::COND_E;
8945 case Intrinsic::x86_avx_vtestc_ps:
8946 case Intrinsic::x86_avx_vtestc_pd:
8947 case Intrinsic::x86_avx_vtestc_ps_256:
8948 case Intrinsic::x86_avx_vtestc_pd_256:
8949 IsTestPacked = true; // Fallthrough
8950 case Intrinsic::x86_sse41_ptestc:
8951 case Intrinsic::x86_avx_ptestc_256:
8953 X86CC = X86::COND_B;
8955 case Intrinsic::x86_avx_vtestnzc_ps:
8956 case Intrinsic::x86_avx_vtestnzc_pd:
8957 case Intrinsic::x86_avx_vtestnzc_ps_256:
8958 case Intrinsic::x86_avx_vtestnzc_pd_256:
8959 IsTestPacked = true; // Fallthrough
8960 case Intrinsic::x86_sse41_ptestnzc:
8961 case Intrinsic::x86_avx_ptestnzc_256:
8963 X86CC = X86::COND_A;
8967 SDValue LHS = Op.getOperand(1);
8968 SDValue RHS = Op.getOperand(2);
8969 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8970 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8971 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8972 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8973 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8976 // Fix vector shift instructions where the last operand is a non-immediate
8978 case Intrinsic::x86_sse2_pslli_w:
8979 case Intrinsic::x86_sse2_pslli_d:
8980 case Intrinsic::x86_sse2_pslli_q:
8981 case Intrinsic::x86_sse2_psrli_w:
8982 case Intrinsic::x86_sse2_psrli_d:
8983 case Intrinsic::x86_sse2_psrli_q:
8984 case Intrinsic::x86_sse2_psrai_w:
8985 case Intrinsic::x86_sse2_psrai_d:
8986 case Intrinsic::x86_mmx_pslli_w:
8987 case Intrinsic::x86_mmx_pslli_d:
8988 case Intrinsic::x86_mmx_pslli_q:
8989 case Intrinsic::x86_mmx_psrli_w:
8990 case Intrinsic::x86_mmx_psrli_d:
8991 case Intrinsic::x86_mmx_psrli_q:
8992 case Intrinsic::x86_mmx_psrai_w:
8993 case Intrinsic::x86_mmx_psrai_d: {
8994 SDValue ShAmt = Op.getOperand(2);
8995 if (isa<ConstantSDNode>(ShAmt))
8998 unsigned NewIntNo = 0;
8999 EVT ShAmtVT = MVT::v4i32;
9001 case Intrinsic::x86_sse2_pslli_w:
9002 NewIntNo = Intrinsic::x86_sse2_psll_w;
9004 case Intrinsic::x86_sse2_pslli_d:
9005 NewIntNo = Intrinsic::x86_sse2_psll_d;
9007 case Intrinsic::x86_sse2_pslli_q:
9008 NewIntNo = Intrinsic::x86_sse2_psll_q;
9010 case Intrinsic::x86_sse2_psrli_w:
9011 NewIntNo = Intrinsic::x86_sse2_psrl_w;
9013 case Intrinsic::x86_sse2_psrli_d:
9014 NewIntNo = Intrinsic::x86_sse2_psrl_d;
9016 case Intrinsic::x86_sse2_psrli_q:
9017 NewIntNo = Intrinsic::x86_sse2_psrl_q;
9019 case Intrinsic::x86_sse2_psrai_w:
9020 NewIntNo = Intrinsic::x86_sse2_psra_w;
9022 case Intrinsic::x86_sse2_psrai_d:
9023 NewIntNo = Intrinsic::x86_sse2_psra_d;
9026 ShAmtVT = MVT::v2i32;
9028 case Intrinsic::x86_mmx_pslli_w:
9029 NewIntNo = Intrinsic::x86_mmx_psll_w;
9031 case Intrinsic::x86_mmx_pslli_d:
9032 NewIntNo = Intrinsic::x86_mmx_psll_d;
9034 case Intrinsic::x86_mmx_pslli_q:
9035 NewIntNo = Intrinsic::x86_mmx_psll_q;
9037 case Intrinsic::x86_mmx_psrli_w:
9038 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9040 case Intrinsic::x86_mmx_psrli_d:
9041 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9043 case Intrinsic::x86_mmx_psrli_q:
9044 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9046 case Intrinsic::x86_mmx_psrai_w:
9047 NewIntNo = Intrinsic::x86_mmx_psra_w;
9049 case Intrinsic::x86_mmx_psrai_d:
9050 NewIntNo = Intrinsic::x86_mmx_psra_d;
9052 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9058 // The vector shift intrinsics with scalars uses 32b shift amounts but
9059 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9063 ShOps[1] = DAG.getConstant(0, MVT::i32);
9064 if (ShAmtVT == MVT::v4i32) {
9065 ShOps[2] = DAG.getUNDEF(MVT::i32);
9066 ShOps[3] = DAG.getUNDEF(MVT::i32);
9067 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9069 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9070 // FIXME this must be lowered to get rid of the invalid type.
9073 EVT VT = Op.getValueType();
9074 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9075 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9076 DAG.getConstant(NewIntNo, MVT::i32),
9077 Op.getOperand(1), ShAmt);
9082 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9083 SelectionDAG &DAG) const {
9084 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9085 MFI->setReturnAddressIsTaken(true);
9087 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9088 DebugLoc dl = Op.getDebugLoc();
9091 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9093 DAG.getConstant(TD->getPointerSize(),
9094 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9095 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9096 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9098 MachinePointerInfo(), false, false, 0);
9101 // Just load the return address.
9102 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9103 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9104 RetAddrFI, MachinePointerInfo(), false, false, 0);
9107 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9108 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9109 MFI->setFrameAddressIsTaken(true);
9111 EVT VT = Op.getValueType();
9112 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9113 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9114 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9115 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9117 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9118 MachinePointerInfo(),
9123 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9124 SelectionDAG &DAG) const {
9125 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9128 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9129 MachineFunction &MF = DAG.getMachineFunction();
9130 SDValue Chain = Op.getOperand(0);
9131 SDValue Offset = Op.getOperand(1);
9132 SDValue Handler = Op.getOperand(2);
9133 DebugLoc dl = Op.getDebugLoc();
9135 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9136 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9138 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9140 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9141 DAG.getIntPtrConstant(TD->getPointerSize()));
9142 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9143 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9145 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9146 MF.getRegInfo().addLiveOut(StoreAddrReg);
9148 return DAG.getNode(X86ISD::EH_RETURN, dl,
9150 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9153 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
9154 SelectionDAG &DAG) const {
9155 SDValue Root = Op.getOperand(0);
9156 SDValue Trmp = Op.getOperand(1); // trampoline
9157 SDValue FPtr = Op.getOperand(2); // nested function
9158 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9159 DebugLoc dl = Op.getDebugLoc();
9161 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9163 if (Subtarget->is64Bit()) {
9164 SDValue OutChains[6];
9166 // Large code-model.
9167 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
9168 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9170 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9171 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9173 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9175 // Load the pointer to the nested function into R11.
9176 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9177 SDValue Addr = Trmp;
9178 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9179 Addr, MachinePointerInfo(TrmpAddr),
9182 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9183 DAG.getConstant(2, MVT::i64));
9184 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9185 MachinePointerInfo(TrmpAddr, 2),
9188 // Load the 'nest' parameter value into R10.
9189 // R10 is specified in X86CallingConv.td
9190 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9191 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9192 DAG.getConstant(10, MVT::i64));
9193 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9194 Addr, MachinePointerInfo(TrmpAddr, 10),
9197 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9198 DAG.getConstant(12, MVT::i64));
9199 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9200 MachinePointerInfo(TrmpAddr, 12),
9203 // Jump to the nested function.
9204 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9205 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9206 DAG.getConstant(20, MVT::i64));
9207 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9208 Addr, MachinePointerInfo(TrmpAddr, 20),
9211 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9212 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9213 DAG.getConstant(22, MVT::i64));
9214 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9215 MachinePointerInfo(TrmpAddr, 22),
9219 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
9220 return DAG.getMergeValues(Ops, 2, dl);
9222 const Function *Func =
9223 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9224 CallingConv::ID CC = Func->getCallingConv();
9229 llvm_unreachable("Unsupported calling convention");
9230 case CallingConv::C:
9231 case CallingConv::X86_StdCall: {
9232 // Pass 'nest' parameter in ECX.
9233 // Must be kept in sync with X86CallingConv.td
9236 // Check that ECX wasn't needed by an 'inreg' parameter.
9237 FunctionType *FTy = Func->getFunctionType();
9238 const AttrListPtr &Attrs = Func->getAttributes();
9240 if (!Attrs.isEmpty() && !Func->isVarArg()) {
9241 unsigned InRegCount = 0;
9244 for (FunctionType::param_iterator I = FTy->param_begin(),
9245 E = FTy->param_end(); I != E; ++I, ++Idx)
9246 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9247 // FIXME: should only count parameters that are lowered to integers.
9248 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9250 if (InRegCount > 2) {
9251 report_fatal_error("Nest register in use - reduce number of inreg"
9257 case CallingConv::X86_FastCall:
9258 case CallingConv::X86_ThisCall:
9259 case CallingConv::Fast:
9260 // Pass 'nest' parameter in EAX.
9261 // Must be kept in sync with X86CallingConv.td
9266 SDValue OutChains[4];
9269 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9270 DAG.getConstant(10, MVT::i32));
9271 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9273 // This is storing the opcode for MOV32ri.
9274 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9275 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9276 OutChains[0] = DAG.getStore(Root, dl,
9277 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9278 Trmp, MachinePointerInfo(TrmpAddr),
9281 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9282 DAG.getConstant(1, MVT::i32));
9283 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9284 MachinePointerInfo(TrmpAddr, 1),
9287 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9288 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9289 DAG.getConstant(5, MVT::i32));
9290 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9291 MachinePointerInfo(TrmpAddr, 5),
9294 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9295 DAG.getConstant(6, MVT::i32));
9296 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9297 MachinePointerInfo(TrmpAddr, 6),
9301 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
9302 return DAG.getMergeValues(Ops, 2, dl);
9306 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9307 SelectionDAG &DAG) const {
9309 The rounding mode is in bits 11:10 of FPSR, and has the following
9316 FLT_ROUNDS, on the other hand, expects the following:
9323 To perform the conversion, we do:
9324 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9327 MachineFunction &MF = DAG.getMachineFunction();
9328 const TargetMachine &TM = MF.getTarget();
9329 const TargetFrameLowering &TFI = *TM.getFrameLowering();
9330 unsigned StackAlignment = TFI.getStackAlignment();
9331 EVT VT = Op.getValueType();
9332 DebugLoc DL = Op.getDebugLoc();
9334 // Save FP Control Word to stack slot
9335 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9336 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9339 MachineMemOperand *MMO =
9340 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9341 MachineMemOperand::MOStore, 2, 2);
9343 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9344 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9345 DAG.getVTList(MVT::Other),
9346 Ops, 2, MVT::i16, MMO);
9348 // Load FP Control Word from stack slot
9349 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9350 MachinePointerInfo(), false, false, 0);
9352 // Transform as necessary
9354 DAG.getNode(ISD::SRL, DL, MVT::i16,
9355 DAG.getNode(ISD::AND, DL, MVT::i16,
9356 CWD, DAG.getConstant(0x800, MVT::i16)),
9357 DAG.getConstant(11, MVT::i8));
9359 DAG.getNode(ISD::SRL, DL, MVT::i16,
9360 DAG.getNode(ISD::AND, DL, MVT::i16,
9361 CWD, DAG.getConstant(0x400, MVT::i16)),
9362 DAG.getConstant(9, MVT::i8));
9365 DAG.getNode(ISD::AND, DL, MVT::i16,
9366 DAG.getNode(ISD::ADD, DL, MVT::i16,
9367 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9368 DAG.getConstant(1, MVT::i16)),
9369 DAG.getConstant(3, MVT::i16));
9372 return DAG.getNode((VT.getSizeInBits() < 16 ?
9373 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9376 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9377 EVT VT = Op.getValueType();
9379 unsigned NumBits = VT.getSizeInBits();
9380 DebugLoc dl = Op.getDebugLoc();
9382 Op = Op.getOperand(0);
9383 if (VT == MVT::i8) {
9384 // Zero extend to i32 since there is not an i8 bsr.
9386 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9389 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9390 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9391 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9393 // If src is zero (i.e. bsr sets ZF), returns NumBits.
9396 DAG.getConstant(NumBits+NumBits-1, OpVT),
9397 DAG.getConstant(X86::COND_E, MVT::i8),
9400 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9402 // Finally xor with NumBits-1.
9403 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9406 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9410 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9411 EVT VT = Op.getValueType();
9413 unsigned NumBits = VT.getSizeInBits();
9414 DebugLoc dl = Op.getDebugLoc();
9416 Op = Op.getOperand(0);
9417 if (VT == MVT::i8) {
9419 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9422 // Issue a bsf (scan bits forward) which also sets EFLAGS.
9423 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9424 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9426 // If src is zero (i.e. bsf sets ZF), returns NumBits.
9429 DAG.getConstant(NumBits, OpVT),
9430 DAG.getConstant(X86::COND_E, MVT::i8),
9433 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9436 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9440 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9441 // ones, and then concatenate the result back.
9442 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9443 EVT VT = Op.getValueType();
9445 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9446 "Unsupported value type for operation");
9448 int NumElems = VT.getVectorNumElements();
9449 DebugLoc dl = Op.getDebugLoc();
9450 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9451 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9453 // Extract the LHS vectors
9454 SDValue LHS = Op.getOperand(0);
9455 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9456 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9458 // Extract the RHS vectors
9459 SDValue RHS = Op.getOperand(1);
9460 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9461 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9463 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9464 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9466 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9467 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9468 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9471 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9472 assert(Op.getValueType().getSizeInBits() == 256 &&
9473 Op.getValueType().isInteger() &&
9474 "Only handle AVX 256-bit vector integer operation");
9475 return Lower256IntArith(Op, DAG);
9478 SDValue X86TargetLowering::LowerSUB(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::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9486 EVT VT = Op.getValueType();
9488 // Decompose 256-bit ops into smaller 128-bit ops.
9489 if (VT.getSizeInBits() == 256)
9490 return Lower256IntArith(Op, DAG);
9492 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9493 DebugLoc dl = Op.getDebugLoc();
9495 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9496 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9497 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9498 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9499 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9501 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9502 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9503 // return AloBlo + AloBhi + AhiBlo;
9505 SDValue A = Op.getOperand(0);
9506 SDValue B = Op.getOperand(1);
9508 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9509 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9510 A, DAG.getConstant(32, MVT::i32));
9511 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9512 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9513 B, DAG.getConstant(32, MVT::i32));
9514 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9515 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9517 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9518 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9520 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9521 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9523 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9524 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9525 AloBhi, DAG.getConstant(32, MVT::i32));
9526 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9527 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9528 AhiBlo, DAG.getConstant(32, MVT::i32));
9529 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9530 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9534 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
9536 EVT VT = Op.getValueType();
9537 DebugLoc dl = Op.getDebugLoc();
9538 SDValue R = Op.getOperand(0);
9539 SDValue Amt = Op.getOperand(1);
9540 LLVMContext *Context = DAG.getContext();
9542 if (!(Subtarget->hasSSE2() || Subtarget->hasAVX()))
9545 // Decompose 256-bit shifts into smaller 128-bit shifts.
9546 if (VT.getSizeInBits() == 256) {
9547 int NumElems = VT.getVectorNumElements();
9548 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9549 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9551 // Extract the two vectors
9552 SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
9553 SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
9556 // Recreate the shift amount vectors
9558 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
9559 // Constant shift amount
9560 SmallVector<SDValue, 4> Amt1Csts;
9561 SmallVector<SDValue, 4> Amt2Csts;
9562 for (int i = 0; i < NumElems/2; ++i)
9563 Amt1Csts.push_back(Amt->getOperand(i));
9564 for (int i = NumElems/2; i < NumElems; ++i)
9565 Amt2Csts.push_back(Amt->getOperand(i));
9567 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9568 &Amt1Csts[0], NumElems/2);
9569 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9570 &Amt2Csts[0], NumElems/2);
9572 // Variable shift amount
9573 Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
9574 Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
9578 // Issue new vector shifts for the smaller types
9579 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
9580 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
9582 // Concatenate the result back
9583 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
9586 // Optimize shl/srl/sra with constant shift amount.
9587 if (isSplatVector(Amt.getNode())) {
9588 SDValue SclrAmt = Amt->getOperand(0);
9589 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
9590 uint64_t ShiftAmt = C->getZExtValue();
9592 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
9593 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9594 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9595 R, DAG.getConstant(ShiftAmt, MVT::i32));
9597 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
9598 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9599 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9600 R, DAG.getConstant(ShiftAmt, MVT::i32));
9602 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
9603 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9604 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9605 R, DAG.getConstant(ShiftAmt, MVT::i32));
9607 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
9608 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9609 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9610 R, DAG.getConstant(ShiftAmt, MVT::i32));
9612 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
9613 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9614 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9615 R, DAG.getConstant(ShiftAmt, MVT::i32));
9617 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
9618 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9619 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9620 R, DAG.getConstant(ShiftAmt, MVT::i32));
9622 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
9623 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9624 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9625 R, DAG.getConstant(ShiftAmt, MVT::i32));
9627 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
9628 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9629 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9630 R, DAG.getConstant(ShiftAmt, MVT::i32));
9634 // Lower SHL with variable shift amount.
9635 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
9636 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9637 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9638 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
9640 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
9642 std::vector<Constant*> CV(4, CI);
9643 Constant *C = ConstantVector::get(CV);
9644 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9645 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9646 MachinePointerInfo::getConstantPool(),
9649 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
9650 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
9651 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9652 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9654 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9656 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9657 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9658 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9660 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
9661 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
9663 std::vector<Constant*> CVM1(16, CM1);
9664 std::vector<Constant*> CVM2(16, CM2);
9665 Constant *C = ConstantVector::get(CVM1);
9666 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9667 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9668 MachinePointerInfo::getConstantPool(),
9671 // r = pblendv(r, psllw(r & (char16)15, 4), a);
9672 M = DAG.getNode(ISD::AND, dl, VT, R, M);
9673 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9674 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9675 DAG.getConstant(4, MVT::i32));
9676 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9678 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9680 C = ConstantVector::get(CVM2);
9681 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9682 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9683 MachinePointerInfo::getConstantPool(),
9686 // r = pblendv(r, psllw(r & (char16)63, 2), a);
9687 M = DAG.getNode(ISD::AND, dl, VT, R, M);
9688 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9689 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9690 DAG.getConstant(2, MVT::i32));
9691 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9693 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9695 // return pblendv(r, r+r, a);
9696 R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
9697 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
9703 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
9704 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
9705 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
9706 // looks for this combo and may remove the "setcc" instruction if the "setcc"
9707 // has only one use.
9708 SDNode *N = Op.getNode();
9709 SDValue LHS = N->getOperand(0);
9710 SDValue RHS = N->getOperand(1);
9711 unsigned BaseOp = 0;
9713 DebugLoc DL = Op.getDebugLoc();
9714 switch (Op.getOpcode()) {
9715 default: llvm_unreachable("Unknown ovf instruction!");
9717 // A subtract of one will be selected as a INC. Note that INC doesn't
9718 // set CF, so we can't do this for UADDO.
9719 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9721 BaseOp = X86ISD::INC;
9725 BaseOp = X86ISD::ADD;
9729 BaseOp = X86ISD::ADD;
9733 // A subtract of one will be selected as a DEC. Note that DEC doesn't
9734 // set CF, so we can't do this for USUBO.
9735 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9737 BaseOp = X86ISD::DEC;
9741 BaseOp = X86ISD::SUB;
9745 BaseOp = X86ISD::SUB;
9749 BaseOp = X86ISD::SMUL;
9752 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9753 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9755 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9758 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9759 DAG.getConstant(X86::COND_O, MVT::i32),
9760 SDValue(Sum.getNode(), 2));
9762 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
9766 // Also sets EFLAGS.
9767 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9768 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9771 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9772 DAG.getConstant(Cond, MVT::i32),
9773 SDValue(Sum.getNode(), 1));
9775 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
9778 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
9779 DebugLoc dl = Op.getDebugLoc();
9780 SDNode* Node = Op.getNode();
9781 EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
9782 EVT VT = Node->getValueType(0);
9784 if (Subtarget->hasSSE2() && VT.isVector()) {
9785 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
9786 ExtraVT.getScalarType().getSizeInBits();
9787 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
9789 unsigned SHLIntrinsicsID = 0;
9790 unsigned SRAIntrinsicsID = 0;
9791 switch (VT.getSimpleVT().SimpleTy) {
9795 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q;
9796 SRAIntrinsicsID = 0;
9800 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
9801 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
9805 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
9806 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
9811 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9812 DAG.getConstant(SHLIntrinsicsID, MVT::i32),
9813 Node->getOperand(0), ShAmt);
9815 // In case of 1 bit sext, no need to shr
9816 if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
9818 if (SRAIntrinsicsID) {
9819 Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9820 DAG.getConstant(SRAIntrinsicsID, MVT::i32),
9830 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9831 DebugLoc dl = Op.getDebugLoc();
9833 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
9834 // There isn't any reason to disable it if the target processor supports it.
9835 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
9836 SDValue Chain = Op.getOperand(0);
9837 SDValue Zero = DAG.getConstant(0, MVT::i32);
9839 DAG.getRegister(X86::ESP, MVT::i32), // Base
9840 DAG.getTargetConstant(1, MVT::i8), // Scale
9841 DAG.getRegister(0, MVT::i32), // Index
9842 DAG.getTargetConstant(0, MVT::i32), // Disp
9843 DAG.getRegister(0, MVT::i32), // Segment.
9848 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9849 array_lengthof(Ops));
9850 return SDValue(Res, 0);
9853 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9855 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9857 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9858 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9859 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9860 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9862 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9863 if (!Op1 && !Op2 && !Op3 && Op4)
9864 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9866 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9867 if (Op1 && !Op2 && !Op3 && !Op4)
9868 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9870 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9872 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9875 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
9876 SelectionDAG &DAG) const {
9877 DebugLoc dl = Op.getDebugLoc();
9878 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
9879 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
9880 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
9881 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9883 // The only fence that needs an instruction is a sequentially-consistent
9884 // cross-thread fence.
9885 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
9886 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
9887 // no-sse2). There isn't any reason to disable it if the target processor
9889 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
9890 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9892 SDValue Chain = Op.getOperand(0);
9893 SDValue Zero = DAG.getConstant(0, MVT::i32);
9895 DAG.getRegister(X86::ESP, MVT::i32), // Base
9896 DAG.getTargetConstant(1, MVT::i8), // Scale
9897 DAG.getRegister(0, MVT::i32), // Index
9898 DAG.getTargetConstant(0, MVT::i32), // Disp
9899 DAG.getRegister(0, MVT::i32), // Segment.
9904 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9905 array_lengthof(Ops));
9906 return SDValue(Res, 0);
9909 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
9910 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9914 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9915 EVT T = Op.getValueType();
9916 DebugLoc DL = Op.getDebugLoc();
9919 switch(T.getSimpleVT().SimpleTy) {
9921 assert(false && "Invalid value type!");
9922 case MVT::i8: Reg = X86::AL; size = 1; break;
9923 case MVT::i16: Reg = X86::AX; size = 2; break;
9924 case MVT::i32: Reg = X86::EAX; size = 4; break;
9926 assert(Subtarget->is64Bit() && "Node not type legal!");
9927 Reg = X86::RAX; size = 8;
9930 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9931 Op.getOperand(2), SDValue());
9932 SDValue Ops[] = { cpIn.getValue(0),
9935 DAG.getTargetConstant(size, MVT::i8),
9937 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9938 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9939 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9942 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9946 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9947 SelectionDAG &DAG) const {
9948 assert(Subtarget->is64Bit() && "Result not type legalized?");
9949 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9950 SDValue TheChain = Op.getOperand(0);
9951 DebugLoc dl = Op.getDebugLoc();
9952 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9953 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9954 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9956 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9957 DAG.getConstant(32, MVT::i8));
9959 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9962 return DAG.getMergeValues(Ops, 2, dl);
9965 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9966 SelectionDAG &DAG) const {
9967 EVT SrcVT = Op.getOperand(0).getValueType();
9968 EVT DstVT = Op.getValueType();
9969 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9970 Subtarget->hasMMX() && "Unexpected custom BITCAST");
9971 assert((DstVT == MVT::i64 ||
9972 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9973 "Unexpected custom BITCAST");
9974 // i64 <=> MMX conversions are Legal.
9975 if (SrcVT==MVT::i64 && DstVT.isVector())
9977 if (DstVT==MVT::i64 && SrcVT.isVector())
9979 // MMX <=> MMX conversions are Legal.
9980 if (SrcVT.isVector() && DstVT.isVector())
9982 // All other conversions need to be expanded.
9986 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9987 SDNode *Node = Op.getNode();
9988 DebugLoc dl = Node->getDebugLoc();
9989 EVT T = Node->getValueType(0);
9990 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9991 DAG.getConstant(0, T), Node->getOperand(2));
9992 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9993 cast<AtomicSDNode>(Node)->getMemoryVT(),
9994 Node->getOperand(0),
9995 Node->getOperand(1), negOp,
9996 cast<AtomicSDNode>(Node)->getSrcValue(),
9997 cast<AtomicSDNode>(Node)->getAlignment(),
9998 cast<AtomicSDNode>(Node)->getOrdering(),
9999 cast<AtomicSDNode>(Node)->getSynchScope());
10002 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10003 EVT VT = Op.getNode()->getValueType(0);
10005 // Let legalize expand this if it isn't a legal type yet.
10006 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10009 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10012 bool ExtraOp = false;
10013 switch (Op.getOpcode()) {
10014 default: assert(0 && "Invalid code");
10015 case ISD::ADDC: Opc = X86ISD::ADD; break;
10016 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10017 case ISD::SUBC: Opc = X86ISD::SUB; break;
10018 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10022 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10024 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10025 Op.getOperand(1), Op.getOperand(2));
10028 /// LowerOperation - Provide custom lowering hooks for some operations.
10030 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10031 switch (Op.getOpcode()) {
10032 default: llvm_unreachable("Should not custom lower this!");
10033 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10034 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10035 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10036 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10037 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10038 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10039 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10040 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10041 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10042 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10043 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10044 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10045 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10046 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10047 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10048 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10049 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10050 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10051 case ISD::SHL_PARTS:
10052 case ISD::SRA_PARTS:
10053 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
10054 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
10055 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
10056 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
10057 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
10058 case ISD::FABS: return LowerFABS(Op, DAG);
10059 case ISD::FNEG: return LowerFNEG(Op, DAG);
10060 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10061 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
10062 case ISD::SETCC: return LowerSETCC(Op, DAG);
10063 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
10064 case ISD::SELECT: return LowerSELECT(Op, DAG);
10065 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10066 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
10067 case ISD::VASTART: return LowerVASTART(Op, DAG);
10068 case ISD::VAARG: return LowerVAARG(Op, DAG);
10069 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
10070 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10071 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10072 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10073 case ISD::FRAME_TO_ARGS_OFFSET:
10074 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10075 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10076 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
10077 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
10078 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10079 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
10080 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
10081 case ISD::MUL: return LowerMUL(Op, DAG);
10084 case ISD::SHL: return LowerShift(Op, DAG);
10090 case ISD::UMULO: return LowerXALUO(Op, DAG);
10091 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
10092 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
10096 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10097 case ISD::ADD: return LowerADD(Op, DAG);
10098 case ISD::SUB: return LowerSUB(Op, DAG);
10102 void X86TargetLowering::
10103 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10104 SelectionDAG &DAG, unsigned NewOp) const {
10105 EVT T = Node->getValueType(0);
10106 DebugLoc dl = Node->getDebugLoc();
10107 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
10109 SDValue Chain = Node->getOperand(0);
10110 SDValue In1 = Node->getOperand(1);
10111 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10112 Node->getOperand(2), DAG.getIntPtrConstant(0));
10113 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10114 Node->getOperand(2), DAG.getIntPtrConstant(1));
10115 SDValue Ops[] = { Chain, In1, In2L, In2H };
10116 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10118 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10119 cast<MemSDNode>(Node)->getMemOperand());
10120 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10121 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10122 Results.push_back(Result.getValue(2));
10125 /// ReplaceNodeResults - Replace a node with an illegal result type
10126 /// with a new node built out of custom code.
10127 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10128 SmallVectorImpl<SDValue>&Results,
10129 SelectionDAG &DAG) const {
10130 DebugLoc dl = N->getDebugLoc();
10131 switch (N->getOpcode()) {
10133 assert(false && "Do not know how to custom type legalize this operation!");
10135 case ISD::SIGN_EXTEND_INREG:
10140 // We don't want to expand or promote these.
10142 case ISD::FP_TO_SINT: {
10143 std::pair<SDValue,SDValue> Vals =
10144 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10145 SDValue FIST = Vals.first, StackSlot = Vals.second;
10146 if (FIST.getNode() != 0) {
10147 EVT VT = N->getValueType(0);
10148 // Return a load from the stack slot.
10149 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10150 MachinePointerInfo(), false, false, 0));
10154 case ISD::READCYCLECOUNTER: {
10155 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10156 SDValue TheChain = N->getOperand(0);
10157 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10158 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10160 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10162 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10163 SDValue Ops[] = { eax, edx };
10164 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10165 Results.push_back(edx.getValue(1));
10168 case ISD::ATOMIC_CMP_SWAP: {
10169 EVT T = N->getValueType(0);
10170 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
10171 SDValue cpInL, cpInH;
10172 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
10173 DAG.getConstant(0, MVT::i32));
10174 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
10175 DAG.getConstant(1, MVT::i32));
10176 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
10177 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
10178 cpInL.getValue(1));
10179 SDValue swapInL, swapInH;
10180 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
10181 DAG.getConstant(0, MVT::i32));
10182 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
10183 DAG.getConstant(1, MVT::i32));
10184 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
10185 cpInH.getValue(1));
10186 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
10187 swapInL.getValue(1));
10188 SDValue Ops[] = { swapInH.getValue(0),
10190 swapInH.getValue(1) };
10191 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10192 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10193 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
10195 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
10196 MVT::i32, Result.getValue(1));
10197 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
10198 MVT::i32, cpOutL.getValue(2));
10199 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10200 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10201 Results.push_back(cpOutH.getValue(1));
10204 case ISD::ATOMIC_LOAD_ADD:
10205 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10207 case ISD::ATOMIC_LOAD_AND:
10208 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10210 case ISD::ATOMIC_LOAD_NAND:
10211 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10213 case ISD::ATOMIC_LOAD_OR:
10214 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10216 case ISD::ATOMIC_LOAD_SUB:
10217 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10219 case ISD::ATOMIC_LOAD_XOR:
10220 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10222 case ISD::ATOMIC_SWAP:
10223 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10228 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10230 default: return NULL;
10231 case X86ISD::BSF: return "X86ISD::BSF";
10232 case X86ISD::BSR: return "X86ISD::BSR";
10233 case X86ISD::SHLD: return "X86ISD::SHLD";
10234 case X86ISD::SHRD: return "X86ISD::SHRD";
10235 case X86ISD::FAND: return "X86ISD::FAND";
10236 case X86ISD::FOR: return "X86ISD::FOR";
10237 case X86ISD::FXOR: return "X86ISD::FXOR";
10238 case X86ISD::FSRL: return "X86ISD::FSRL";
10239 case X86ISD::FILD: return "X86ISD::FILD";
10240 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
10241 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10242 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10243 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10244 case X86ISD::FLD: return "X86ISD::FLD";
10245 case X86ISD::FST: return "X86ISD::FST";
10246 case X86ISD::CALL: return "X86ISD::CALL";
10247 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
10248 case X86ISD::BT: return "X86ISD::BT";
10249 case X86ISD::CMP: return "X86ISD::CMP";
10250 case X86ISD::COMI: return "X86ISD::COMI";
10251 case X86ISD::UCOMI: return "X86ISD::UCOMI";
10252 case X86ISD::SETCC: return "X86ISD::SETCC";
10253 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
10254 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
10255 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
10256 case X86ISD::CMOV: return "X86ISD::CMOV";
10257 case X86ISD::BRCOND: return "X86ISD::BRCOND";
10258 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
10259 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
10260 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
10261 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
10262 case X86ISD::Wrapper: return "X86ISD::Wrapper";
10263 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
10264 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
10265 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
10266 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
10267 case X86ISD::PINSRB: return "X86ISD::PINSRB";
10268 case X86ISD::PINSRW: return "X86ISD::PINSRW";
10269 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
10270 case X86ISD::ANDNP: return "X86ISD::ANDNP";
10271 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
10272 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
10273 case X86ISD::PSIGND: return "X86ISD::PSIGND";
10274 case X86ISD::PBLENDVB: return "X86ISD::PBLENDVB";
10275 case X86ISD::FMAX: return "X86ISD::FMAX";
10276 case X86ISD::FMIN: return "X86ISD::FMIN";
10277 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
10278 case X86ISD::FRCP: return "X86ISD::FRCP";
10279 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
10280 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
10281 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
10282 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
10283 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
10284 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
10285 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
10286 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
10287 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
10288 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
10289 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
10290 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
10291 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
10292 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
10293 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
10294 case X86ISD::VSHL: return "X86ISD::VSHL";
10295 case X86ISD::VSRL: return "X86ISD::VSRL";
10296 case X86ISD::CMPPD: return "X86ISD::CMPPD";
10297 case X86ISD::CMPPS: return "X86ISD::CMPPS";
10298 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
10299 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
10300 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
10301 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
10302 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
10303 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
10304 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
10305 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
10306 case X86ISD::ADD: return "X86ISD::ADD";
10307 case X86ISD::SUB: return "X86ISD::SUB";
10308 case X86ISD::ADC: return "X86ISD::ADC";
10309 case X86ISD::SBB: return "X86ISD::SBB";
10310 case X86ISD::SMUL: return "X86ISD::SMUL";
10311 case X86ISD::UMUL: return "X86ISD::UMUL";
10312 case X86ISD::INC: return "X86ISD::INC";
10313 case X86ISD::DEC: return "X86ISD::DEC";
10314 case X86ISD::OR: return "X86ISD::OR";
10315 case X86ISD::XOR: return "X86ISD::XOR";
10316 case X86ISD::AND: return "X86ISD::AND";
10317 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
10318 case X86ISD::PTEST: return "X86ISD::PTEST";
10319 case X86ISD::TESTP: return "X86ISD::TESTP";
10320 case X86ISD::PALIGN: return "X86ISD::PALIGN";
10321 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
10322 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
10323 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
10324 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
10325 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
10326 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
10327 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
10328 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
10329 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
10330 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
10331 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
10332 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
10333 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
10334 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
10335 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
10336 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
10337 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
10338 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
10339 case X86ISD::MOVSD: return "X86ISD::MOVSD";
10340 case X86ISD::MOVSS: return "X86ISD::MOVSS";
10341 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
10342 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
10343 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
10344 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
10345 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
10346 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
10347 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
10348 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
10349 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
10350 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
10351 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
10352 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
10353 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
10354 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
10355 case X86ISD::VPERMILPS: return "X86ISD::VPERMILPS";
10356 case X86ISD::VPERMILPSY: return "X86ISD::VPERMILPSY";
10357 case X86ISD::VPERMILPD: return "X86ISD::VPERMILPD";
10358 case X86ISD::VPERMILPDY: return "X86ISD::VPERMILPDY";
10359 case X86ISD::VPERM2F128: return "X86ISD::VPERM2F128";
10360 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10361 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
10362 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
10363 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
10367 // isLegalAddressingMode - Return true if the addressing mode represented
10368 // by AM is legal for this target, for a load/store of the specified type.
10369 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10371 // X86 supports extremely general addressing modes.
10372 CodeModel::Model M = getTargetMachine().getCodeModel();
10373 Reloc::Model R = getTargetMachine().getRelocationModel();
10375 // X86 allows a sign-extended 32-bit immediate field as a displacement.
10376 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10381 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10383 // If a reference to this global requires an extra load, we can't fold it.
10384 if (isGlobalStubReference(GVFlags))
10387 // If BaseGV requires a register for the PIC base, we cannot also have a
10388 // BaseReg specified.
10389 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
10392 // If lower 4G is not available, then we must use rip-relative addressing.
10393 if ((M != CodeModel::Small || R != Reloc::Static) &&
10394 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
10398 switch (AM.Scale) {
10404 // These scales always work.
10409 // These scales are formed with basereg+scalereg. Only accept if there is
10414 default: // Other stuff never works.
10422 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10423 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10425 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10426 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10427 if (NumBits1 <= NumBits2)
10432 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10433 if (!VT1.isInteger() || !VT2.isInteger())
10435 unsigned NumBits1 = VT1.getSizeInBits();
10436 unsigned NumBits2 = VT2.getSizeInBits();
10437 if (NumBits1 <= NumBits2)
10442 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
10443 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10444 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
10447 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
10448 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10449 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
10452 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
10453 // i16 instructions are longer (0x66 prefix) and potentially slower.
10454 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
10457 /// isShuffleMaskLegal - Targets can use this to indicate that they only
10458 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
10459 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
10460 /// are assumed to be legal.
10462 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
10464 // Very little shuffling can be done for 64-bit vectors right now.
10465 if (VT.getSizeInBits() == 64)
10466 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
10468 // FIXME: pshufb, blends, shifts.
10469 return (VT.getVectorNumElements() == 2 ||
10470 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
10471 isMOVLMask(M, VT) ||
10472 isSHUFPMask(M, VT) ||
10473 isPSHUFDMask(M, VT) ||
10474 isPSHUFHWMask(M, VT) ||
10475 isPSHUFLWMask(M, VT) ||
10476 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
10477 isUNPCKLMask(M, VT) ||
10478 isUNPCKHMask(M, VT) ||
10479 isUNPCKL_v_undef_Mask(M, VT) ||
10480 isUNPCKH_v_undef_Mask(M, VT));
10484 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
10486 unsigned NumElts = VT.getVectorNumElements();
10487 // FIXME: This collection of masks seems suspect.
10490 if (NumElts == 4 && VT.getSizeInBits() == 128) {
10491 return (isMOVLMask(Mask, VT) ||
10492 isCommutedMOVLMask(Mask, VT, true) ||
10493 isSHUFPMask(Mask, VT) ||
10494 isCommutedSHUFPMask(Mask, VT));
10499 //===----------------------------------------------------------------------===//
10500 // X86 Scheduler Hooks
10501 //===----------------------------------------------------------------------===//
10503 // private utility function
10504 MachineBasicBlock *
10505 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
10506 MachineBasicBlock *MBB,
10513 TargetRegisterClass *RC,
10514 bool invSrc) const {
10515 // For the atomic bitwise operator, we generate
10518 // ld t1 = [bitinstr.addr]
10519 // op t2 = t1, [bitinstr.val]
10521 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
10523 // fallthrough -->nextMBB
10524 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10525 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10526 MachineFunction::iterator MBBIter = MBB;
10529 /// First build the CFG
10530 MachineFunction *F = MBB->getParent();
10531 MachineBasicBlock *thisMBB = MBB;
10532 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10533 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10534 F->insert(MBBIter, newMBB);
10535 F->insert(MBBIter, nextMBB);
10537 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10538 nextMBB->splice(nextMBB->begin(), thisMBB,
10539 llvm::next(MachineBasicBlock::iterator(bInstr)),
10541 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10543 // Update thisMBB to fall through to newMBB
10544 thisMBB->addSuccessor(newMBB);
10546 // newMBB jumps to itself and fall through to nextMBB
10547 newMBB->addSuccessor(nextMBB);
10548 newMBB->addSuccessor(newMBB);
10550 // Insert instructions into newMBB based on incoming instruction
10551 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10552 "unexpected number of operands");
10553 DebugLoc dl = bInstr->getDebugLoc();
10554 MachineOperand& destOper = bInstr->getOperand(0);
10555 MachineOperand* argOpers[2 + X86::AddrNumOperands];
10556 int numArgs = bInstr->getNumOperands() - 1;
10557 for (int i=0; i < numArgs; ++i)
10558 argOpers[i] = &bInstr->getOperand(i+1);
10560 // x86 address has 4 operands: base, index, scale, and displacement
10561 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10562 int valArgIndx = lastAddrIndx + 1;
10564 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10565 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
10566 for (int i=0; i <= lastAddrIndx; ++i)
10567 (*MIB).addOperand(*argOpers[i]);
10569 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
10571 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
10576 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10577 assert((argOpers[valArgIndx]->isReg() ||
10578 argOpers[valArgIndx]->isImm()) &&
10579 "invalid operand");
10580 if (argOpers[valArgIndx]->isReg())
10581 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
10583 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
10585 (*MIB).addOperand(*argOpers[valArgIndx]);
10587 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
10590 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
10591 for (int i=0; i <= lastAddrIndx; ++i)
10592 (*MIB).addOperand(*argOpers[i]);
10594 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10595 (*MIB).setMemRefs(bInstr->memoperands_begin(),
10596 bInstr->memoperands_end());
10598 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10599 MIB.addReg(EAXreg);
10602 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10604 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
10608 // private utility function: 64 bit atomics on 32 bit host.
10609 MachineBasicBlock *
10610 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
10611 MachineBasicBlock *MBB,
10616 bool invSrc) const {
10617 // For the atomic bitwise operator, we generate
10618 // thisMBB (instructions are in pairs, except cmpxchg8b)
10619 // ld t1,t2 = [bitinstr.addr]
10621 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
10622 // op t5, t6 <- out1, out2, [bitinstr.val]
10623 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
10624 // mov ECX, EBX <- t5, t6
10625 // mov EAX, EDX <- t1, t2
10626 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
10627 // mov t3, t4 <- EAX, EDX
10629 // result in out1, out2
10630 // fallthrough -->nextMBB
10632 const TargetRegisterClass *RC = X86::GR32RegisterClass;
10633 const unsigned LoadOpc = X86::MOV32rm;
10634 const unsigned NotOpc = X86::NOT32r;
10635 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10636 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10637 MachineFunction::iterator MBBIter = MBB;
10640 /// First build the CFG
10641 MachineFunction *F = MBB->getParent();
10642 MachineBasicBlock *thisMBB = MBB;
10643 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10644 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10645 F->insert(MBBIter, newMBB);
10646 F->insert(MBBIter, nextMBB);
10648 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10649 nextMBB->splice(nextMBB->begin(), thisMBB,
10650 llvm::next(MachineBasicBlock::iterator(bInstr)),
10652 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10654 // Update thisMBB to fall through to newMBB
10655 thisMBB->addSuccessor(newMBB);
10657 // newMBB jumps to itself and fall through to nextMBB
10658 newMBB->addSuccessor(nextMBB);
10659 newMBB->addSuccessor(newMBB);
10661 DebugLoc dl = bInstr->getDebugLoc();
10662 // Insert instructions into newMBB based on incoming instruction
10663 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
10664 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
10665 "unexpected number of operands");
10666 MachineOperand& dest1Oper = bInstr->getOperand(0);
10667 MachineOperand& dest2Oper = bInstr->getOperand(1);
10668 MachineOperand* argOpers[2 + X86::AddrNumOperands];
10669 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
10670 argOpers[i] = &bInstr->getOperand(i+2);
10672 // We use some of the operands multiple times, so conservatively just
10673 // clear any kill flags that might be present.
10674 if (argOpers[i]->isReg() && argOpers[i]->isUse())
10675 argOpers[i]->setIsKill(false);
10678 // x86 address has 5 operands: base, index, scale, displacement, and segment.
10679 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10681 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10682 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
10683 for (int i=0; i <= lastAddrIndx; ++i)
10684 (*MIB).addOperand(*argOpers[i]);
10685 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10686 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
10687 // add 4 to displacement.
10688 for (int i=0; i <= lastAddrIndx-2; ++i)
10689 (*MIB).addOperand(*argOpers[i]);
10690 MachineOperand newOp3 = *(argOpers[3]);
10691 if (newOp3.isImm())
10692 newOp3.setImm(newOp3.getImm()+4);
10694 newOp3.setOffset(newOp3.getOffset()+4);
10695 (*MIB).addOperand(newOp3);
10696 (*MIB).addOperand(*argOpers[lastAddrIndx]);
10698 // t3/4 are defined later, at the bottom of the loop
10699 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
10700 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
10701 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
10702 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
10703 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
10704 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
10706 // The subsequent operations should be using the destination registers of
10707 //the PHI instructions.
10709 t1 = F->getRegInfo().createVirtualRegister(RC);
10710 t2 = F->getRegInfo().createVirtualRegister(RC);
10711 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
10712 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
10714 t1 = dest1Oper.getReg();
10715 t2 = dest2Oper.getReg();
10718 int valArgIndx = lastAddrIndx + 1;
10719 assert((argOpers[valArgIndx]->isReg() ||
10720 argOpers[valArgIndx]->isImm()) &&
10721 "invalid operand");
10722 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
10723 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
10724 if (argOpers[valArgIndx]->isReg())
10725 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
10727 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
10728 if (regOpcL != X86::MOV32rr)
10730 (*MIB).addOperand(*argOpers[valArgIndx]);
10731 assert(argOpers[valArgIndx + 1]->isReg() ==
10732 argOpers[valArgIndx]->isReg());
10733 assert(argOpers[valArgIndx + 1]->isImm() ==
10734 argOpers[valArgIndx]->isImm());
10735 if (argOpers[valArgIndx + 1]->isReg())
10736 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
10738 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
10739 if (regOpcH != X86::MOV32rr)
10741 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
10743 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10745 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
10748 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
10750 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
10753 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
10754 for (int i=0; i <= lastAddrIndx; ++i)
10755 (*MIB).addOperand(*argOpers[i]);
10757 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10758 (*MIB).setMemRefs(bInstr->memoperands_begin(),
10759 bInstr->memoperands_end());
10761 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
10762 MIB.addReg(X86::EAX);
10763 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
10764 MIB.addReg(X86::EDX);
10767 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10769 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
10773 // private utility function
10774 MachineBasicBlock *
10775 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
10776 MachineBasicBlock *MBB,
10777 unsigned cmovOpc) const {
10778 // For the atomic min/max operator, we generate
10781 // ld t1 = [min/max.addr]
10782 // mov t2 = [min/max.val]
10784 // cmov[cond] t2 = t1
10786 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
10788 // fallthrough -->nextMBB
10790 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10791 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10792 MachineFunction::iterator MBBIter = MBB;
10795 /// First build the CFG
10796 MachineFunction *F = MBB->getParent();
10797 MachineBasicBlock *thisMBB = MBB;
10798 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10799 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10800 F->insert(MBBIter, newMBB);
10801 F->insert(MBBIter, nextMBB);
10803 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10804 nextMBB->splice(nextMBB->begin(), thisMBB,
10805 llvm::next(MachineBasicBlock::iterator(mInstr)),
10807 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10809 // Update thisMBB to fall through to newMBB
10810 thisMBB->addSuccessor(newMBB);
10812 // newMBB jumps to newMBB and fall through to nextMBB
10813 newMBB->addSuccessor(nextMBB);
10814 newMBB->addSuccessor(newMBB);
10816 DebugLoc dl = mInstr->getDebugLoc();
10817 // Insert instructions into newMBB based on incoming instruction
10818 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10819 "unexpected number of operands");
10820 MachineOperand& destOper = mInstr->getOperand(0);
10821 MachineOperand* argOpers[2 + X86::AddrNumOperands];
10822 int numArgs = mInstr->getNumOperands() - 1;
10823 for (int i=0; i < numArgs; ++i)
10824 argOpers[i] = &mInstr->getOperand(i+1);
10826 // x86 address has 4 operands: base, index, scale, and displacement
10827 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10828 int valArgIndx = lastAddrIndx + 1;
10830 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10831 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10832 for (int i=0; i <= lastAddrIndx; ++i)
10833 (*MIB).addOperand(*argOpers[i]);
10835 // We only support register and immediate values
10836 assert((argOpers[valArgIndx]->isReg() ||
10837 argOpers[valArgIndx]->isImm()) &&
10838 "invalid operand");
10840 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10841 if (argOpers[valArgIndx]->isReg())
10842 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10844 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10845 (*MIB).addOperand(*argOpers[valArgIndx]);
10847 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10850 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10855 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10856 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10860 // Cmp and exchange if none has modified the memory location
10861 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10862 for (int i=0; i <= lastAddrIndx; ++i)
10863 (*MIB).addOperand(*argOpers[i]);
10865 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10866 (*MIB).setMemRefs(mInstr->memoperands_begin(),
10867 mInstr->memoperands_end());
10869 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10870 MIB.addReg(X86::EAX);
10873 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10875 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
10879 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10880 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10881 // in the .td file.
10882 MachineBasicBlock *
10883 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10884 unsigned numArgs, bool memArg) const {
10885 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10886 "Target must have SSE4.2 or AVX features enabled");
10888 DebugLoc dl = MI->getDebugLoc();
10889 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10891 if (!Subtarget->hasAVX()) {
10893 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10895 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10898 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10900 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10903 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10904 for (unsigned i = 0; i < numArgs; ++i) {
10905 MachineOperand &Op = MI->getOperand(i+1);
10906 if (!(Op.isReg() && Op.isImplicit()))
10907 MIB.addOperand(Op);
10909 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10910 .addReg(X86::XMM0);
10912 MI->eraseFromParent();
10916 MachineBasicBlock *
10917 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10918 DebugLoc dl = MI->getDebugLoc();
10919 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10921 // Address into RAX/EAX, other two args into ECX, EDX.
10922 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10923 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10924 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10925 for (int i = 0; i < X86::AddrNumOperands; ++i)
10926 MIB.addOperand(MI->getOperand(i));
10928 unsigned ValOps = X86::AddrNumOperands;
10929 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10930 .addReg(MI->getOperand(ValOps).getReg());
10931 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10932 .addReg(MI->getOperand(ValOps+1).getReg());
10934 // The instruction doesn't actually take any operands though.
10935 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10937 MI->eraseFromParent(); // The pseudo is gone now.
10941 MachineBasicBlock *
10942 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10943 DebugLoc dl = MI->getDebugLoc();
10944 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10946 // First arg in ECX, the second in EAX.
10947 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10948 .addReg(MI->getOperand(0).getReg());
10949 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10950 .addReg(MI->getOperand(1).getReg());
10952 // The instruction doesn't actually take any operands though.
10953 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10955 MI->eraseFromParent(); // The pseudo is gone now.
10959 MachineBasicBlock *
10960 X86TargetLowering::EmitVAARG64WithCustomInserter(
10962 MachineBasicBlock *MBB) const {
10963 // Emit va_arg instruction on X86-64.
10965 // Operands to this pseudo-instruction:
10966 // 0 ) Output : destination address (reg)
10967 // 1-5) Input : va_list address (addr, i64mem)
10968 // 6 ) ArgSize : Size (in bytes) of vararg type
10969 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10970 // 8 ) Align : Alignment of type
10971 // 9 ) EFLAGS (implicit-def)
10973 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10974 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10976 unsigned DestReg = MI->getOperand(0).getReg();
10977 MachineOperand &Base = MI->getOperand(1);
10978 MachineOperand &Scale = MI->getOperand(2);
10979 MachineOperand &Index = MI->getOperand(3);
10980 MachineOperand &Disp = MI->getOperand(4);
10981 MachineOperand &Segment = MI->getOperand(5);
10982 unsigned ArgSize = MI->getOperand(6).getImm();
10983 unsigned ArgMode = MI->getOperand(7).getImm();
10984 unsigned Align = MI->getOperand(8).getImm();
10986 // Memory Reference
10987 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10988 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10989 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10991 // Machine Information
10992 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10993 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10994 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10995 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10996 DebugLoc DL = MI->getDebugLoc();
10998 // struct va_list {
11001 // i64 overflow_area (address)
11002 // i64 reg_save_area (address)
11004 // sizeof(va_list) = 24
11005 // alignment(va_list) = 8
11007 unsigned TotalNumIntRegs = 6;
11008 unsigned TotalNumXMMRegs = 8;
11009 bool UseGPOffset = (ArgMode == 1);
11010 bool UseFPOffset = (ArgMode == 2);
11011 unsigned MaxOffset = TotalNumIntRegs * 8 +
11012 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11014 /* Align ArgSize to a multiple of 8 */
11015 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11016 bool NeedsAlign = (Align > 8);
11018 MachineBasicBlock *thisMBB = MBB;
11019 MachineBasicBlock *overflowMBB;
11020 MachineBasicBlock *offsetMBB;
11021 MachineBasicBlock *endMBB;
11023 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
11024 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
11025 unsigned OffsetReg = 0;
11027 if (!UseGPOffset && !UseFPOffset) {
11028 // If we only pull from the overflow region, we don't create a branch.
11029 // We don't need to alter control flow.
11030 OffsetDestReg = 0; // unused
11031 OverflowDestReg = DestReg;
11034 overflowMBB = thisMBB;
11037 // First emit code to check if gp_offset (or fp_offset) is below the bound.
11038 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11039 // If not, pull from overflow_area. (branch to overflowMBB)
11044 // offsetMBB overflowMBB
11049 // Registers for the PHI in endMBB
11050 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11051 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11053 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11054 MachineFunction *MF = MBB->getParent();
11055 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11056 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11057 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11059 MachineFunction::iterator MBBIter = MBB;
11062 // Insert the new basic blocks
11063 MF->insert(MBBIter, offsetMBB);
11064 MF->insert(MBBIter, overflowMBB);
11065 MF->insert(MBBIter, endMBB);
11067 // Transfer the remainder of MBB and its successor edges to endMBB.
11068 endMBB->splice(endMBB->begin(), thisMBB,
11069 llvm::next(MachineBasicBlock::iterator(MI)),
11071 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11073 // Make offsetMBB and overflowMBB successors of thisMBB
11074 thisMBB->addSuccessor(offsetMBB);
11075 thisMBB->addSuccessor(overflowMBB);
11077 // endMBB is a successor of both offsetMBB and overflowMBB
11078 offsetMBB->addSuccessor(endMBB);
11079 overflowMBB->addSuccessor(endMBB);
11081 // Load the offset value into a register
11082 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11083 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11087 .addDisp(Disp, UseFPOffset ? 4 : 0)
11088 .addOperand(Segment)
11089 .setMemRefs(MMOBegin, MMOEnd);
11091 // Check if there is enough room left to pull this argument.
11092 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11094 .addImm(MaxOffset + 8 - ArgSizeA8);
11096 // Branch to "overflowMBB" if offset >= max
11097 // Fall through to "offsetMBB" otherwise
11098 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11099 .addMBB(overflowMBB);
11102 // In offsetMBB, emit code to use the reg_save_area.
11104 assert(OffsetReg != 0);
11106 // Read the reg_save_area address.
11107 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11108 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11113 .addOperand(Segment)
11114 .setMemRefs(MMOBegin, MMOEnd);
11116 // Zero-extend the offset
11117 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11118 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11121 .addImm(X86::sub_32bit);
11123 // Add the offset to the reg_save_area to get the final address.
11124 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11125 .addReg(OffsetReg64)
11126 .addReg(RegSaveReg);
11128 // Compute the offset for the next argument
11129 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11130 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11132 .addImm(UseFPOffset ? 16 : 8);
11134 // Store it back into the va_list.
11135 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11139 .addDisp(Disp, UseFPOffset ? 4 : 0)
11140 .addOperand(Segment)
11141 .addReg(NextOffsetReg)
11142 .setMemRefs(MMOBegin, MMOEnd);
11145 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11150 // Emit code to use overflow area
11153 // Load the overflow_area address into a register.
11154 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11155 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11160 .addOperand(Segment)
11161 .setMemRefs(MMOBegin, MMOEnd);
11163 // If we need to align it, do so. Otherwise, just copy the address
11164 // to OverflowDestReg.
11166 // Align the overflow address
11167 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11168 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11170 // aligned_addr = (addr + (align-1)) & ~(align-1)
11171 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11172 .addReg(OverflowAddrReg)
11175 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11177 .addImm(~(uint64_t)(Align-1));
11179 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11180 .addReg(OverflowAddrReg);
11183 // Compute the next overflow address after this argument.
11184 // (the overflow address should be kept 8-byte aligned)
11185 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11186 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11187 .addReg(OverflowDestReg)
11188 .addImm(ArgSizeA8);
11190 // Store the new overflow address.
11191 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11196 .addOperand(Segment)
11197 .addReg(NextAddrReg)
11198 .setMemRefs(MMOBegin, MMOEnd);
11200 // If we branched, emit the PHI to the front of endMBB.
11202 BuildMI(*endMBB, endMBB->begin(), DL,
11203 TII->get(X86::PHI), DestReg)
11204 .addReg(OffsetDestReg).addMBB(offsetMBB)
11205 .addReg(OverflowDestReg).addMBB(overflowMBB);
11208 // Erase the pseudo instruction
11209 MI->eraseFromParent();
11214 MachineBasicBlock *
11215 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11217 MachineBasicBlock *MBB) const {
11218 // Emit code to save XMM registers to the stack. The ABI says that the
11219 // number of registers to save is given in %al, so it's theoretically
11220 // possible to do an indirect jump trick to avoid saving all of them,
11221 // however this code takes a simpler approach and just executes all
11222 // of the stores if %al is non-zero. It's less code, and it's probably
11223 // easier on the hardware branch predictor, and stores aren't all that
11224 // expensive anyway.
11226 // Create the new basic blocks. One block contains all the XMM stores,
11227 // and one block is the final destination regardless of whether any
11228 // stores were performed.
11229 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11230 MachineFunction *F = MBB->getParent();
11231 MachineFunction::iterator MBBIter = MBB;
11233 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11234 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11235 F->insert(MBBIter, XMMSaveMBB);
11236 F->insert(MBBIter, EndMBB);
11238 // Transfer the remainder of MBB and its successor edges to EndMBB.
11239 EndMBB->splice(EndMBB->begin(), MBB,
11240 llvm::next(MachineBasicBlock::iterator(MI)),
11242 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11244 // The original block will now fall through to the XMM save block.
11245 MBB->addSuccessor(XMMSaveMBB);
11246 // The XMMSaveMBB will fall through to the end block.
11247 XMMSaveMBB->addSuccessor(EndMBB);
11249 // Now add the instructions.
11250 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11251 DebugLoc DL = MI->getDebugLoc();
11253 unsigned CountReg = MI->getOperand(0).getReg();
11254 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11255 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11257 if (!Subtarget->isTargetWin64()) {
11258 // If %al is 0, branch around the XMM save block.
11259 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11260 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11261 MBB->addSuccessor(EndMBB);
11264 // In the XMM save block, save all the XMM argument registers.
11265 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11266 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11267 MachineMemOperand *MMO =
11268 F->getMachineMemOperand(
11269 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11270 MachineMemOperand::MOStore,
11271 /*Size=*/16, /*Align=*/16);
11272 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
11273 .addFrameIndex(RegSaveFrameIndex)
11274 .addImm(/*Scale=*/1)
11275 .addReg(/*IndexReg=*/0)
11276 .addImm(/*Disp=*/Offset)
11277 .addReg(/*Segment=*/0)
11278 .addReg(MI->getOperand(i).getReg())
11279 .addMemOperand(MMO);
11282 MI->eraseFromParent(); // The pseudo instruction is gone now.
11287 MachineBasicBlock *
11288 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11289 MachineBasicBlock *BB) const {
11290 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11291 DebugLoc DL = MI->getDebugLoc();
11293 // To "insert" a SELECT_CC instruction, we actually have to insert the
11294 // diamond control-flow pattern. The incoming instruction knows the
11295 // destination vreg to set, the condition code register to branch on, the
11296 // true/false values to select between, and a branch opcode to use.
11297 const BasicBlock *LLVM_BB = BB->getBasicBlock();
11298 MachineFunction::iterator It = BB;
11304 // cmpTY ccX, r1, r2
11306 // fallthrough --> copy0MBB
11307 MachineBasicBlock *thisMBB = BB;
11308 MachineFunction *F = BB->getParent();
11309 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11310 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11311 F->insert(It, copy0MBB);
11312 F->insert(It, sinkMBB);
11314 // If the EFLAGS register isn't dead in the terminator, then claim that it's
11315 // live into the sink and copy blocks.
11316 const MachineFunction *MF = BB->getParent();
11317 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
11318 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
11320 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
11321 const MachineOperand &MO = MI->getOperand(I);
11322 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
11323 unsigned Reg = MO.getReg();
11324 if (Reg != X86::EFLAGS) continue;
11325 copy0MBB->addLiveIn(Reg);
11326 sinkMBB->addLiveIn(Reg);
11329 // Transfer the remainder of BB and its successor edges to sinkMBB.
11330 sinkMBB->splice(sinkMBB->begin(), BB,
11331 llvm::next(MachineBasicBlock::iterator(MI)),
11333 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11335 // Add the true and fallthrough blocks as its successors.
11336 BB->addSuccessor(copy0MBB);
11337 BB->addSuccessor(sinkMBB);
11339 // Create the conditional branch instruction.
11341 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11342 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11345 // %FalseValue = ...
11346 // # fallthrough to sinkMBB
11347 copy0MBB->addSuccessor(sinkMBB);
11350 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11352 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11353 TII->get(X86::PHI), MI->getOperand(0).getReg())
11354 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11355 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11357 MI->eraseFromParent(); // The pseudo instruction is gone now.
11361 MachineBasicBlock *
11362 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
11363 MachineBasicBlock *BB) const {
11364 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11365 DebugLoc DL = MI->getDebugLoc();
11367 assert(!Subtarget->isTargetEnvMacho());
11369 // The lowering is pretty easy: we're just emitting the call to _alloca. The
11370 // non-trivial part is impdef of ESP.
11372 if (Subtarget->isTargetWin64()) {
11373 if (Subtarget->isTargetCygMing()) {
11374 // ___chkstk(Mingw64):
11375 // Clobbers R10, R11, RAX and EFLAGS.
11377 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11378 .addExternalSymbol("___chkstk")
11379 .addReg(X86::RAX, RegState::Implicit)
11380 .addReg(X86::RSP, RegState::Implicit)
11381 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
11382 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
11383 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11385 // __chkstk(MSVCRT): does not update stack pointer.
11386 // Clobbers R10, R11 and EFLAGS.
11387 // FIXME: RAX(allocated size) might be reused and not killed.
11388 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11389 .addExternalSymbol("__chkstk")
11390 .addReg(X86::RAX, RegState::Implicit)
11391 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11392 // RAX has the offset to subtracted from RSP.
11393 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
11398 const char *StackProbeSymbol =
11399 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
11401 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
11402 .addExternalSymbol(StackProbeSymbol)
11403 .addReg(X86::EAX, RegState::Implicit)
11404 .addReg(X86::ESP, RegState::Implicit)
11405 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
11406 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
11407 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11410 MI->eraseFromParent(); // The pseudo instruction is gone now.
11414 MachineBasicBlock *
11415 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
11416 MachineBasicBlock *BB) const {
11417 // This is pretty easy. We're taking the value that we received from
11418 // our load from the relocation, sticking it in either RDI (x86-64)
11419 // or EAX and doing an indirect call. The return value will then
11420 // be in the normal return register.
11421 const X86InstrInfo *TII
11422 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
11423 DebugLoc DL = MI->getDebugLoc();
11424 MachineFunction *F = BB->getParent();
11426 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
11427 assert(MI->getOperand(3).isGlobal() && "This should be a global");
11429 if (Subtarget->is64Bit()) {
11430 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11431 TII->get(X86::MOV64rm), X86::RDI)
11433 .addImm(0).addReg(0)
11434 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11435 MI->getOperand(3).getTargetFlags())
11437 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
11438 addDirectMem(MIB, X86::RDI);
11439 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
11440 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11441 TII->get(X86::MOV32rm), X86::EAX)
11443 .addImm(0).addReg(0)
11444 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11445 MI->getOperand(3).getTargetFlags())
11447 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11448 addDirectMem(MIB, X86::EAX);
11450 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11451 TII->get(X86::MOV32rm), X86::EAX)
11452 .addReg(TII->getGlobalBaseReg(F))
11453 .addImm(0).addReg(0)
11454 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11455 MI->getOperand(3).getTargetFlags())
11457 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11458 addDirectMem(MIB, X86::EAX);
11461 MI->eraseFromParent(); // The pseudo instruction is gone now.
11465 MachineBasicBlock *
11466 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
11467 MachineBasicBlock *BB) const {
11468 switch (MI->getOpcode()) {
11469 default: assert(false && "Unexpected instr type to insert");
11470 case X86::TAILJMPd64:
11471 case X86::TAILJMPr64:
11472 case X86::TAILJMPm64:
11473 assert(!"TAILJMP64 would not be touched here.");
11474 case X86::TCRETURNdi64:
11475 case X86::TCRETURNri64:
11476 case X86::TCRETURNmi64:
11477 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
11478 // On AMD64, additional defs should be added before register allocation.
11479 if (!Subtarget->isTargetWin64()) {
11480 MI->addRegisterDefined(X86::RSI);
11481 MI->addRegisterDefined(X86::RDI);
11482 MI->addRegisterDefined(X86::XMM6);
11483 MI->addRegisterDefined(X86::XMM7);
11484 MI->addRegisterDefined(X86::XMM8);
11485 MI->addRegisterDefined(X86::XMM9);
11486 MI->addRegisterDefined(X86::XMM10);
11487 MI->addRegisterDefined(X86::XMM11);
11488 MI->addRegisterDefined(X86::XMM12);
11489 MI->addRegisterDefined(X86::XMM13);
11490 MI->addRegisterDefined(X86::XMM14);
11491 MI->addRegisterDefined(X86::XMM15);
11494 case X86::WIN_ALLOCA:
11495 return EmitLoweredWinAlloca(MI, BB);
11496 case X86::TLSCall_32:
11497 case X86::TLSCall_64:
11498 return EmitLoweredTLSCall(MI, BB);
11499 case X86::CMOV_GR8:
11500 case X86::CMOV_FR32:
11501 case X86::CMOV_FR64:
11502 case X86::CMOV_V4F32:
11503 case X86::CMOV_V2F64:
11504 case X86::CMOV_V2I64:
11505 case X86::CMOV_V8F32:
11506 case X86::CMOV_V4F64:
11507 case X86::CMOV_V4I64:
11508 case X86::CMOV_GR16:
11509 case X86::CMOV_GR32:
11510 case X86::CMOV_RFP32:
11511 case X86::CMOV_RFP64:
11512 case X86::CMOV_RFP80:
11513 return EmitLoweredSelect(MI, BB);
11515 case X86::FP32_TO_INT16_IN_MEM:
11516 case X86::FP32_TO_INT32_IN_MEM:
11517 case X86::FP32_TO_INT64_IN_MEM:
11518 case X86::FP64_TO_INT16_IN_MEM:
11519 case X86::FP64_TO_INT32_IN_MEM:
11520 case X86::FP64_TO_INT64_IN_MEM:
11521 case X86::FP80_TO_INT16_IN_MEM:
11522 case X86::FP80_TO_INT32_IN_MEM:
11523 case X86::FP80_TO_INT64_IN_MEM: {
11524 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11525 DebugLoc DL = MI->getDebugLoc();
11527 // Change the floating point control register to use "round towards zero"
11528 // mode when truncating to an integer value.
11529 MachineFunction *F = BB->getParent();
11530 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
11531 addFrameReference(BuildMI(*BB, MI, DL,
11532 TII->get(X86::FNSTCW16m)), CWFrameIdx);
11534 // Load the old value of the high byte of the control word...
11536 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
11537 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
11540 // Set the high part to be round to zero...
11541 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
11544 // Reload the modified control word now...
11545 addFrameReference(BuildMI(*BB, MI, DL,
11546 TII->get(X86::FLDCW16m)), CWFrameIdx);
11548 // Restore the memory image of control word to original value
11549 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
11552 // Get the X86 opcode to use.
11554 switch (MI->getOpcode()) {
11555 default: llvm_unreachable("illegal opcode!");
11556 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
11557 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
11558 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
11559 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
11560 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
11561 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
11562 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
11563 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
11564 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
11568 MachineOperand &Op = MI->getOperand(0);
11570 AM.BaseType = X86AddressMode::RegBase;
11571 AM.Base.Reg = Op.getReg();
11573 AM.BaseType = X86AddressMode::FrameIndexBase;
11574 AM.Base.FrameIndex = Op.getIndex();
11576 Op = MI->getOperand(1);
11578 AM.Scale = Op.getImm();
11579 Op = MI->getOperand(2);
11581 AM.IndexReg = Op.getImm();
11582 Op = MI->getOperand(3);
11583 if (Op.isGlobal()) {
11584 AM.GV = Op.getGlobal();
11586 AM.Disp = Op.getImm();
11588 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
11589 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
11591 // Reload the original control word now.
11592 addFrameReference(BuildMI(*BB, MI, DL,
11593 TII->get(X86::FLDCW16m)), CWFrameIdx);
11595 MI->eraseFromParent(); // The pseudo instruction is gone now.
11598 // String/text processing lowering.
11599 case X86::PCMPISTRM128REG:
11600 case X86::VPCMPISTRM128REG:
11601 return EmitPCMP(MI, BB, 3, false /* in-mem */);
11602 case X86::PCMPISTRM128MEM:
11603 case X86::VPCMPISTRM128MEM:
11604 return EmitPCMP(MI, BB, 3, true /* in-mem */);
11605 case X86::PCMPESTRM128REG:
11606 case X86::VPCMPESTRM128REG:
11607 return EmitPCMP(MI, BB, 5, false /* in mem */);
11608 case X86::PCMPESTRM128MEM:
11609 case X86::VPCMPESTRM128MEM:
11610 return EmitPCMP(MI, BB, 5, true /* in mem */);
11612 // Thread synchronization.
11614 return EmitMonitor(MI, BB);
11616 return EmitMwait(MI, BB);
11618 // Atomic Lowering.
11619 case X86::ATOMAND32:
11620 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
11621 X86::AND32ri, X86::MOV32rm,
11623 X86::NOT32r, X86::EAX,
11624 X86::GR32RegisterClass);
11625 case X86::ATOMOR32:
11626 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
11627 X86::OR32ri, X86::MOV32rm,
11629 X86::NOT32r, X86::EAX,
11630 X86::GR32RegisterClass);
11631 case X86::ATOMXOR32:
11632 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
11633 X86::XOR32ri, X86::MOV32rm,
11635 X86::NOT32r, X86::EAX,
11636 X86::GR32RegisterClass);
11637 case X86::ATOMNAND32:
11638 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
11639 X86::AND32ri, X86::MOV32rm,
11641 X86::NOT32r, X86::EAX,
11642 X86::GR32RegisterClass, true);
11643 case X86::ATOMMIN32:
11644 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
11645 case X86::ATOMMAX32:
11646 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
11647 case X86::ATOMUMIN32:
11648 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
11649 case X86::ATOMUMAX32:
11650 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
11652 case X86::ATOMAND16:
11653 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
11654 X86::AND16ri, X86::MOV16rm,
11656 X86::NOT16r, X86::AX,
11657 X86::GR16RegisterClass);
11658 case X86::ATOMOR16:
11659 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
11660 X86::OR16ri, X86::MOV16rm,
11662 X86::NOT16r, X86::AX,
11663 X86::GR16RegisterClass);
11664 case X86::ATOMXOR16:
11665 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
11666 X86::XOR16ri, X86::MOV16rm,
11668 X86::NOT16r, X86::AX,
11669 X86::GR16RegisterClass);
11670 case X86::ATOMNAND16:
11671 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
11672 X86::AND16ri, X86::MOV16rm,
11674 X86::NOT16r, X86::AX,
11675 X86::GR16RegisterClass, true);
11676 case X86::ATOMMIN16:
11677 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
11678 case X86::ATOMMAX16:
11679 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
11680 case X86::ATOMUMIN16:
11681 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
11682 case X86::ATOMUMAX16:
11683 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
11685 case X86::ATOMAND8:
11686 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
11687 X86::AND8ri, X86::MOV8rm,
11689 X86::NOT8r, X86::AL,
11690 X86::GR8RegisterClass);
11692 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
11693 X86::OR8ri, X86::MOV8rm,
11695 X86::NOT8r, X86::AL,
11696 X86::GR8RegisterClass);
11697 case X86::ATOMXOR8:
11698 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
11699 X86::XOR8ri, X86::MOV8rm,
11701 X86::NOT8r, X86::AL,
11702 X86::GR8RegisterClass);
11703 case X86::ATOMNAND8:
11704 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
11705 X86::AND8ri, X86::MOV8rm,
11707 X86::NOT8r, X86::AL,
11708 X86::GR8RegisterClass, true);
11709 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
11710 // This group is for 64-bit host.
11711 case X86::ATOMAND64:
11712 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
11713 X86::AND64ri32, X86::MOV64rm,
11715 X86::NOT64r, X86::RAX,
11716 X86::GR64RegisterClass);
11717 case X86::ATOMOR64:
11718 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
11719 X86::OR64ri32, X86::MOV64rm,
11721 X86::NOT64r, X86::RAX,
11722 X86::GR64RegisterClass);
11723 case X86::ATOMXOR64:
11724 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
11725 X86::XOR64ri32, X86::MOV64rm,
11727 X86::NOT64r, X86::RAX,
11728 X86::GR64RegisterClass);
11729 case X86::ATOMNAND64:
11730 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
11731 X86::AND64ri32, X86::MOV64rm,
11733 X86::NOT64r, X86::RAX,
11734 X86::GR64RegisterClass, true);
11735 case X86::ATOMMIN64:
11736 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
11737 case X86::ATOMMAX64:
11738 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
11739 case X86::ATOMUMIN64:
11740 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
11741 case X86::ATOMUMAX64:
11742 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
11744 // This group does 64-bit operations on a 32-bit host.
11745 case X86::ATOMAND6432:
11746 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11747 X86::AND32rr, X86::AND32rr,
11748 X86::AND32ri, X86::AND32ri,
11750 case X86::ATOMOR6432:
11751 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11752 X86::OR32rr, X86::OR32rr,
11753 X86::OR32ri, X86::OR32ri,
11755 case X86::ATOMXOR6432:
11756 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11757 X86::XOR32rr, X86::XOR32rr,
11758 X86::XOR32ri, X86::XOR32ri,
11760 case X86::ATOMNAND6432:
11761 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11762 X86::AND32rr, X86::AND32rr,
11763 X86::AND32ri, X86::AND32ri,
11765 case X86::ATOMADD6432:
11766 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11767 X86::ADD32rr, X86::ADC32rr,
11768 X86::ADD32ri, X86::ADC32ri,
11770 case X86::ATOMSUB6432:
11771 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11772 X86::SUB32rr, X86::SBB32rr,
11773 X86::SUB32ri, X86::SBB32ri,
11775 case X86::ATOMSWAP6432:
11776 return EmitAtomicBit6432WithCustomInserter(MI, BB,
11777 X86::MOV32rr, X86::MOV32rr,
11778 X86::MOV32ri, X86::MOV32ri,
11780 case X86::VASTART_SAVE_XMM_REGS:
11781 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
11783 case X86::VAARG_64:
11784 return EmitVAARG64WithCustomInserter(MI, BB);
11788 //===----------------------------------------------------------------------===//
11789 // X86 Optimization Hooks
11790 //===----------------------------------------------------------------------===//
11792 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
11796 const SelectionDAG &DAG,
11797 unsigned Depth) const {
11798 unsigned Opc = Op.getOpcode();
11799 assert((Opc >= ISD::BUILTIN_OP_END ||
11800 Opc == ISD::INTRINSIC_WO_CHAIN ||
11801 Opc == ISD::INTRINSIC_W_CHAIN ||
11802 Opc == ISD::INTRINSIC_VOID) &&
11803 "Should use MaskedValueIsZero if you don't know whether Op"
11804 " is a target node!");
11806 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
11820 // These nodes' second result is a boolean.
11821 if (Op.getResNo() == 0)
11824 case X86ISD::SETCC:
11825 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11826 Mask.getBitWidth() - 1);
11831 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11832 unsigned Depth) const {
11833 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11834 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11835 return Op.getValueType().getScalarType().getSizeInBits();
11841 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11842 /// node is a GlobalAddress + offset.
11843 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11844 const GlobalValue* &GA,
11845 int64_t &Offset) const {
11846 if (N->getOpcode() == X86ISD::Wrapper) {
11847 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11848 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11849 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11853 return TargetLowering::isGAPlusOffset(N, GA, Offset);
11856 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
11857 /// same as extracting the high 128-bit part of 256-bit vector and then
11858 /// inserting the result into the low part of a new 256-bit vector
11859 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
11860 EVT VT = SVOp->getValueType(0);
11861 int NumElems = VT.getVectorNumElements();
11863 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
11864 for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
11865 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
11866 SVOp->getMaskElt(j) >= 0)
11872 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
11873 /// same as extracting the low 128-bit part of 256-bit vector and then
11874 /// inserting the result into the high part of a new 256-bit vector
11875 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
11876 EVT VT = SVOp->getValueType(0);
11877 int NumElems = VT.getVectorNumElements();
11879 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
11880 for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
11881 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
11882 SVOp->getMaskElt(j) >= 0)
11888 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
11889 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
11890 TargetLowering::DAGCombinerInfo &DCI) {
11891 DebugLoc dl = N->getDebugLoc();
11892 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
11893 SDValue V1 = SVOp->getOperand(0);
11894 SDValue V2 = SVOp->getOperand(1);
11895 EVT VT = SVOp->getValueType(0);
11896 int NumElems = VT.getVectorNumElements();
11898 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
11899 V2.getOpcode() == ISD::CONCAT_VECTORS) {
11903 // V UNDEF BUILD_VECTOR UNDEF
11905 // CONCAT_VECTOR CONCAT_VECTOR
11908 // RESULT: V + zero extended
11910 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
11911 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
11912 V1.getOperand(1).getOpcode() != ISD::UNDEF)
11915 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
11918 // To match the shuffle mask, the first half of the mask should
11919 // be exactly the first vector, and all the rest a splat with the
11920 // first element of the second one.
11921 for (int i = 0; i < NumElems/2; ++i)
11922 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
11923 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
11926 // Emit a zeroed vector and insert the desired subvector on its
11928 SDValue Zeros = getZeroVector(VT, true /* HasSSE2 */, DAG, dl);
11929 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
11930 DAG.getConstant(0, MVT::i32), DAG, dl);
11931 return DCI.CombineTo(N, InsV);
11934 //===--------------------------------------------------------------------===//
11935 // Combine some shuffles into subvector extracts and inserts:
11938 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
11939 if (isShuffleHigh128VectorInsertLow(SVOp)) {
11940 SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
11942 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
11943 V, DAG.getConstant(0, MVT::i32), DAG, dl);
11944 return DCI.CombineTo(N, InsV);
11947 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
11948 if (isShuffleLow128VectorInsertHigh(SVOp)) {
11949 SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
11950 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
11951 V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
11952 return DCI.CombineTo(N, InsV);
11958 /// PerformShuffleCombine - Performs several different shuffle combines.
11959 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11960 TargetLowering::DAGCombinerInfo &DCI,
11961 const X86Subtarget *Subtarget) {
11962 DebugLoc dl = N->getDebugLoc();
11963 EVT VT = N->getValueType(0);
11965 // Don't create instructions with illegal types after legalize types has run.
11966 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11967 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11970 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
11971 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
11972 N->getOpcode() == ISD::VECTOR_SHUFFLE)
11973 return PerformShuffleCombine256(N, DAG, DCI);
11975 // Only handle 128 wide vector from here on.
11976 if (VT.getSizeInBits() != 128)
11979 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
11980 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
11981 // consecutive, non-overlapping, and in the right order.
11982 SmallVector<SDValue, 16> Elts;
11983 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11984 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11986 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11989 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11990 /// generation and convert it from being a bunch of shuffles and extracts
11991 /// to a simple store and scalar loads to extract the elements.
11992 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11993 const TargetLowering &TLI) {
11994 SDValue InputVector = N->getOperand(0);
11996 // Only operate on vectors of 4 elements, where the alternative shuffling
11997 // gets to be more expensive.
11998 if (InputVector.getValueType() != MVT::v4i32)
12001 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12002 // single use which is a sign-extend or zero-extend, and all elements are
12004 SmallVector<SDNode *, 4> Uses;
12005 unsigned ExtractedElements = 0;
12006 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12007 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12008 if (UI.getUse().getResNo() != InputVector.getResNo())
12011 SDNode *Extract = *UI;
12012 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12015 if (Extract->getValueType(0) != MVT::i32)
12017 if (!Extract->hasOneUse())
12019 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12020 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12022 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12025 // Record which element was extracted.
12026 ExtractedElements |=
12027 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12029 Uses.push_back(Extract);
12032 // If not all the elements were used, this may not be worthwhile.
12033 if (ExtractedElements != 15)
12036 // Ok, we've now decided to do the transformation.
12037 DebugLoc dl = InputVector.getDebugLoc();
12039 // Store the value to a temporary stack slot.
12040 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12041 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12042 MachinePointerInfo(), false, false, 0);
12044 // Replace each use (extract) with a load of the appropriate element.
12045 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12046 UE = Uses.end(); UI != UE; ++UI) {
12047 SDNode *Extract = *UI;
12049 // cOMpute the element's address.
12050 SDValue Idx = Extract->getOperand(1);
12052 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12053 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12054 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12056 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12057 StackPtr, OffsetVal);
12059 // Load the scalar.
12060 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12061 ScalarAddr, MachinePointerInfo(),
12064 // Replace the exact with the load.
12065 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12068 // The replacement was made in place; don't return anything.
12072 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
12073 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12074 const X86Subtarget *Subtarget) {
12075 DebugLoc DL = N->getDebugLoc();
12076 SDValue Cond = N->getOperand(0);
12077 // Get the LHS/RHS of the select.
12078 SDValue LHS = N->getOperand(1);
12079 SDValue RHS = N->getOperand(2);
12081 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12082 // instructions match the semantics of the common C idiom x<y?x:y but not
12083 // x<=y?x:y, because of how they handle negative zero (which can be
12084 // ignored in unsafe-math mode).
12085 if (Subtarget->hasSSE2() &&
12086 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
12087 Cond.getOpcode() == ISD::SETCC) {
12088 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12090 unsigned Opcode = 0;
12091 // Check for x CC y ? x : y.
12092 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12093 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12097 // Converting this to a min would handle NaNs incorrectly, and swapping
12098 // the operands would cause it to handle comparisons between positive
12099 // and negative zero incorrectly.
12100 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12101 if (!UnsafeFPMath &&
12102 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12104 std::swap(LHS, RHS);
12106 Opcode = X86ISD::FMIN;
12109 // Converting this to a min would handle comparisons between positive
12110 // and negative zero incorrectly.
12111 if (!UnsafeFPMath &&
12112 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12114 Opcode = X86ISD::FMIN;
12117 // Converting this to a min would handle both negative zeros and NaNs
12118 // incorrectly, but we can swap the operands to fix both.
12119 std::swap(LHS, RHS);
12123 Opcode = X86ISD::FMIN;
12127 // Converting this to a max would handle comparisons between positive
12128 // and negative zero incorrectly.
12129 if (!UnsafeFPMath &&
12130 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12132 Opcode = X86ISD::FMAX;
12135 // Converting this to a max would handle NaNs incorrectly, and swapping
12136 // the operands would cause it to handle comparisons between positive
12137 // and negative zero incorrectly.
12138 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12139 if (!UnsafeFPMath &&
12140 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12142 std::swap(LHS, RHS);
12144 Opcode = X86ISD::FMAX;
12147 // Converting this to a max would handle both negative zeros and NaNs
12148 // incorrectly, but we can swap the operands to fix both.
12149 std::swap(LHS, RHS);
12153 Opcode = X86ISD::FMAX;
12156 // Check for x CC y ? y : x -- a min/max with reversed arms.
12157 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12158 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12162 // Converting this to a min would handle comparisons between positive
12163 // and negative zero incorrectly, and swapping the operands would
12164 // cause it to handle NaNs incorrectly.
12165 if (!UnsafeFPMath &&
12166 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12167 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12169 std::swap(LHS, RHS);
12171 Opcode = X86ISD::FMIN;
12174 // Converting this to a min would handle NaNs incorrectly.
12175 if (!UnsafeFPMath &&
12176 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12178 Opcode = X86ISD::FMIN;
12181 // Converting this to a min would handle both negative zeros and NaNs
12182 // incorrectly, but we can swap the operands to fix both.
12183 std::swap(LHS, RHS);
12187 Opcode = X86ISD::FMIN;
12191 // Converting this to a max would handle NaNs incorrectly.
12192 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12194 Opcode = X86ISD::FMAX;
12197 // Converting this to a max would handle comparisons between positive
12198 // and negative zero incorrectly, and swapping the operands would
12199 // cause it to handle NaNs incorrectly.
12200 if (!UnsafeFPMath &&
12201 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12202 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12204 std::swap(LHS, RHS);
12206 Opcode = X86ISD::FMAX;
12209 // Converting this to a max would handle both negative zeros and NaNs
12210 // incorrectly, but we can swap the operands to fix both.
12211 std::swap(LHS, RHS);
12215 Opcode = X86ISD::FMAX;
12221 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12224 // If this is a select between two integer constants, try to do some
12226 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
12227 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
12228 // Don't do this for crazy integer types.
12229 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
12230 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
12231 // so that TrueC (the true value) is larger than FalseC.
12232 bool NeedsCondInvert = false;
12234 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
12235 // Efficiently invertible.
12236 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
12237 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
12238 isa<ConstantSDNode>(Cond.getOperand(1))))) {
12239 NeedsCondInvert = true;
12240 std::swap(TrueC, FalseC);
12243 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
12244 if (FalseC->getAPIntValue() == 0 &&
12245 TrueC->getAPIntValue().isPowerOf2()) {
12246 if (NeedsCondInvert) // Invert the condition if needed.
12247 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12248 DAG.getConstant(1, Cond.getValueType()));
12250 // Zero extend the condition if needed.
12251 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
12253 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12254 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
12255 DAG.getConstant(ShAmt, MVT::i8));
12258 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
12259 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12260 if (NeedsCondInvert) // Invert the condition if needed.
12261 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12262 DAG.getConstant(1, Cond.getValueType()));
12264 // Zero extend the condition if needed.
12265 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12266 FalseC->getValueType(0), Cond);
12267 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12268 SDValue(FalseC, 0));
12271 // Optimize cases that will turn into an LEA instruction. This requires
12272 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12273 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12274 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12275 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12277 bool isFastMultiplier = false;
12279 switch ((unsigned char)Diff) {
12281 case 1: // result = add base, cond
12282 case 2: // result = lea base( , cond*2)
12283 case 3: // result = lea base(cond, cond*2)
12284 case 4: // result = lea base( , cond*4)
12285 case 5: // result = lea base(cond, cond*4)
12286 case 8: // result = lea base( , cond*8)
12287 case 9: // result = lea base(cond, cond*8)
12288 isFastMultiplier = true;
12293 if (isFastMultiplier) {
12294 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12295 if (NeedsCondInvert) // Invert the condition if needed.
12296 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12297 DAG.getConstant(1, Cond.getValueType()));
12299 // Zero extend the condition if needed.
12300 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12302 // Scale the condition by the difference.
12304 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12305 DAG.getConstant(Diff, Cond.getValueType()));
12307 // Add the base if non-zero.
12308 if (FalseC->getAPIntValue() != 0)
12309 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12310 SDValue(FalseC, 0));
12320 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
12321 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
12322 TargetLowering::DAGCombinerInfo &DCI) {
12323 DebugLoc DL = N->getDebugLoc();
12325 // If the flag operand isn't dead, don't touch this CMOV.
12326 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
12329 SDValue FalseOp = N->getOperand(0);
12330 SDValue TrueOp = N->getOperand(1);
12331 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
12332 SDValue Cond = N->getOperand(3);
12333 if (CC == X86::COND_E || CC == X86::COND_NE) {
12334 switch (Cond.getOpcode()) {
12338 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
12339 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
12340 return (CC == X86::COND_E) ? FalseOp : TrueOp;
12344 // If this is a select between two integer constants, try to do some
12345 // optimizations. Note that the operands are ordered the opposite of SELECT
12347 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
12348 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
12349 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
12350 // larger than FalseC (the false value).
12351 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
12352 CC = X86::GetOppositeBranchCondition(CC);
12353 std::swap(TrueC, FalseC);
12356 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
12357 // This is efficient for any integer data type (including i8/i16) and
12359 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
12360 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12361 DAG.getConstant(CC, MVT::i8), Cond);
12363 // Zero extend the condition if needed.
12364 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
12366 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12367 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
12368 DAG.getConstant(ShAmt, MVT::i8));
12369 if (N->getNumValues() == 2) // Dead flag value?
12370 return DCI.CombineTo(N, Cond, SDValue());
12374 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
12375 // for any integer data type, including i8/i16.
12376 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12377 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12378 DAG.getConstant(CC, MVT::i8), Cond);
12380 // Zero extend the condition if needed.
12381 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12382 FalseC->getValueType(0), Cond);
12383 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12384 SDValue(FalseC, 0));
12386 if (N->getNumValues() == 2) // Dead flag value?
12387 return DCI.CombineTo(N, Cond, SDValue());
12391 // Optimize cases that will turn into an LEA instruction. This requires
12392 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12393 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12394 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12395 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12397 bool isFastMultiplier = false;
12399 switch ((unsigned char)Diff) {
12401 case 1: // result = add base, cond
12402 case 2: // result = lea base( , cond*2)
12403 case 3: // result = lea base(cond, cond*2)
12404 case 4: // result = lea base( , cond*4)
12405 case 5: // result = lea base(cond, cond*4)
12406 case 8: // result = lea base( , cond*8)
12407 case 9: // result = lea base(cond, cond*8)
12408 isFastMultiplier = true;
12413 if (isFastMultiplier) {
12414 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12415 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12416 DAG.getConstant(CC, MVT::i8), Cond);
12417 // Zero extend the condition if needed.
12418 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12420 // Scale the condition by the difference.
12422 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12423 DAG.getConstant(Diff, Cond.getValueType()));
12425 // Add the base if non-zero.
12426 if (FalseC->getAPIntValue() != 0)
12427 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12428 SDValue(FalseC, 0));
12429 if (N->getNumValues() == 2) // Dead flag value?
12430 return DCI.CombineTo(N, Cond, SDValue());
12440 /// PerformMulCombine - Optimize a single multiply with constant into two
12441 /// in order to implement it with two cheaper instructions, e.g.
12442 /// LEA + SHL, LEA + LEA.
12443 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
12444 TargetLowering::DAGCombinerInfo &DCI) {
12445 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12448 EVT VT = N->getValueType(0);
12449 if (VT != MVT::i64)
12452 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12455 uint64_t MulAmt = C->getZExtValue();
12456 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
12459 uint64_t MulAmt1 = 0;
12460 uint64_t MulAmt2 = 0;
12461 if ((MulAmt % 9) == 0) {
12463 MulAmt2 = MulAmt / 9;
12464 } else if ((MulAmt % 5) == 0) {
12466 MulAmt2 = MulAmt / 5;
12467 } else if ((MulAmt % 3) == 0) {
12469 MulAmt2 = MulAmt / 3;
12472 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
12473 DebugLoc DL = N->getDebugLoc();
12475 if (isPowerOf2_64(MulAmt2) &&
12476 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
12477 // If second multiplifer is pow2, issue it first. We want the multiply by
12478 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
12480 std::swap(MulAmt1, MulAmt2);
12483 if (isPowerOf2_64(MulAmt1))
12484 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
12485 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
12487 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
12488 DAG.getConstant(MulAmt1, VT));
12490 if (isPowerOf2_64(MulAmt2))
12491 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
12492 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
12494 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
12495 DAG.getConstant(MulAmt2, VT));
12497 // Do not add new nodes to DAG combiner worklist.
12498 DCI.CombineTo(N, NewMul, false);
12503 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
12504 SDValue N0 = N->getOperand(0);
12505 SDValue N1 = N->getOperand(1);
12506 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
12507 EVT VT = N0.getValueType();
12509 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
12510 // since the result of setcc_c is all zero's or all ones.
12511 if (N1C && N0.getOpcode() == ISD::AND &&
12512 N0.getOperand(1).getOpcode() == ISD::Constant) {
12513 SDValue N00 = N0.getOperand(0);
12514 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
12515 ((N00.getOpcode() == ISD::ANY_EXTEND ||
12516 N00.getOpcode() == ISD::ZERO_EXTEND) &&
12517 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
12518 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
12519 APInt ShAmt = N1C->getAPIntValue();
12520 Mask = Mask.shl(ShAmt);
12522 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
12523 N00, DAG.getConstant(Mask, VT));
12530 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
12532 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
12533 const X86Subtarget *Subtarget) {
12534 EVT VT = N->getValueType(0);
12535 if (!VT.isVector() && VT.isInteger() &&
12536 N->getOpcode() == ISD::SHL)
12537 return PerformSHLCombine(N, DAG);
12539 // On X86 with SSE2 support, we can transform this to a vector shift if
12540 // all elements are shifted by the same amount. We can't do this in legalize
12541 // because the a constant vector is typically transformed to a constant pool
12542 // so we have no knowledge of the shift amount.
12543 if (!(Subtarget->hasSSE2() || Subtarget->hasAVX()))
12546 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
12549 SDValue ShAmtOp = N->getOperand(1);
12550 EVT EltVT = VT.getVectorElementType();
12551 DebugLoc DL = N->getDebugLoc();
12552 SDValue BaseShAmt = SDValue();
12553 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
12554 unsigned NumElts = VT.getVectorNumElements();
12556 for (; i != NumElts; ++i) {
12557 SDValue Arg = ShAmtOp.getOperand(i);
12558 if (Arg.getOpcode() == ISD::UNDEF) continue;
12562 for (; i != NumElts; ++i) {
12563 SDValue Arg = ShAmtOp.getOperand(i);
12564 if (Arg.getOpcode() == ISD::UNDEF) continue;
12565 if (Arg != BaseShAmt) {
12569 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
12570 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
12571 SDValue InVec = ShAmtOp.getOperand(0);
12572 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12573 unsigned NumElts = InVec.getValueType().getVectorNumElements();
12575 for (; i != NumElts; ++i) {
12576 SDValue Arg = InVec.getOperand(i);
12577 if (Arg.getOpcode() == ISD::UNDEF) continue;
12581 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12582 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12583 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
12584 if (C->getZExtValue() == SplatIdx)
12585 BaseShAmt = InVec.getOperand(1);
12588 if (BaseShAmt.getNode() == 0)
12589 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
12590 DAG.getIntPtrConstant(0));
12594 // The shift amount is an i32.
12595 if (EltVT.bitsGT(MVT::i32))
12596 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
12597 else if (EltVT.bitsLT(MVT::i32))
12598 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
12600 // The shift amount is identical so we can do a vector shift.
12601 SDValue ValOp = N->getOperand(0);
12602 switch (N->getOpcode()) {
12604 llvm_unreachable("Unknown shift opcode!");
12607 if (VT == MVT::v2i64)
12608 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12609 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
12611 if (VT == MVT::v4i32)
12612 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12613 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
12615 if (VT == MVT::v8i16)
12616 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12617 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
12621 if (VT == MVT::v4i32)
12622 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12623 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
12625 if (VT == MVT::v8i16)
12626 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12627 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
12631 if (VT == MVT::v2i64)
12632 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12633 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
12635 if (VT == MVT::v4i32)
12636 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12637 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
12639 if (VT == MVT::v8i16)
12640 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12641 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
12649 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
12650 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
12651 // and friends. Likewise for OR -> CMPNEQSS.
12652 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
12653 TargetLowering::DAGCombinerInfo &DCI,
12654 const X86Subtarget *Subtarget) {
12657 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
12658 // we're requiring SSE2 for both.
12659 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
12660 SDValue N0 = N->getOperand(0);
12661 SDValue N1 = N->getOperand(1);
12662 SDValue CMP0 = N0->getOperand(1);
12663 SDValue CMP1 = N1->getOperand(1);
12664 DebugLoc DL = N->getDebugLoc();
12666 // The SETCCs should both refer to the same CMP.
12667 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
12670 SDValue CMP00 = CMP0->getOperand(0);
12671 SDValue CMP01 = CMP0->getOperand(1);
12672 EVT VT = CMP00.getValueType();
12674 if (VT == MVT::f32 || VT == MVT::f64) {
12675 bool ExpectingFlags = false;
12676 // Check for any users that want flags:
12677 for (SDNode::use_iterator UI = N->use_begin(),
12679 !ExpectingFlags && UI != UE; ++UI)
12680 switch (UI->getOpcode()) {
12685 ExpectingFlags = true;
12687 case ISD::CopyToReg:
12688 case ISD::SIGN_EXTEND:
12689 case ISD::ZERO_EXTEND:
12690 case ISD::ANY_EXTEND:
12694 if (!ExpectingFlags) {
12695 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
12696 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
12698 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
12699 X86::CondCode tmp = cc0;
12704 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
12705 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
12706 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
12707 X86ISD::NodeType NTOperator = is64BitFP ?
12708 X86ISD::FSETCCsd : X86ISD::FSETCCss;
12709 // FIXME: need symbolic constants for these magic numbers.
12710 // See X86ATTInstPrinter.cpp:printSSECC().
12711 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
12712 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
12713 DAG.getConstant(x86cc, MVT::i8));
12714 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
12716 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
12717 DAG.getConstant(1, MVT::i32));
12718 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
12719 return OneBitOfTruth;
12727 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
12728 /// so it can be folded inside ANDNP.
12729 static bool CanFoldXORWithAllOnes(const SDNode *N) {
12730 EVT VT = N->getValueType(0);
12732 // Match direct AllOnes for 128 and 256-bit vectors
12733 if (ISD::isBuildVectorAllOnes(N))
12736 // Look through a bit convert.
12737 if (N->getOpcode() == ISD::BITCAST)
12738 N = N->getOperand(0).getNode();
12740 // Sometimes the operand may come from a insert_subvector building a 256-bit
12742 if (VT.getSizeInBits() == 256 &&
12743 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
12744 SDValue V1 = N->getOperand(0);
12745 SDValue V2 = N->getOperand(1);
12747 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
12748 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
12749 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
12750 ISD::isBuildVectorAllOnes(V2.getNode()))
12757 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
12758 TargetLowering::DAGCombinerInfo &DCI,
12759 const X86Subtarget *Subtarget) {
12760 if (DCI.isBeforeLegalizeOps())
12763 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
12767 // Want to form ANDNP nodes:
12768 // 1) In the hopes of then easily combining them with OR and AND nodes
12769 // to form PBLEND/PSIGN.
12770 // 2) To match ANDN packed intrinsics
12771 EVT VT = N->getValueType(0);
12772 if (VT != MVT::v2i64 && VT != MVT::v4i64)
12775 SDValue N0 = N->getOperand(0);
12776 SDValue N1 = N->getOperand(1);
12777 DebugLoc DL = N->getDebugLoc();
12779 // Check LHS for vnot
12780 if (N0.getOpcode() == ISD::XOR &&
12781 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
12782 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
12783 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
12785 // Check RHS for vnot
12786 if (N1.getOpcode() == ISD::XOR &&
12787 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
12788 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
12789 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
12794 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
12795 TargetLowering::DAGCombinerInfo &DCI,
12796 const X86Subtarget *Subtarget) {
12797 if (DCI.isBeforeLegalizeOps())
12800 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
12804 EVT VT = N->getValueType(0);
12805 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
12808 SDValue N0 = N->getOperand(0);
12809 SDValue N1 = N->getOperand(1);
12811 // look for psign/blend
12812 if (Subtarget->hasSSSE3()) {
12813 if (VT == MVT::v2i64) {
12814 // Canonicalize pandn to RHS
12815 if (N0.getOpcode() == X86ISD::ANDNP)
12817 // or (and (m, x), (pandn m, y))
12818 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
12819 SDValue Mask = N1.getOperand(0);
12820 SDValue X = N1.getOperand(1);
12822 if (N0.getOperand(0) == Mask)
12823 Y = N0.getOperand(1);
12824 if (N0.getOperand(1) == Mask)
12825 Y = N0.getOperand(0);
12827 // Check to see if the mask appeared in both the AND and ANDNP and
12831 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
12832 if (Mask.getOpcode() != ISD::BITCAST ||
12833 X.getOpcode() != ISD::BITCAST ||
12834 Y.getOpcode() != ISD::BITCAST)
12837 // Look through mask bitcast.
12838 Mask = Mask.getOperand(0);
12839 EVT MaskVT = Mask.getValueType();
12841 // Validate that the Mask operand is a vector sra node. The sra node
12842 // will be an intrinsic.
12843 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
12846 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
12847 // there is no psrai.b
12848 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
12849 case Intrinsic::x86_sse2_psrai_w:
12850 case Intrinsic::x86_sse2_psrai_d:
12852 default: return SDValue();
12855 // Check that the SRA is all signbits.
12856 SDValue SraC = Mask.getOperand(2);
12857 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
12858 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
12859 if ((SraAmt + 1) != EltBits)
12862 DebugLoc DL = N->getDebugLoc();
12864 // Now we know we at least have a plendvb with the mask val. See if
12865 // we can form a psignb/w/d.
12866 // psign = x.type == y.type == mask.type && y = sub(0, x);
12867 X = X.getOperand(0);
12868 Y = Y.getOperand(0);
12869 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
12870 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
12871 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
12874 case 8: Opc = X86ISD::PSIGNB; break;
12875 case 16: Opc = X86ISD::PSIGNW; break;
12876 case 32: Opc = X86ISD::PSIGND; break;
12880 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
12881 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
12884 // PBLENDVB only available on SSE 4.1
12885 if (!Subtarget->hasSSE41())
12888 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
12889 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
12890 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
12891 Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
12892 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
12897 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
12898 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
12900 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
12902 if (!N0.hasOneUse() || !N1.hasOneUse())
12905 SDValue ShAmt0 = N0.getOperand(1);
12906 if (ShAmt0.getValueType() != MVT::i8)
12908 SDValue ShAmt1 = N1.getOperand(1);
12909 if (ShAmt1.getValueType() != MVT::i8)
12911 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
12912 ShAmt0 = ShAmt0.getOperand(0);
12913 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
12914 ShAmt1 = ShAmt1.getOperand(0);
12916 DebugLoc DL = N->getDebugLoc();
12917 unsigned Opc = X86ISD::SHLD;
12918 SDValue Op0 = N0.getOperand(0);
12919 SDValue Op1 = N1.getOperand(0);
12920 if (ShAmt0.getOpcode() == ISD::SUB) {
12921 Opc = X86ISD::SHRD;
12922 std::swap(Op0, Op1);
12923 std::swap(ShAmt0, ShAmt1);
12926 unsigned Bits = VT.getSizeInBits();
12927 if (ShAmt1.getOpcode() == ISD::SUB) {
12928 SDValue Sum = ShAmt1.getOperand(0);
12929 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
12930 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
12931 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
12932 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
12933 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
12934 return DAG.getNode(Opc, DL, VT,
12936 DAG.getNode(ISD::TRUNCATE, DL,
12939 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
12940 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
12942 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
12943 return DAG.getNode(Opc, DL, VT,
12944 N0.getOperand(0), N1.getOperand(0),
12945 DAG.getNode(ISD::TRUNCATE, DL,
12952 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
12953 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
12954 const X86Subtarget *Subtarget) {
12955 StoreSDNode *St = cast<StoreSDNode>(N);
12956 EVT VT = St->getValue().getValueType();
12957 EVT StVT = St->getMemoryVT();
12958 DebugLoc dl = St->getDebugLoc();
12959 SDValue StoredVal = St->getOperand(1);
12960 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12962 // If we are saving a concatination of two XMM registers, perform two stores.
12963 // This is better in Sandy Bridge cause one 256-bit mem op is done via two
12964 // 128-bit ones. If in the future the cost becomes only one memory access the
12965 // first version would be better.
12966 if (VT.getSizeInBits() == 256 &&
12967 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
12968 StoredVal.getNumOperands() == 2) {
12970 SDValue Value0 = StoredVal.getOperand(0);
12971 SDValue Value1 = StoredVal.getOperand(1);
12973 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
12974 SDValue Ptr0 = St->getBasePtr();
12975 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
12977 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
12978 St->getPointerInfo(), St->isVolatile(),
12979 St->isNonTemporal(), St->getAlignment());
12980 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
12981 St->getPointerInfo(), St->isVolatile(),
12982 St->isNonTemporal(), St->getAlignment());
12983 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
12986 // Optimize trunc store (of multiple scalars) to shuffle and store.
12987 // First, pack all of the elements in one place. Next, store to memory
12988 // in fewer chunks.
12989 if (St->isTruncatingStore() && VT.isVector()) {
12990 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12991 unsigned NumElems = VT.getVectorNumElements();
12992 assert(StVT != VT && "Cannot truncate to the same type");
12993 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
12994 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
12996 // From, To sizes and ElemCount must be pow of two
12997 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
12998 // We are going to use the original vector elt for storing.
12999 // accumulated smaller vector elements must be a multiple of bigger size.
13000 if (0 != (NumElems * ToSz) % FromSz) return SDValue();
13001 unsigned SizeRatio = FromSz / ToSz;
13003 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13005 // Create a type on which we perform the shuffle
13006 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13007 StVT.getScalarType(), NumElems*SizeRatio);
13009 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13011 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13012 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13013 for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13015 // Can't shuffle using an illegal type
13016 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13018 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13019 DAG.getUNDEF(WideVec.getValueType()),
13020 ShuffleVec.data());
13021 // At this point all of the data is stored at the bottom of the
13022 // register. We now need to save it to mem.
13024 // Find the largest store unit
13025 MVT StoreType = MVT::i8;
13026 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13027 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13028 MVT Tp = (MVT::SimpleValueType)tp;
13029 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
13033 // Bitcast the original vector into a vector of store-size units
13034 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13035 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13036 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13037 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
13038 SmallVector<SDValue, 8> Chains;
13039 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
13040 TLI.getPointerTy());
13041 SDValue Ptr = St->getBasePtr();
13043 // Perform one or more big stores into memory.
13044 for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
13045 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
13046 StoreType, ShuffWide,
13047 DAG.getIntPtrConstant(i));
13048 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
13049 St->getPointerInfo(), St->isVolatile(),
13050 St->isNonTemporal(), St->getAlignment());
13051 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13052 Chains.push_back(Ch);
13055 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
13060 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
13061 // the FP state in cases where an emms may be missing.
13062 // A preferable solution to the general problem is to figure out the right
13063 // places to insert EMMS. This qualifies as a quick hack.
13065 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
13066 if (VT.getSizeInBits() != 64)
13069 const Function *F = DAG.getMachineFunction().getFunction();
13070 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
13071 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
13072 && Subtarget->hasSSE2();
13073 if ((VT.isVector() ||
13074 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
13075 isa<LoadSDNode>(St->getValue()) &&
13076 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
13077 St->getChain().hasOneUse() && !St->isVolatile()) {
13078 SDNode* LdVal = St->getValue().getNode();
13079 LoadSDNode *Ld = 0;
13080 int TokenFactorIndex = -1;
13081 SmallVector<SDValue, 8> Ops;
13082 SDNode* ChainVal = St->getChain().getNode();
13083 // Must be a store of a load. We currently handle two cases: the load
13084 // is a direct child, and it's under an intervening TokenFactor. It is
13085 // possible to dig deeper under nested TokenFactors.
13086 if (ChainVal == LdVal)
13087 Ld = cast<LoadSDNode>(St->getChain());
13088 else if (St->getValue().hasOneUse() &&
13089 ChainVal->getOpcode() == ISD::TokenFactor) {
13090 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
13091 if (ChainVal->getOperand(i).getNode() == LdVal) {
13092 TokenFactorIndex = i;
13093 Ld = cast<LoadSDNode>(St->getValue());
13095 Ops.push_back(ChainVal->getOperand(i));
13099 if (!Ld || !ISD::isNormalLoad(Ld))
13102 // If this is not the MMX case, i.e. we are just turning i64 load/store
13103 // into f64 load/store, avoid the transformation if there are multiple
13104 // uses of the loaded value.
13105 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
13108 DebugLoc LdDL = Ld->getDebugLoc();
13109 DebugLoc StDL = N->getDebugLoc();
13110 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
13111 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
13113 if (Subtarget->is64Bit() || F64IsLegal) {
13114 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
13115 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
13116 Ld->getPointerInfo(), Ld->isVolatile(),
13117 Ld->isNonTemporal(), Ld->getAlignment());
13118 SDValue NewChain = NewLd.getValue(1);
13119 if (TokenFactorIndex != -1) {
13120 Ops.push_back(NewChain);
13121 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13124 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
13125 St->getPointerInfo(),
13126 St->isVolatile(), St->isNonTemporal(),
13127 St->getAlignment());
13130 // Otherwise, lower to two pairs of 32-bit loads / stores.
13131 SDValue LoAddr = Ld->getBasePtr();
13132 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
13133 DAG.getConstant(4, MVT::i32));
13135 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
13136 Ld->getPointerInfo(),
13137 Ld->isVolatile(), Ld->isNonTemporal(),
13138 Ld->getAlignment());
13139 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
13140 Ld->getPointerInfo().getWithOffset(4),
13141 Ld->isVolatile(), Ld->isNonTemporal(),
13142 MinAlign(Ld->getAlignment(), 4));
13144 SDValue NewChain = LoLd.getValue(1);
13145 if (TokenFactorIndex != -1) {
13146 Ops.push_back(LoLd);
13147 Ops.push_back(HiLd);
13148 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13152 LoAddr = St->getBasePtr();
13153 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
13154 DAG.getConstant(4, MVT::i32));
13156 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
13157 St->getPointerInfo(),
13158 St->isVolatile(), St->isNonTemporal(),
13159 St->getAlignment());
13160 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
13161 St->getPointerInfo().getWithOffset(4),
13163 St->isNonTemporal(),
13164 MinAlign(St->getAlignment(), 4));
13165 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
13170 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
13171 /// X86ISD::FXOR nodes.
13172 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
13173 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
13174 // F[X]OR(0.0, x) -> x
13175 // F[X]OR(x, 0.0) -> x
13176 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13177 if (C->getValueAPF().isPosZero())
13178 return N->getOperand(1);
13179 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13180 if (C->getValueAPF().isPosZero())
13181 return N->getOperand(0);
13185 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
13186 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
13187 // FAND(0.0, x) -> 0.0
13188 // FAND(x, 0.0) -> 0.0
13189 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13190 if (C->getValueAPF().isPosZero())
13191 return N->getOperand(0);
13192 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13193 if (C->getValueAPF().isPosZero())
13194 return N->getOperand(1);
13198 static SDValue PerformBTCombine(SDNode *N,
13200 TargetLowering::DAGCombinerInfo &DCI) {
13201 // BT ignores high bits in the bit index operand.
13202 SDValue Op1 = N->getOperand(1);
13203 if (Op1.hasOneUse()) {
13204 unsigned BitWidth = Op1.getValueSizeInBits();
13205 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
13206 APInt KnownZero, KnownOne;
13207 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
13208 !DCI.isBeforeLegalizeOps());
13209 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13210 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
13211 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
13212 DCI.CommitTargetLoweringOpt(TLO);
13217 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
13218 SDValue Op = N->getOperand(0);
13219 if (Op.getOpcode() == ISD::BITCAST)
13220 Op = Op.getOperand(0);
13221 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
13222 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
13223 VT.getVectorElementType().getSizeInBits() ==
13224 OpVT.getVectorElementType().getSizeInBits()) {
13225 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
13230 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
13231 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
13232 // (and (i32 x86isd::setcc_carry), 1)
13233 // This eliminates the zext. This transformation is necessary because
13234 // ISD::SETCC is always legalized to i8.
13235 DebugLoc dl = N->getDebugLoc();
13236 SDValue N0 = N->getOperand(0);
13237 EVT VT = N->getValueType(0);
13238 if (N0.getOpcode() == ISD::AND &&
13240 N0.getOperand(0).hasOneUse()) {
13241 SDValue N00 = N0.getOperand(0);
13242 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
13244 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
13245 if (!C || C->getZExtValue() != 1)
13247 return DAG.getNode(ISD::AND, dl, VT,
13248 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
13249 N00.getOperand(0), N00.getOperand(1)),
13250 DAG.getConstant(1, VT));
13256 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
13257 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
13258 unsigned X86CC = N->getConstantOperandVal(0);
13259 SDValue EFLAG = N->getOperand(1);
13260 DebugLoc DL = N->getDebugLoc();
13262 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
13263 // a zext and produces an all-ones bit which is more useful than 0/1 in some
13265 if (X86CC == X86::COND_B)
13266 return DAG.getNode(ISD::AND, DL, MVT::i8,
13267 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
13268 DAG.getConstant(X86CC, MVT::i8), EFLAG),
13269 DAG.getConstant(1, MVT::i8));
13274 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
13275 const X86TargetLowering *XTLI) {
13276 SDValue Op0 = N->getOperand(0);
13277 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
13278 // a 32-bit target where SSE doesn't support i64->FP operations.
13279 if (Op0.getOpcode() == ISD::LOAD) {
13280 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
13281 EVT VT = Ld->getValueType(0);
13282 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
13283 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
13284 !XTLI->getSubtarget()->is64Bit() &&
13285 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13286 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
13287 Ld->getChain(), Op0, DAG);
13288 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
13295 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
13296 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
13297 X86TargetLowering::DAGCombinerInfo &DCI) {
13298 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
13299 // the result is either zero or one (depending on the input carry bit).
13300 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
13301 if (X86::isZeroNode(N->getOperand(0)) &&
13302 X86::isZeroNode(N->getOperand(1)) &&
13303 // We don't have a good way to replace an EFLAGS use, so only do this when
13305 SDValue(N, 1).use_empty()) {
13306 DebugLoc DL = N->getDebugLoc();
13307 EVT VT = N->getValueType(0);
13308 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
13309 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
13310 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
13311 DAG.getConstant(X86::COND_B,MVT::i8),
13313 DAG.getConstant(1, VT));
13314 return DCI.CombineTo(N, Res1, CarryOut);
13320 // fold (add Y, (sete X, 0)) -> adc 0, Y
13321 // (add Y, (setne X, 0)) -> sbb -1, Y
13322 // (sub (sete X, 0), Y) -> sbb 0, Y
13323 // (sub (setne X, 0), Y) -> adc -1, Y
13324 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
13325 DebugLoc DL = N->getDebugLoc();
13327 // Look through ZExts.
13328 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
13329 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
13332 SDValue SetCC = Ext.getOperand(0);
13333 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
13336 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
13337 if (CC != X86::COND_E && CC != X86::COND_NE)
13340 SDValue Cmp = SetCC.getOperand(1);
13341 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
13342 !X86::isZeroNode(Cmp.getOperand(1)) ||
13343 !Cmp.getOperand(0).getValueType().isInteger())
13346 SDValue CmpOp0 = Cmp.getOperand(0);
13347 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
13348 DAG.getConstant(1, CmpOp0.getValueType()));
13350 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
13351 if (CC == X86::COND_NE)
13352 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
13353 DL, OtherVal.getValueType(), OtherVal,
13354 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
13355 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
13356 DL, OtherVal.getValueType(), OtherVal,
13357 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
13360 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
13361 SDValue Op0 = N->getOperand(0);
13362 SDValue Op1 = N->getOperand(1);
13364 // X86 can't encode an immediate LHS of a sub. See if we can push the
13365 // negation into a preceding instruction.
13366 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
13367 // If the RHS of the sub is a XOR with one use and a constant, invert the
13368 // immediate. Then add one to the LHS of the sub so we can turn
13369 // X-Y -> X+~Y+1, saving one register.
13370 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
13371 isa<ConstantSDNode>(Op1.getOperand(1))) {
13372 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
13373 EVT VT = Op0.getValueType();
13374 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
13376 DAG.getConstant(~XorC, VT));
13377 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
13378 DAG.getConstant(C->getAPIntValue()+1, VT));
13382 return OptimizeConditionalInDecrement(N, DAG);
13385 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
13386 DAGCombinerInfo &DCI) const {
13387 SelectionDAG &DAG = DCI.DAG;
13388 switch (N->getOpcode()) {
13390 case ISD::EXTRACT_VECTOR_ELT:
13391 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
13392 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
13393 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
13394 case ISD::ADD: return OptimizeConditionalInDecrement(N, DAG);
13395 case ISD::SUB: return PerformSubCombine(N, DAG);
13396 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
13397 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
13400 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
13401 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
13402 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
13403 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
13404 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
13406 case X86ISD::FOR: return PerformFORCombine(N, DAG);
13407 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
13408 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
13409 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
13410 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
13411 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
13412 case X86ISD::SHUFPS: // Handle all target specific shuffles
13413 case X86ISD::SHUFPD:
13414 case X86ISD::PALIGN:
13415 case X86ISD::PUNPCKHBW:
13416 case X86ISD::PUNPCKHWD:
13417 case X86ISD::PUNPCKHDQ:
13418 case X86ISD::PUNPCKHQDQ:
13419 case X86ISD::UNPCKHPS:
13420 case X86ISD::UNPCKHPD:
13421 case X86ISD::VUNPCKHPSY:
13422 case X86ISD::VUNPCKHPDY:
13423 case X86ISD::PUNPCKLBW:
13424 case X86ISD::PUNPCKLWD:
13425 case X86ISD::PUNPCKLDQ:
13426 case X86ISD::PUNPCKLQDQ:
13427 case X86ISD::UNPCKLPS:
13428 case X86ISD::UNPCKLPD:
13429 case X86ISD::VUNPCKLPSY:
13430 case X86ISD::VUNPCKLPDY:
13431 case X86ISD::MOVHLPS:
13432 case X86ISD::MOVLHPS:
13433 case X86ISD::PSHUFD:
13434 case X86ISD::PSHUFHW:
13435 case X86ISD::PSHUFLW:
13436 case X86ISD::MOVSS:
13437 case X86ISD::MOVSD:
13438 case X86ISD::VPERMILPS:
13439 case X86ISD::VPERMILPSY:
13440 case X86ISD::VPERMILPD:
13441 case X86ISD::VPERMILPDY:
13442 case X86ISD::VPERM2F128:
13443 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
13449 /// isTypeDesirableForOp - Return true if the target has native support for
13450 /// the specified value type and it is 'desirable' to use the type for the
13451 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
13452 /// instruction encodings are longer and some i16 instructions are slow.
13453 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
13454 if (!isTypeLegal(VT))
13456 if (VT != MVT::i16)
13463 case ISD::SIGN_EXTEND:
13464 case ISD::ZERO_EXTEND:
13465 case ISD::ANY_EXTEND:
13478 /// IsDesirableToPromoteOp - This method query the target whether it is
13479 /// beneficial for dag combiner to promote the specified node. If true, it
13480 /// should return the desired promotion type by reference.
13481 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
13482 EVT VT = Op.getValueType();
13483 if (VT != MVT::i16)
13486 bool Promote = false;
13487 bool Commute = false;
13488 switch (Op.getOpcode()) {
13491 LoadSDNode *LD = cast<LoadSDNode>(Op);
13492 // If the non-extending load has a single use and it's not live out, then it
13493 // might be folded.
13494 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
13495 Op.hasOneUse()*/) {
13496 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13497 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
13498 // The only case where we'd want to promote LOAD (rather then it being
13499 // promoted as an operand is when it's only use is liveout.
13500 if (UI->getOpcode() != ISD::CopyToReg)
13507 case ISD::SIGN_EXTEND:
13508 case ISD::ZERO_EXTEND:
13509 case ISD::ANY_EXTEND:
13514 SDValue N0 = Op.getOperand(0);
13515 // Look out for (store (shl (load), x)).
13516 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
13529 SDValue N0 = Op.getOperand(0);
13530 SDValue N1 = Op.getOperand(1);
13531 if (!Commute && MayFoldLoad(N1))
13533 // Avoid disabling potential load folding opportunities.
13534 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
13536 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
13546 //===----------------------------------------------------------------------===//
13547 // X86 Inline Assembly Support
13548 //===----------------------------------------------------------------------===//
13550 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
13551 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
13553 std::string AsmStr = IA->getAsmString();
13555 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
13556 SmallVector<StringRef, 4> AsmPieces;
13557 SplitString(AsmStr, AsmPieces, ";\n");
13559 switch (AsmPieces.size()) {
13560 default: return false;
13562 AsmStr = AsmPieces[0];
13564 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
13566 // FIXME: this should verify that we are targeting a 486 or better. If not,
13567 // we will turn this bswap into something that will be lowered to logical ops
13568 // instead of emitting the bswap asm. For now, we don't support 486 or lower
13569 // so don't worry about this.
13571 if (AsmPieces.size() == 2 &&
13572 (AsmPieces[0] == "bswap" ||
13573 AsmPieces[0] == "bswapq" ||
13574 AsmPieces[0] == "bswapl") &&
13575 (AsmPieces[1] == "$0" ||
13576 AsmPieces[1] == "${0:q}")) {
13577 // No need to check constraints, nothing other than the equivalent of
13578 // "=r,0" would be valid here.
13579 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13580 if (!Ty || Ty->getBitWidth() % 16 != 0)
13582 return IntrinsicLowering::LowerToByteSwap(CI);
13584 // rorw $$8, ${0:w} --> llvm.bswap.i16
13585 if (CI->getType()->isIntegerTy(16) &&
13586 AsmPieces.size() == 3 &&
13587 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
13588 AsmPieces[1] == "$$8," &&
13589 AsmPieces[2] == "${0:w}" &&
13590 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
13592 const std::string &ConstraintsStr = IA->getConstraintString();
13593 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
13594 std::sort(AsmPieces.begin(), AsmPieces.end());
13595 if (AsmPieces.size() == 4 &&
13596 AsmPieces[0] == "~{cc}" &&
13597 AsmPieces[1] == "~{dirflag}" &&
13598 AsmPieces[2] == "~{flags}" &&
13599 AsmPieces[3] == "~{fpsr}") {
13600 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13601 if (!Ty || Ty->getBitWidth() % 16 != 0)
13603 return IntrinsicLowering::LowerToByteSwap(CI);
13608 if (CI->getType()->isIntegerTy(32) &&
13609 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
13610 SmallVector<StringRef, 4> Words;
13611 SplitString(AsmPieces[0], Words, " \t,");
13612 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
13613 Words[2] == "${0:w}") {
13615 SplitString(AsmPieces[1], Words, " \t,");
13616 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
13617 Words[2] == "$0") {
13619 SplitString(AsmPieces[2], Words, " \t,");
13620 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
13621 Words[2] == "${0:w}") {
13623 const std::string &ConstraintsStr = IA->getConstraintString();
13624 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
13625 std::sort(AsmPieces.begin(), AsmPieces.end());
13626 if (AsmPieces.size() == 4 &&
13627 AsmPieces[0] == "~{cc}" &&
13628 AsmPieces[1] == "~{dirflag}" &&
13629 AsmPieces[2] == "~{flags}" &&
13630 AsmPieces[3] == "~{fpsr}") {
13631 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13632 if (!Ty || Ty->getBitWidth() % 16 != 0)
13634 return IntrinsicLowering::LowerToByteSwap(CI);
13641 if (CI->getType()->isIntegerTy(64)) {
13642 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
13643 if (Constraints.size() >= 2 &&
13644 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
13645 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
13646 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
13647 SmallVector<StringRef, 4> Words;
13648 SplitString(AsmPieces[0], Words, " \t");
13649 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
13651 SplitString(AsmPieces[1], Words, " \t");
13652 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
13654 SplitString(AsmPieces[2], Words, " \t,");
13655 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
13656 Words[2] == "%edx") {
13657 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13658 if (!Ty || Ty->getBitWidth() % 16 != 0)
13660 return IntrinsicLowering::LowerToByteSwap(CI);
13673 /// getConstraintType - Given a constraint letter, return the type of
13674 /// constraint it is for this target.
13675 X86TargetLowering::ConstraintType
13676 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
13677 if (Constraint.size() == 1) {
13678 switch (Constraint[0]) {
13689 return C_RegisterClass;
13713 return TargetLowering::getConstraintType(Constraint);
13716 /// Examine constraint type and operand type and determine a weight value.
13717 /// This object must already have been set up with the operand type
13718 /// and the current alternative constraint selected.
13719 TargetLowering::ConstraintWeight
13720 X86TargetLowering::getSingleConstraintMatchWeight(
13721 AsmOperandInfo &info, const char *constraint) const {
13722 ConstraintWeight weight = CW_Invalid;
13723 Value *CallOperandVal = info.CallOperandVal;
13724 // If we don't have a value, we can't do a match,
13725 // but allow it at the lowest weight.
13726 if (CallOperandVal == NULL)
13728 Type *type = CallOperandVal->getType();
13729 // Look at the constraint type.
13730 switch (*constraint) {
13732 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13743 if (CallOperandVal->getType()->isIntegerTy())
13744 weight = CW_SpecificReg;
13749 if (type->isFloatingPointTy())
13750 weight = CW_SpecificReg;
13753 if (type->isX86_MMXTy() && Subtarget->hasMMX())
13754 weight = CW_SpecificReg;
13758 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
13759 weight = CW_Register;
13762 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
13763 if (C->getZExtValue() <= 31)
13764 weight = CW_Constant;
13768 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13769 if (C->getZExtValue() <= 63)
13770 weight = CW_Constant;
13774 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13775 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
13776 weight = CW_Constant;
13780 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13781 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
13782 weight = CW_Constant;
13786 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13787 if (C->getZExtValue() <= 3)
13788 weight = CW_Constant;
13792 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13793 if (C->getZExtValue() <= 0xff)
13794 weight = CW_Constant;
13799 if (dyn_cast<ConstantFP>(CallOperandVal)) {
13800 weight = CW_Constant;
13804 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13805 if ((C->getSExtValue() >= -0x80000000LL) &&
13806 (C->getSExtValue() <= 0x7fffffffLL))
13807 weight = CW_Constant;
13811 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13812 if (C->getZExtValue() <= 0xffffffff)
13813 weight = CW_Constant;
13820 /// LowerXConstraint - try to replace an X constraint, which matches anything,
13821 /// with another that has more specific requirements based on the type of the
13822 /// corresponding operand.
13823 const char *X86TargetLowering::
13824 LowerXConstraint(EVT ConstraintVT) const {
13825 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
13826 // 'f' like normal targets.
13827 if (ConstraintVT.isFloatingPoint()) {
13828 if (Subtarget->hasXMMInt())
13830 if (Subtarget->hasXMM())
13834 return TargetLowering::LowerXConstraint(ConstraintVT);
13837 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13838 /// vector. If it is invalid, don't add anything to Ops.
13839 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13840 std::string &Constraint,
13841 std::vector<SDValue>&Ops,
13842 SelectionDAG &DAG) const {
13843 SDValue Result(0, 0);
13845 // Only support length 1 constraints for now.
13846 if (Constraint.length() > 1) return;
13848 char ConstraintLetter = Constraint[0];
13849 switch (ConstraintLetter) {
13852 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13853 if (C->getZExtValue() <= 31) {
13854 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13860 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13861 if (C->getZExtValue() <= 63) {
13862 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13868 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13869 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
13870 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13876 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13877 if (C->getZExtValue() <= 255) {
13878 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13884 // 32-bit signed value
13885 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13886 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
13887 C->getSExtValue())) {
13888 // Widen to 64 bits here to get it sign extended.
13889 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
13892 // FIXME gcc accepts some relocatable values here too, but only in certain
13893 // memory models; it's complicated.
13898 // 32-bit unsigned value
13899 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13900 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
13901 C->getZExtValue())) {
13902 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13906 // FIXME gcc accepts some relocatable values here too, but only in certain
13907 // memory models; it's complicated.
13911 // Literal immediates are always ok.
13912 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
13913 // Widen to 64 bits here to get it sign extended.
13914 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
13918 // In any sort of PIC mode addresses need to be computed at runtime by
13919 // adding in a register or some sort of table lookup. These can't
13920 // be used as immediates.
13921 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
13924 // If we are in non-pic codegen mode, we allow the address of a global (with
13925 // an optional displacement) to be used with 'i'.
13926 GlobalAddressSDNode *GA = 0;
13927 int64_t Offset = 0;
13929 // Match either (GA), (GA+C), (GA+C1+C2), etc.
13931 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
13932 Offset += GA->getOffset();
13934 } else if (Op.getOpcode() == ISD::ADD) {
13935 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
13936 Offset += C->getZExtValue();
13937 Op = Op.getOperand(0);
13940 } else if (Op.getOpcode() == ISD::SUB) {
13941 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
13942 Offset += -C->getZExtValue();
13943 Op = Op.getOperand(0);
13948 // Otherwise, this isn't something we can handle, reject it.
13952 const GlobalValue *GV = GA->getGlobal();
13953 // If we require an extra load to get this address, as in PIC mode, we
13954 // can't accept it.
13955 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
13956 getTargetMachine())))
13959 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
13960 GA->getValueType(0), Offset);
13965 if (Result.getNode()) {
13966 Ops.push_back(Result);
13969 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13972 std::pair<unsigned, const TargetRegisterClass*>
13973 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
13975 // First, see if this is a constraint that directly corresponds to an LLVM
13977 if (Constraint.size() == 1) {
13978 // GCC Constraint Letters
13979 switch (Constraint[0]) {
13981 // TODO: Slight differences here in allocation order and leaving
13982 // RIP in the class. Do they matter any more here than they do
13983 // in the normal allocation?
13984 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
13985 if (Subtarget->is64Bit()) {
13986 if (VT == MVT::i32 || VT == MVT::f32)
13987 return std::make_pair(0U, X86::GR32RegisterClass);
13988 else if (VT == MVT::i16)
13989 return std::make_pair(0U, X86::GR16RegisterClass);
13990 else if (VT == MVT::i8 || VT == MVT::i1)
13991 return std::make_pair(0U, X86::GR8RegisterClass);
13992 else if (VT == MVT::i64 || VT == MVT::f64)
13993 return std::make_pair(0U, X86::GR64RegisterClass);
13996 // 32-bit fallthrough
13997 case 'Q': // Q_REGS
13998 if (VT == MVT::i32 || VT == MVT::f32)
13999 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
14000 else if (VT == MVT::i16)
14001 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
14002 else if (VT == MVT::i8 || VT == MVT::i1)
14003 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
14004 else if (VT == MVT::i64)
14005 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
14007 case 'r': // GENERAL_REGS
14008 case 'l': // INDEX_REGS
14009 if (VT == MVT::i8 || VT == MVT::i1)
14010 return std::make_pair(0U, X86::GR8RegisterClass);
14011 if (VT == MVT::i16)
14012 return std::make_pair(0U, X86::GR16RegisterClass);
14013 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
14014 return std::make_pair(0U, X86::GR32RegisterClass);
14015 return std::make_pair(0U, X86::GR64RegisterClass);
14016 case 'R': // LEGACY_REGS
14017 if (VT == MVT::i8 || VT == MVT::i1)
14018 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
14019 if (VT == MVT::i16)
14020 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
14021 if (VT == MVT::i32 || !Subtarget->is64Bit())
14022 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
14023 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
14024 case 'f': // FP Stack registers.
14025 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
14026 // value to the correct fpstack register class.
14027 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
14028 return std::make_pair(0U, X86::RFP32RegisterClass);
14029 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
14030 return std::make_pair(0U, X86::RFP64RegisterClass);
14031 return std::make_pair(0U, X86::RFP80RegisterClass);
14032 case 'y': // MMX_REGS if MMX allowed.
14033 if (!Subtarget->hasMMX()) break;
14034 return std::make_pair(0U, X86::VR64RegisterClass);
14035 case 'Y': // SSE_REGS if SSE2 allowed
14036 if (!Subtarget->hasXMMInt()) break;
14038 case 'x': // SSE_REGS if SSE1 allowed
14039 if (!Subtarget->hasXMM()) break;
14041 switch (VT.getSimpleVT().SimpleTy) {
14043 // Scalar SSE types.
14046 return std::make_pair(0U, X86::FR32RegisterClass);
14049 return std::make_pair(0U, X86::FR64RegisterClass);
14057 return std::make_pair(0U, X86::VR128RegisterClass);
14063 // Use the default implementation in TargetLowering to convert the register
14064 // constraint into a member of a register class.
14065 std::pair<unsigned, const TargetRegisterClass*> Res;
14066 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
14068 // Not found as a standard register?
14069 if (Res.second == 0) {
14070 // Map st(0) -> st(7) -> ST0
14071 if (Constraint.size() == 7 && Constraint[0] == '{' &&
14072 tolower(Constraint[1]) == 's' &&
14073 tolower(Constraint[2]) == 't' &&
14074 Constraint[3] == '(' &&
14075 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
14076 Constraint[5] == ')' &&
14077 Constraint[6] == '}') {
14079 Res.first = X86::ST0+Constraint[4]-'0';
14080 Res.second = X86::RFP80RegisterClass;
14084 // GCC allows "st(0)" to be called just plain "st".
14085 if (StringRef("{st}").equals_lower(Constraint)) {
14086 Res.first = X86::ST0;
14087 Res.second = X86::RFP80RegisterClass;
14092 if (StringRef("{flags}").equals_lower(Constraint)) {
14093 Res.first = X86::EFLAGS;
14094 Res.second = X86::CCRRegisterClass;
14098 // 'A' means EAX + EDX.
14099 if (Constraint == "A") {
14100 Res.first = X86::EAX;
14101 Res.second = X86::GR32_ADRegisterClass;
14107 // Otherwise, check to see if this is a register class of the wrong value
14108 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
14109 // turn into {ax},{dx}.
14110 if (Res.second->hasType(VT))
14111 return Res; // Correct type already, nothing to do.
14113 // All of the single-register GCC register classes map their values onto
14114 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
14115 // really want an 8-bit or 32-bit register, map to the appropriate register
14116 // class and return the appropriate register.
14117 if (Res.second == X86::GR16RegisterClass) {
14118 if (VT == MVT::i8) {
14119 unsigned DestReg = 0;
14120 switch (Res.first) {
14122 case X86::AX: DestReg = X86::AL; break;
14123 case X86::DX: DestReg = X86::DL; break;
14124 case X86::CX: DestReg = X86::CL; break;
14125 case X86::BX: DestReg = X86::BL; break;
14128 Res.first = DestReg;
14129 Res.second = X86::GR8RegisterClass;
14131 } else if (VT == MVT::i32) {
14132 unsigned DestReg = 0;
14133 switch (Res.first) {
14135 case X86::AX: DestReg = X86::EAX; break;
14136 case X86::DX: DestReg = X86::EDX; break;
14137 case X86::CX: DestReg = X86::ECX; break;
14138 case X86::BX: DestReg = X86::EBX; break;
14139 case X86::SI: DestReg = X86::ESI; break;
14140 case X86::DI: DestReg = X86::EDI; break;
14141 case X86::BP: DestReg = X86::EBP; break;
14142 case X86::SP: DestReg = X86::ESP; break;
14145 Res.first = DestReg;
14146 Res.second = X86::GR32RegisterClass;
14148 } else if (VT == MVT::i64) {
14149 unsigned DestReg = 0;
14150 switch (Res.first) {
14152 case X86::AX: DestReg = X86::RAX; break;
14153 case X86::DX: DestReg = X86::RDX; break;
14154 case X86::CX: DestReg = X86::RCX; break;
14155 case X86::BX: DestReg = X86::RBX; break;
14156 case X86::SI: DestReg = X86::RSI; break;
14157 case X86::DI: DestReg = X86::RDI; break;
14158 case X86::BP: DestReg = X86::RBP; break;
14159 case X86::SP: DestReg = X86::RSP; break;
14162 Res.first = DestReg;
14163 Res.second = X86::GR64RegisterClass;
14166 } else if (Res.second == X86::FR32RegisterClass ||
14167 Res.second == X86::FR64RegisterClass ||
14168 Res.second == X86::VR128RegisterClass) {
14169 // Handle references to XMM physical registers that got mapped into the
14170 // wrong class. This can happen with constraints like {xmm0} where the
14171 // target independent register mapper will just pick the first match it can
14172 // find, ignoring the required type.
14173 if (VT == MVT::f32)
14174 Res.second = X86::FR32RegisterClass;
14175 else if (VT == MVT::f64)
14176 Res.second = X86::FR64RegisterClass;
14177 else if (X86::VR128RegisterClass->hasType(VT))
14178 Res.second = X86::VR128RegisterClass;