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/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.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();
172 X86ScalarSSEf32 = Subtarget->hasXMM();
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);
183 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
184 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
186 // For 64-bit since we have so many registers use the ILP scheduler, for
187 // 32-bit code use the register pressure specific scheduling.
188 if (Subtarget->is64Bit())
189 setSchedulingPreference(Sched::ILP);
191 setSchedulingPreference(Sched::RegPressure);
192 setStackPointerRegisterToSaveRestore(X86StackPtr);
194 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
195 // Setup Windows compiler runtime calls.
196 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
197 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
198 setLibcallName(RTLIB::SREM_I64, "_allrem");
199 setLibcallName(RTLIB::UREM_I64, "_aullrem");
200 setLibcallName(RTLIB::MUL_I64, "_allmul");
201 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
202 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
203 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
204 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
205 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
206 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
207 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
208 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
209 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
212 if (Subtarget->isTargetDarwin()) {
213 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
214 setUseUnderscoreSetJmp(false);
215 setUseUnderscoreLongJmp(false);
216 } else if (Subtarget->isTargetMingw()) {
217 // MS runtime is weird: it exports _setjmp, but longjmp!
218 setUseUnderscoreSetJmp(true);
219 setUseUnderscoreLongJmp(false);
221 setUseUnderscoreSetJmp(true);
222 setUseUnderscoreLongJmp(true);
225 // Set up the register classes.
226 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
227 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
228 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
229 if (Subtarget->is64Bit())
230 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
232 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
234 // We don't accept any truncstore of integer registers.
235 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
236 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
237 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
238 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
239 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
240 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
242 // SETOEQ and SETUNE require checking two conditions.
243 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
244 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
245 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
246 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
247 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
248 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
250 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
252 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
253 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
254 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
256 if (Subtarget->is64Bit()) {
257 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
258 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
259 } else if (!UseSoftFloat) {
260 // We have an algorithm for SSE2->double, and we turn this into a
261 // 64-bit FILD followed by conditional FADD for other targets.
262 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
263 // We have an algorithm for SSE2, and we turn this into a 64-bit
264 // FILD for other targets.
265 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
268 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
270 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
271 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
274 // SSE has no i16 to fp conversion, only i32
275 if (X86ScalarSSEf32) {
276 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
277 // f32 and f64 cases are Legal, f80 case is not
278 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
280 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
281 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
284 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
285 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
288 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
289 // are Legal, f80 is custom lowered.
290 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
291 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
293 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
295 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
296 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
298 if (X86ScalarSSEf32) {
299 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
300 // f32 and f64 cases are Legal, f80 case is not
301 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
303 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
304 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
307 // Handle FP_TO_UINT by promoting the destination to a larger signed
309 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
310 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
311 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
313 if (Subtarget->is64Bit()) {
314 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
315 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
316 } else if (!UseSoftFloat) {
317 // Since AVX is a superset of SSE3, only check for SSE here.
318 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
319 // Expand FP_TO_UINT into a select.
320 // FIXME: We would like to use a Custom expander here eventually to do
321 // the optimal thing for SSE vs. the default expansion in the legalizer.
322 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
324 // With SSE3 we can use fisttpll to convert to a signed i64; without
325 // SSE, we're stuck with a fistpll.
326 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
329 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
330 if (!X86ScalarSSEf64) {
331 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
332 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
333 if (Subtarget->is64Bit()) {
334 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
335 // Without SSE, i64->f64 goes through memory.
336 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
340 // Scalar integer divide and remainder are lowered to use operations that
341 // produce two results, to match the available instructions. This exposes
342 // the two-result form to trivial CSE, which is able to combine x/y and x%y
343 // into a single instruction.
345 // Scalar integer multiply-high is also lowered to use two-result
346 // operations, to match the available instructions. However, plain multiply
347 // (low) operations are left as Legal, as there are single-result
348 // instructions for this in x86. Using the two-result multiply instructions
349 // when both high and low results are needed must be arranged by dagcombine.
350 for (unsigned i = 0, e = 4; i != e; ++i) {
352 setOperationAction(ISD::MULHS, VT, Expand);
353 setOperationAction(ISD::MULHU, VT, Expand);
354 setOperationAction(ISD::SDIV, VT, Expand);
355 setOperationAction(ISD::UDIV, VT, Expand);
356 setOperationAction(ISD::SREM, VT, Expand);
357 setOperationAction(ISD::UREM, VT, Expand);
359 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
360 setOperationAction(ISD::ADDC, VT, Custom);
361 setOperationAction(ISD::ADDE, VT, Custom);
362 setOperationAction(ISD::SUBC, VT, Custom);
363 setOperationAction(ISD::SUBE, VT, Custom);
366 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
367 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
368 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
369 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
370 if (Subtarget->is64Bit())
371 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
372 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
373 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
375 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
376 setOperationAction(ISD::FREM , MVT::f32 , Expand);
377 setOperationAction(ISD::FREM , MVT::f64 , Expand);
378 setOperationAction(ISD::FREM , MVT::f80 , Expand);
379 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
381 if (Subtarget->hasBMI()) {
382 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
384 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
385 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
386 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
387 if (Subtarget->is64Bit())
388 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
391 if (Subtarget->hasLZCNT()) {
392 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
394 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
395 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
396 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
397 if (Subtarget->is64Bit())
398 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
401 if (Subtarget->hasPOPCNT()) {
402 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
404 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
405 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
406 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
407 if (Subtarget->is64Bit())
408 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
411 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
412 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
414 // These should be promoted to a larger select which is supported.
415 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
416 // X86 wants to expand cmov itself.
417 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
418 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
419 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
420 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
421 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
422 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
423 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
424 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
425 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
426 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
427 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
428 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
429 if (Subtarget->is64Bit()) {
430 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
431 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
433 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
436 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
437 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
438 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
439 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
440 if (Subtarget->is64Bit())
441 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
442 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
443 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
444 if (Subtarget->is64Bit()) {
445 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
446 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
447 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
448 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
449 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
451 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
452 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
453 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
454 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
455 if (Subtarget->is64Bit()) {
456 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
457 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
458 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
461 if (Subtarget->hasXMM())
462 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
464 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
465 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
467 // On X86 and X86-64, atomic operations are lowered to locked instructions.
468 // Locked instructions, in turn, have implicit fence semantics (all memory
469 // operations are flushed before issuing the locked instruction, and they
470 // are not buffered), so we can fold away the common pattern of
471 // fence-atomic-fence.
472 setShouldFoldAtomicFences(true);
474 // Expand certain atomics
475 for (unsigned i = 0, e = 4; i != e; ++i) {
477 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
478 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
479 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
482 if (!Subtarget->is64Bit()) {
483 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
484 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
485 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
486 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
487 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
488 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
489 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
490 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
493 if (Subtarget->hasCmpxchg16b()) {
494 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
497 // FIXME - use subtarget debug flags
498 if (!Subtarget->isTargetDarwin() &&
499 !Subtarget->isTargetELF() &&
500 !Subtarget->isTargetCygMing()) {
501 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
504 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
505 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
506 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
507 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
508 if (Subtarget->is64Bit()) {
509 setExceptionPointerRegister(X86::RAX);
510 setExceptionSelectorRegister(X86::RDX);
512 setExceptionPointerRegister(X86::EAX);
513 setExceptionSelectorRegister(X86::EDX);
515 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
516 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
518 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
519 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
521 setOperationAction(ISD::TRAP, MVT::Other, Legal);
523 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
524 setOperationAction(ISD::VASTART , MVT::Other, Custom);
525 setOperationAction(ISD::VAEND , MVT::Other, Expand);
526 if (Subtarget->is64Bit()) {
527 setOperationAction(ISD::VAARG , MVT::Other, Custom);
528 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
530 setOperationAction(ISD::VAARG , MVT::Other, Expand);
531 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
534 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
535 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
537 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
538 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
539 MVT::i64 : MVT::i32, Custom);
540 else if (EnableSegmentedStacks)
541 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
542 MVT::i64 : MVT::i32, Custom);
544 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
545 MVT::i64 : MVT::i32, Expand);
547 if (!UseSoftFloat && X86ScalarSSEf64) {
548 // f32 and f64 use SSE.
549 // Set up the FP register classes.
550 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
551 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
553 // Use ANDPD to simulate FABS.
554 setOperationAction(ISD::FABS , MVT::f64, Custom);
555 setOperationAction(ISD::FABS , MVT::f32, Custom);
557 // Use XORP to simulate FNEG.
558 setOperationAction(ISD::FNEG , MVT::f64, Custom);
559 setOperationAction(ISD::FNEG , MVT::f32, Custom);
561 // Use ANDPD and ORPD to simulate FCOPYSIGN.
562 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
563 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565 // Lower this to FGETSIGNx86 plus an AND.
566 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
567 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
569 // We don't support sin/cos/fmod
570 setOperationAction(ISD::FSIN , MVT::f64, Expand);
571 setOperationAction(ISD::FCOS , MVT::f64, Expand);
572 setOperationAction(ISD::FSIN , MVT::f32, Expand);
573 setOperationAction(ISD::FCOS , MVT::f32, Expand);
575 // Expand FP immediates into loads from the stack, except for the special
577 addLegalFPImmediate(APFloat(+0.0)); // xorpd
578 addLegalFPImmediate(APFloat(+0.0f)); // xorps
579 } else if (!UseSoftFloat && X86ScalarSSEf32) {
580 // Use SSE for f32, x87 for f64.
581 // Set up the FP register classes.
582 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
583 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
585 // Use ANDPS to simulate FABS.
586 setOperationAction(ISD::FABS , MVT::f32, Custom);
588 // Use XORP to simulate FNEG.
589 setOperationAction(ISD::FNEG , MVT::f32, Custom);
591 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
593 // Use ANDPS and ORPS to simulate FCOPYSIGN.
594 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
595 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
597 // We don't support sin/cos/fmod
598 setOperationAction(ISD::FSIN , MVT::f32, Expand);
599 setOperationAction(ISD::FCOS , MVT::f32, Expand);
601 // Special cases we handle for FP constants.
602 addLegalFPImmediate(APFloat(+0.0f)); // xorps
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
609 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
610 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
612 } else if (!UseSoftFloat) {
613 // f32 and f64 in x87.
614 // Set up the FP register classes.
615 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
616 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
618 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
619 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
620 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
621 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
624 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
625 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
627 addLegalFPImmediate(APFloat(+0.0)); // FLD0
628 addLegalFPImmediate(APFloat(+1.0)); // FLD1
629 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
630 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
631 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
632 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
633 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
634 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
637 // We don't support FMA.
638 setOperationAction(ISD::FMA, MVT::f64, Expand);
639 setOperationAction(ISD::FMA, MVT::f32, Expand);
641 // Long double always uses X87.
643 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
644 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
645 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
647 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
648 addLegalFPImmediate(TmpFlt); // FLD0
650 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
653 APFloat TmpFlt2(+1.0);
654 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
656 addLegalFPImmediate(TmpFlt2); // FLD1
657 TmpFlt2.changeSign();
658 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
662 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
663 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
666 setOperationAction(ISD::FMA, MVT::f80, Expand);
669 // Always use a library call for pow.
670 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
671 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
672 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
674 setOperationAction(ISD::FLOG, MVT::f80, Expand);
675 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
676 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
677 setOperationAction(ISD::FEXP, MVT::f80, Expand);
678 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
680 // First set operation action for all vector types to either promote
681 // (for widening) or expand (for scalarization). Then we will selectively
682 // turn on ones that can be effectively codegen'd.
683 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
684 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
685 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
686 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
687 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
688 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
689 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
690 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
691 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
692 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
693 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
694 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
695 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
696 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
697 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
698 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
699 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
700 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
701 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
702 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
703 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
704 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
705 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
706 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
721 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
723 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
724 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
735 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
740 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
741 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
742 setTruncStoreAction((MVT::SimpleValueType)VT,
743 (MVT::SimpleValueType)InnerVT, Expand);
744 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
745 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
749 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
750 // with -msoft-float, disable use of MMX as well.
751 if (!UseSoftFloat && Subtarget->hasMMX()) {
752 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
753 // No operations on x86mmx supported, everything uses intrinsics.
756 // MMX-sized vectors (other than x86mmx) are expected to be expanded
757 // into smaller operations.
758 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
759 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
760 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
761 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
762 setOperationAction(ISD::AND, MVT::v8i8, Expand);
763 setOperationAction(ISD::AND, MVT::v4i16, Expand);
764 setOperationAction(ISD::AND, MVT::v2i32, Expand);
765 setOperationAction(ISD::AND, MVT::v1i64, Expand);
766 setOperationAction(ISD::OR, MVT::v8i8, Expand);
767 setOperationAction(ISD::OR, MVT::v4i16, Expand);
768 setOperationAction(ISD::OR, MVT::v2i32, Expand);
769 setOperationAction(ISD::OR, MVT::v1i64, Expand);
770 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
771 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
772 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
773 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
774 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
775 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
776 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
777 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
778 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
779 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
780 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
781 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
782 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
783 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
784 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
785 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
786 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
788 if (!UseSoftFloat && Subtarget->hasXMM()) {
789 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
791 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
792 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
793 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
794 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
795 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
796 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
797 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
798 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
799 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
800 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
801 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
802 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
805 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
806 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
808 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
809 // registers cannot be used even for integer operations.
810 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
811 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
812 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
813 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
815 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
816 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
817 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
818 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
819 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
820 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
821 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
822 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
823 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
824 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
825 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
826 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
827 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
828 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
829 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
830 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
832 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
833 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
834 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
835 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
837 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
838 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
839 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
840 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
841 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
843 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
844 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
845 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
846 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
847 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
849 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
851 EVT VT = (MVT::SimpleValueType)i;
852 // Do not attempt to custom lower non-power-of-2 vectors
853 if (!isPowerOf2_32(VT.getVectorNumElements()))
855 // Do not attempt to custom lower non-128-bit vectors
856 if (!VT.is128BitVector())
858 setOperationAction(ISD::BUILD_VECTOR,
859 VT.getSimpleVT().SimpleTy, Custom);
860 setOperationAction(ISD::VECTOR_SHUFFLE,
861 VT.getSimpleVT().SimpleTy, Custom);
862 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
863 VT.getSimpleVT().SimpleTy, Custom);
866 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
867 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
868 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
869 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
870 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
871 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
873 if (Subtarget->is64Bit()) {
874 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
875 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
878 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
879 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
880 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
883 // Do not attempt to promote non-128-bit vectors
884 if (!VT.is128BitVector())
887 setOperationAction(ISD::AND, SVT, Promote);
888 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
889 setOperationAction(ISD::OR, SVT, Promote);
890 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
891 setOperationAction(ISD::XOR, SVT, Promote);
892 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
893 setOperationAction(ISD::LOAD, SVT, Promote);
894 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
895 setOperationAction(ISD::SELECT, SVT, Promote);
896 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
899 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
901 // Custom lower v2i64 and v2f64 selects.
902 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
903 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
904 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
905 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
907 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
908 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
911 if (Subtarget->hasSSE41orAVX()) {
912 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
913 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
914 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
915 setOperationAction(ISD::FRINT, MVT::f32, Legal);
916 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
917 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
918 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
919 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
920 setOperationAction(ISD::FRINT, MVT::f64, Legal);
921 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
923 // FIXME: Do we need to handle scalar-to-vector here?
924 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
926 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
927 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
928 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
929 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
930 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
932 // i8 and i16 vectors are custom , because the source register and source
933 // source memory operand types are not the same width. f32 vectors are
934 // custom since the immediate controlling the insert encodes additional
936 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
937 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
938 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
939 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
941 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
942 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
943 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
944 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
946 // FIXME: these should be Legal but thats only for the case where
947 // the index is constant. For now custom expand to deal with that
948 if (Subtarget->is64Bit()) {
949 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
950 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
954 if (Subtarget->hasXMMInt()) {
955 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
956 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
958 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
959 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
961 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
962 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
964 if (Subtarget->hasAVX2()) {
965 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
966 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
968 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
969 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
971 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
973 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
974 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
976 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
977 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
979 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
983 if (Subtarget->hasSSE42orAVX())
984 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
986 if (!UseSoftFloat && Subtarget->hasAVX()) {
987 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
988 addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
989 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
990 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
991 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
992 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
994 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
995 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
996 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
998 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
999 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1000 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1001 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1002 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1003 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1005 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1006 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1007 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1008 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1009 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1010 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1012 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1013 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1014 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1016 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom);
1017 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom);
1018 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
1019 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
1020 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom);
1021 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom);
1023 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1024 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1026 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1027 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1029 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1030 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1032 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1033 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1034 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1035 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1037 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1038 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1039 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1041 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1042 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1043 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1044 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1046 if (Subtarget->hasAVX2()) {
1047 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1048 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1049 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1050 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1052 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1053 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1054 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1055 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1057 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1058 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1059 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1060 // Don't lower v32i8 because there is no 128-bit byte mul
1062 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1064 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1065 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1067 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1068 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1070 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1072 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1073 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1074 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1075 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1077 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1078 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1079 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1080 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1082 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1083 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1084 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1085 // Don't lower v32i8 because there is no 128-bit byte mul
1087 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1088 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1090 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1091 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1093 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1096 // Custom lower several nodes for 256-bit types.
1097 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1098 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1099 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1102 // Extract subvector is special because the value type
1103 // (result) is 128-bit but the source is 256-bit wide.
1104 if (VT.is128BitVector())
1105 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1107 // Do not attempt to custom lower other non-256-bit vectors
1108 if (!VT.is256BitVector())
1111 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1112 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1113 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1114 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1115 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1116 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1119 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1120 for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1121 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1124 // Do not attempt to promote non-256-bit vectors
1125 if (!VT.is256BitVector())
1128 setOperationAction(ISD::AND, SVT, Promote);
1129 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1130 setOperationAction(ISD::OR, SVT, Promote);
1131 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1132 setOperationAction(ISD::XOR, SVT, Promote);
1133 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1134 setOperationAction(ISD::LOAD, SVT, Promote);
1135 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1136 setOperationAction(ISD::SELECT, SVT, Promote);
1137 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1141 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1142 // of this type with custom code.
1143 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1144 VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1145 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1148 // We want to custom lower some of our intrinsics.
1149 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1152 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1153 // handle type legalization for these operations here.
1155 // FIXME: We really should do custom legalization for addition and
1156 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1157 // than generic legalization for 64-bit multiplication-with-overflow, though.
1158 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1159 // Add/Sub/Mul with overflow operations are custom lowered.
1161 setOperationAction(ISD::SADDO, VT, Custom);
1162 setOperationAction(ISD::UADDO, VT, Custom);
1163 setOperationAction(ISD::SSUBO, VT, Custom);
1164 setOperationAction(ISD::USUBO, VT, Custom);
1165 setOperationAction(ISD::SMULO, VT, Custom);
1166 setOperationAction(ISD::UMULO, VT, Custom);
1169 // There are no 8-bit 3-address imul/mul instructions
1170 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1171 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1173 if (!Subtarget->is64Bit()) {
1174 // These libcalls are not available in 32-bit.
1175 setLibcallName(RTLIB::SHL_I128, 0);
1176 setLibcallName(RTLIB::SRL_I128, 0);
1177 setLibcallName(RTLIB::SRA_I128, 0);
1180 // We have target-specific dag combine patterns for the following nodes:
1181 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1182 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1183 setTargetDAGCombine(ISD::BUILD_VECTOR);
1184 setTargetDAGCombine(ISD::VSELECT);
1185 setTargetDAGCombine(ISD::SELECT);
1186 setTargetDAGCombine(ISD::SHL);
1187 setTargetDAGCombine(ISD::SRA);
1188 setTargetDAGCombine(ISD::SRL);
1189 setTargetDAGCombine(ISD::OR);
1190 setTargetDAGCombine(ISD::AND);
1191 setTargetDAGCombine(ISD::ADD);
1192 setTargetDAGCombine(ISD::FADD);
1193 setTargetDAGCombine(ISD::FSUB);
1194 setTargetDAGCombine(ISD::SUB);
1195 setTargetDAGCombine(ISD::LOAD);
1196 setTargetDAGCombine(ISD::STORE);
1197 setTargetDAGCombine(ISD::ZERO_EXTEND);
1198 setTargetDAGCombine(ISD::SINT_TO_FP);
1199 if (Subtarget->is64Bit())
1200 setTargetDAGCombine(ISD::MUL);
1201 if (Subtarget->hasBMI())
1202 setTargetDAGCombine(ISD::XOR);
1204 computeRegisterProperties();
1206 // On Darwin, -Os means optimize for size without hurting performance,
1207 // do not reduce the limit.
1208 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1209 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1210 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1211 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1212 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1213 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1214 setPrefLoopAlignment(16);
1215 benefitFromCodePlacementOpt = true;
1217 setPrefFunctionAlignment(4);
1221 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1222 if (!VT.isVector()) return MVT::i8;
1223 return VT.changeVectorElementTypeToInteger();
1227 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1228 /// the desired ByVal argument alignment.
1229 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1232 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1233 if (VTy->getBitWidth() == 128)
1235 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1236 unsigned EltAlign = 0;
1237 getMaxByValAlign(ATy->getElementType(), EltAlign);
1238 if (EltAlign > MaxAlign)
1239 MaxAlign = EltAlign;
1240 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1241 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1242 unsigned EltAlign = 0;
1243 getMaxByValAlign(STy->getElementType(i), EltAlign);
1244 if (EltAlign > MaxAlign)
1245 MaxAlign = EltAlign;
1253 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1254 /// function arguments in the caller parameter area. For X86, aggregates
1255 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1256 /// are at 4-byte boundaries.
1257 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1258 if (Subtarget->is64Bit()) {
1259 // Max of 8 and alignment of type.
1260 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1267 if (Subtarget->hasXMM())
1268 getMaxByValAlign(Ty, Align);
1272 /// getOptimalMemOpType - Returns the target specific optimal type for load
1273 /// and store operations as a result of memset, memcpy, and memmove
1274 /// lowering. If DstAlign is zero that means it's safe to destination
1275 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1276 /// means there isn't a need to check it against alignment requirement,
1277 /// probably because the source does not need to be loaded. If
1278 /// 'IsZeroVal' is true, that means it's safe to return a
1279 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1280 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1281 /// constant so it does not need to be loaded.
1282 /// It returns EVT::Other if the type should be determined using generic
1283 /// target-independent logic.
1285 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1286 unsigned DstAlign, unsigned SrcAlign,
1289 MachineFunction &MF) const {
1290 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1291 // linux. This is because the stack realignment code can't handle certain
1292 // cases like PR2962. This should be removed when PR2962 is fixed.
1293 const Function *F = MF.getFunction();
1295 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1297 (Subtarget->isUnalignedMemAccessFast() ||
1298 ((DstAlign == 0 || DstAlign >= 16) &&
1299 (SrcAlign == 0 || SrcAlign >= 16))) &&
1300 Subtarget->getStackAlignment() >= 16) {
1301 if (Subtarget->hasAVX() &&
1302 Subtarget->getStackAlignment() >= 32)
1304 if (Subtarget->hasXMMInt())
1306 if (Subtarget->hasXMM())
1308 } else if (!MemcpyStrSrc && Size >= 8 &&
1309 !Subtarget->is64Bit() &&
1310 Subtarget->getStackAlignment() >= 8 &&
1311 Subtarget->hasXMMInt()) {
1312 // Do not use f64 to lower memcpy if source is string constant. It's
1313 // better to use i32 to avoid the loads.
1317 if (Subtarget->is64Bit() && Size >= 8)
1322 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1323 /// current function. The returned value is a member of the
1324 /// MachineJumpTableInfo::JTEntryKind enum.
1325 unsigned X86TargetLowering::getJumpTableEncoding() const {
1326 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1328 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1329 Subtarget->isPICStyleGOT())
1330 return MachineJumpTableInfo::EK_Custom32;
1332 // Otherwise, use the normal jump table encoding heuristics.
1333 return TargetLowering::getJumpTableEncoding();
1337 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1338 const MachineBasicBlock *MBB,
1339 unsigned uid,MCContext &Ctx) const{
1340 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1341 Subtarget->isPICStyleGOT());
1342 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1344 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1345 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1348 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1350 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1351 SelectionDAG &DAG) const {
1352 if (!Subtarget->is64Bit())
1353 // This doesn't have DebugLoc associated with it, but is not really the
1354 // same as a Register.
1355 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1359 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1360 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1362 const MCExpr *X86TargetLowering::
1363 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1364 MCContext &Ctx) const {
1365 // X86-64 uses RIP relative addressing based on the jump table label.
1366 if (Subtarget->isPICStyleRIPRel())
1367 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1369 // Otherwise, the reference is relative to the PIC base.
1370 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1373 // FIXME: Why this routine is here? Move to RegInfo!
1374 std::pair<const TargetRegisterClass*, uint8_t>
1375 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1376 const TargetRegisterClass *RRC = 0;
1378 switch (VT.getSimpleVT().SimpleTy) {
1380 return TargetLowering::findRepresentativeClass(VT);
1381 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1382 RRC = (Subtarget->is64Bit()
1383 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1386 RRC = X86::VR64RegisterClass;
1388 case MVT::f32: case MVT::f64:
1389 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1390 case MVT::v4f32: case MVT::v2f64:
1391 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1393 RRC = X86::VR128RegisterClass;
1396 return std::make_pair(RRC, Cost);
1399 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1400 unsigned &Offset) const {
1401 if (!Subtarget->isTargetLinux())
1404 if (Subtarget->is64Bit()) {
1405 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1407 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1420 //===----------------------------------------------------------------------===//
1421 // Return Value Calling Convention Implementation
1422 //===----------------------------------------------------------------------===//
1424 #include "X86GenCallingConv.inc"
1427 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1428 MachineFunction &MF, bool isVarArg,
1429 const SmallVectorImpl<ISD::OutputArg> &Outs,
1430 LLVMContext &Context) const {
1431 SmallVector<CCValAssign, 16> RVLocs;
1432 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1434 return CCInfo.CheckReturn(Outs, RetCC_X86);
1438 X86TargetLowering::LowerReturn(SDValue Chain,
1439 CallingConv::ID CallConv, bool isVarArg,
1440 const SmallVectorImpl<ISD::OutputArg> &Outs,
1441 const SmallVectorImpl<SDValue> &OutVals,
1442 DebugLoc dl, SelectionDAG &DAG) const {
1443 MachineFunction &MF = DAG.getMachineFunction();
1444 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1446 SmallVector<CCValAssign, 16> RVLocs;
1447 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1448 RVLocs, *DAG.getContext());
1449 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1451 // Add the regs to the liveout set for the function.
1452 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1453 for (unsigned i = 0; i != RVLocs.size(); ++i)
1454 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1455 MRI.addLiveOut(RVLocs[i].getLocReg());
1459 SmallVector<SDValue, 6> RetOps;
1460 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1461 // Operand #1 = Bytes To Pop
1462 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1465 // Copy the result values into the output registers.
1466 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1467 CCValAssign &VA = RVLocs[i];
1468 assert(VA.isRegLoc() && "Can only return in registers!");
1469 SDValue ValToCopy = OutVals[i];
1470 EVT ValVT = ValToCopy.getValueType();
1472 // If this is x86-64, and we disabled SSE, we can't return FP values,
1473 // or SSE or MMX vectors.
1474 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1475 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1476 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1477 report_fatal_error("SSE register return with SSE disabled");
1479 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1480 // llvm-gcc has never done it right and no one has noticed, so this
1481 // should be OK for now.
1482 if (ValVT == MVT::f64 &&
1483 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1484 report_fatal_error("SSE2 register return with SSE2 disabled");
1486 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1487 // the RET instruction and handled by the FP Stackifier.
1488 if (VA.getLocReg() == X86::ST0 ||
1489 VA.getLocReg() == X86::ST1) {
1490 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1491 // change the value to the FP stack register class.
1492 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1493 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1494 RetOps.push_back(ValToCopy);
1495 // Don't emit a copytoreg.
1499 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1500 // which is returned in RAX / RDX.
1501 if (Subtarget->is64Bit()) {
1502 if (ValVT == MVT::x86mmx) {
1503 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1504 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1505 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1507 // If we don't have SSE2 available, convert to v4f32 so the generated
1508 // register is legal.
1509 if (!Subtarget->hasXMMInt())
1510 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1515 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1516 Flag = Chain.getValue(1);
1519 // The x86-64 ABI for returning structs by value requires that we copy
1520 // the sret argument into %rax for the return. We saved the argument into
1521 // a virtual register in the entry block, so now we copy the value out
1523 if (Subtarget->is64Bit() &&
1524 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1525 MachineFunction &MF = DAG.getMachineFunction();
1526 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1527 unsigned Reg = FuncInfo->getSRetReturnReg();
1529 "SRetReturnReg should have been set in LowerFormalArguments().");
1530 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1532 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1533 Flag = Chain.getValue(1);
1535 // RAX now acts like a return value.
1536 MRI.addLiveOut(X86::RAX);
1539 RetOps[0] = Chain; // Update chain.
1541 // Add the flag if we have it.
1543 RetOps.push_back(Flag);
1545 return DAG.getNode(X86ISD::RET_FLAG, dl,
1546 MVT::Other, &RetOps[0], RetOps.size());
1549 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1550 if (N->getNumValues() != 1)
1552 if (!N->hasNUsesOfValue(1, 0))
1555 SDNode *Copy = *N->use_begin();
1556 if (Copy->getOpcode() != ISD::CopyToReg &&
1557 Copy->getOpcode() != ISD::FP_EXTEND)
1560 bool HasRet = false;
1561 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1563 if (UI->getOpcode() != X86ISD::RET_FLAG)
1572 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1573 ISD::NodeType ExtendKind) const {
1575 // TODO: Is this also valid on 32-bit?
1576 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1577 ReturnMVT = MVT::i8;
1579 ReturnMVT = MVT::i32;
1581 EVT MinVT = getRegisterType(Context, ReturnMVT);
1582 return VT.bitsLT(MinVT) ? MinVT : VT;
1585 /// LowerCallResult - Lower the result values of a call into the
1586 /// appropriate copies out of appropriate physical registers.
1589 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1590 CallingConv::ID CallConv, bool isVarArg,
1591 const SmallVectorImpl<ISD::InputArg> &Ins,
1592 DebugLoc dl, SelectionDAG &DAG,
1593 SmallVectorImpl<SDValue> &InVals) const {
1595 // Assign locations to each value returned by this call.
1596 SmallVector<CCValAssign, 16> RVLocs;
1597 bool Is64Bit = Subtarget->is64Bit();
1598 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1599 getTargetMachine(), RVLocs, *DAG.getContext());
1600 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1602 // Copy all of the result registers out of their specified physreg.
1603 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1604 CCValAssign &VA = RVLocs[i];
1605 EVT CopyVT = VA.getValVT();
1607 // If this is x86-64, and we disabled SSE, we can't return FP values
1608 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1609 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1610 report_fatal_error("SSE register return with SSE disabled");
1615 // If this is a call to a function that returns an fp value on the floating
1616 // point stack, we must guarantee the the value is popped from the stack, so
1617 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1618 // if the return value is not used. We use the FpPOP_RETVAL instruction
1620 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1621 // If we prefer to use the value in xmm registers, copy it out as f80 and
1622 // use a truncate to move it from fp stack reg to xmm reg.
1623 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1624 SDValue Ops[] = { Chain, InFlag };
1625 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1626 MVT::Other, MVT::Glue, Ops, 2), 1);
1627 Val = Chain.getValue(0);
1629 // Round the f80 to the right size, which also moves it to the appropriate
1631 if (CopyVT != VA.getValVT())
1632 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1633 // This truncation won't change the value.
1634 DAG.getIntPtrConstant(1));
1636 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1637 CopyVT, InFlag).getValue(1);
1638 Val = Chain.getValue(0);
1640 InFlag = Chain.getValue(2);
1641 InVals.push_back(Val);
1648 //===----------------------------------------------------------------------===//
1649 // C & StdCall & Fast Calling Convention implementation
1650 //===----------------------------------------------------------------------===//
1651 // StdCall calling convention seems to be standard for many Windows' API
1652 // routines and around. It differs from C calling convention just a little:
1653 // callee should clean up the stack, not caller. Symbols should be also
1654 // decorated in some fancy way :) It doesn't support any vector arguments.
1655 // For info on fast calling convention see Fast Calling Convention (tail call)
1656 // implementation LowerX86_32FastCCCallTo.
1658 /// CallIsStructReturn - Determines whether a call uses struct return
1660 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1664 return Outs[0].Flags.isSRet();
1667 /// ArgsAreStructReturn - Determines whether a function uses struct
1668 /// return semantics.
1670 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1674 return Ins[0].Flags.isSRet();
1677 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1678 /// by "Src" to address "Dst" with size and alignment information specified by
1679 /// the specific parameter attribute. The copy will be passed as a byval
1680 /// function parameter.
1682 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1683 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1685 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1687 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1688 /*isVolatile*/false, /*AlwaysInline=*/true,
1689 MachinePointerInfo(), MachinePointerInfo());
1692 /// IsTailCallConvention - Return true if the calling convention is one that
1693 /// supports tail call optimization.
1694 static bool IsTailCallConvention(CallingConv::ID CC) {
1695 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1698 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1699 if (!CI->isTailCall())
1703 CallingConv::ID CalleeCC = CS.getCallingConv();
1704 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1710 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1711 /// a tailcall target by changing its ABI.
1712 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1713 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1717 X86TargetLowering::LowerMemArgument(SDValue Chain,
1718 CallingConv::ID CallConv,
1719 const SmallVectorImpl<ISD::InputArg> &Ins,
1720 DebugLoc dl, SelectionDAG &DAG,
1721 const CCValAssign &VA,
1722 MachineFrameInfo *MFI,
1724 // Create the nodes corresponding to a load from this parameter slot.
1725 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1726 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1727 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1730 // If value is passed by pointer we have address passed instead of the value
1732 if (VA.getLocInfo() == CCValAssign::Indirect)
1733 ValVT = VA.getLocVT();
1735 ValVT = VA.getValVT();
1737 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1738 // changed with more analysis.
1739 // In case of tail call optimization mark all arguments mutable. Since they
1740 // could be overwritten by lowering of arguments in case of a tail call.
1741 if (Flags.isByVal()) {
1742 unsigned Bytes = Flags.getByValSize();
1743 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1744 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1745 return DAG.getFrameIndex(FI, getPointerTy());
1747 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1748 VA.getLocMemOffset(), isImmutable);
1749 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1750 return DAG.getLoad(ValVT, dl, Chain, FIN,
1751 MachinePointerInfo::getFixedStack(FI),
1752 false, false, false, 0);
1757 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1758 CallingConv::ID CallConv,
1760 const SmallVectorImpl<ISD::InputArg> &Ins,
1763 SmallVectorImpl<SDValue> &InVals)
1765 MachineFunction &MF = DAG.getMachineFunction();
1766 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1768 const Function* Fn = MF.getFunction();
1769 if (Fn->hasExternalLinkage() &&
1770 Subtarget->isTargetCygMing() &&
1771 Fn->getName() == "main")
1772 FuncInfo->setForceFramePointer(true);
1774 MachineFrameInfo *MFI = MF.getFrameInfo();
1775 bool Is64Bit = Subtarget->is64Bit();
1776 bool IsWin64 = Subtarget->isTargetWin64();
1778 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1779 "Var args not supported with calling convention fastcc or ghc");
1781 // Assign locations to all of the incoming arguments.
1782 SmallVector<CCValAssign, 16> ArgLocs;
1783 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1784 ArgLocs, *DAG.getContext());
1786 // Allocate shadow area for Win64
1788 CCInfo.AllocateStack(32, 8);
1791 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1793 unsigned LastVal = ~0U;
1795 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1796 CCValAssign &VA = ArgLocs[i];
1797 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1799 assert(VA.getValNo() != LastVal &&
1800 "Don't support value assigned to multiple locs yet");
1802 LastVal = VA.getValNo();
1804 if (VA.isRegLoc()) {
1805 EVT RegVT = VA.getLocVT();
1806 TargetRegisterClass *RC = NULL;
1807 if (RegVT == MVT::i32)
1808 RC = X86::GR32RegisterClass;
1809 else if (Is64Bit && RegVT == MVT::i64)
1810 RC = X86::GR64RegisterClass;
1811 else if (RegVT == MVT::f32)
1812 RC = X86::FR32RegisterClass;
1813 else if (RegVT == MVT::f64)
1814 RC = X86::FR64RegisterClass;
1815 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1816 RC = X86::VR256RegisterClass;
1817 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1818 RC = X86::VR128RegisterClass;
1819 else if (RegVT == MVT::x86mmx)
1820 RC = X86::VR64RegisterClass;
1822 llvm_unreachable("Unknown argument type!");
1824 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1825 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1827 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1828 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1830 if (VA.getLocInfo() == CCValAssign::SExt)
1831 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1832 DAG.getValueType(VA.getValVT()));
1833 else if (VA.getLocInfo() == CCValAssign::ZExt)
1834 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1835 DAG.getValueType(VA.getValVT()));
1836 else if (VA.getLocInfo() == CCValAssign::BCvt)
1837 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1839 if (VA.isExtInLoc()) {
1840 // Handle MMX values passed in XMM regs.
1841 if (RegVT.isVector()) {
1842 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1845 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1848 assert(VA.isMemLoc());
1849 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1852 // If value is passed via pointer - do a load.
1853 if (VA.getLocInfo() == CCValAssign::Indirect)
1854 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1855 MachinePointerInfo(), false, false, false, 0);
1857 InVals.push_back(ArgValue);
1860 // The x86-64 ABI for returning structs by value requires that we copy
1861 // the sret argument into %rax for the return. Save the argument into
1862 // a virtual register so that we can access it from the return points.
1863 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1864 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1865 unsigned Reg = FuncInfo->getSRetReturnReg();
1867 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1868 FuncInfo->setSRetReturnReg(Reg);
1870 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1871 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1874 unsigned StackSize = CCInfo.getNextStackOffset();
1875 // Align stack specially for tail calls.
1876 if (FuncIsMadeTailCallSafe(CallConv))
1877 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1879 // If the function takes variable number of arguments, make a frame index for
1880 // the start of the first vararg value... for expansion of llvm.va_start.
1882 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1883 CallConv != CallingConv::X86_ThisCall)) {
1884 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1887 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1889 // FIXME: We should really autogenerate these arrays
1890 static const unsigned GPR64ArgRegsWin64[] = {
1891 X86::RCX, X86::RDX, X86::R8, X86::R9
1893 static const unsigned GPR64ArgRegs64Bit[] = {
1894 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1896 static const unsigned XMMArgRegs64Bit[] = {
1897 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1898 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1900 const unsigned *GPR64ArgRegs;
1901 unsigned NumXMMRegs = 0;
1904 // The XMM registers which might contain var arg parameters are shadowed
1905 // in their paired GPR. So we only need to save the GPR to their home
1907 TotalNumIntRegs = 4;
1908 GPR64ArgRegs = GPR64ArgRegsWin64;
1910 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1911 GPR64ArgRegs = GPR64ArgRegs64Bit;
1913 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1915 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1918 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1919 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1920 "SSE register cannot be used when SSE is disabled!");
1921 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1922 "SSE register cannot be used when SSE is disabled!");
1923 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1924 // Kernel mode asks for SSE to be disabled, so don't push them
1926 TotalNumXMMRegs = 0;
1929 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1930 // Get to the caller-allocated home save location. Add 8 to account
1931 // for the return address.
1932 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1933 FuncInfo->setRegSaveFrameIndex(
1934 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1935 // Fixup to set vararg frame on shadow area (4 x i64).
1937 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1939 // For X86-64, if there are vararg parameters that are passed via
1940 // registers, then we must store them to their spots on the stack so they
1941 // may be loaded by deferencing the result of va_next.
1942 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1943 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1944 FuncInfo->setRegSaveFrameIndex(
1945 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1949 // Store the integer parameter registers.
1950 SmallVector<SDValue, 8> MemOps;
1951 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1953 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1954 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1955 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1956 DAG.getIntPtrConstant(Offset));
1957 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1958 X86::GR64RegisterClass);
1959 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1961 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1962 MachinePointerInfo::getFixedStack(
1963 FuncInfo->getRegSaveFrameIndex(), Offset),
1965 MemOps.push_back(Store);
1969 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1970 // Now store the XMM (fp + vector) parameter registers.
1971 SmallVector<SDValue, 11> SaveXMMOps;
1972 SaveXMMOps.push_back(Chain);
1974 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1975 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1976 SaveXMMOps.push_back(ALVal);
1978 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1979 FuncInfo->getRegSaveFrameIndex()));
1980 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1981 FuncInfo->getVarArgsFPOffset()));
1983 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1984 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1985 X86::VR128RegisterClass);
1986 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1987 SaveXMMOps.push_back(Val);
1989 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1991 &SaveXMMOps[0], SaveXMMOps.size()));
1994 if (!MemOps.empty())
1995 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1996 &MemOps[0], MemOps.size());
2000 // Some CCs need callee pop.
2001 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
2002 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2004 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2005 // If this is an sret function, the return should pop the hidden pointer.
2006 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
2007 FuncInfo->setBytesToPopOnReturn(4);
2011 // RegSaveFrameIndex is X86-64 only.
2012 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2013 if (CallConv == CallingConv::X86_FastCall ||
2014 CallConv == CallingConv::X86_ThisCall)
2015 // fastcc functions can't have varargs.
2016 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2019 FuncInfo->setArgumentStackSize(StackSize);
2025 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2026 SDValue StackPtr, SDValue Arg,
2027 DebugLoc dl, SelectionDAG &DAG,
2028 const CCValAssign &VA,
2029 ISD::ArgFlagsTy Flags) const {
2030 unsigned LocMemOffset = VA.getLocMemOffset();
2031 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2032 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2033 if (Flags.isByVal())
2034 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2036 return DAG.getStore(Chain, dl, Arg, PtrOff,
2037 MachinePointerInfo::getStack(LocMemOffset),
2041 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2042 /// optimization is performed and it is required.
2044 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2045 SDValue &OutRetAddr, SDValue Chain,
2046 bool IsTailCall, bool Is64Bit,
2047 int FPDiff, DebugLoc dl) const {
2048 // Adjust the Return address stack slot.
2049 EVT VT = getPointerTy();
2050 OutRetAddr = getReturnAddressFrameIndex(DAG);
2052 // Load the "old" Return address.
2053 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2054 false, false, false, 0);
2055 return SDValue(OutRetAddr.getNode(), 1);
2058 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2059 /// optimization is performed and it is required (FPDiff!=0).
2061 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2062 SDValue Chain, SDValue RetAddrFrIdx,
2063 bool Is64Bit, int FPDiff, DebugLoc dl) {
2064 // Store the return address to the appropriate stack slot.
2065 if (!FPDiff) return Chain;
2066 // Calculate the new stack slot for the return address.
2067 int SlotSize = Is64Bit ? 8 : 4;
2068 int NewReturnAddrFI =
2069 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2070 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2071 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2072 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2073 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2079 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2080 CallingConv::ID CallConv, bool isVarArg,
2082 const SmallVectorImpl<ISD::OutputArg> &Outs,
2083 const SmallVectorImpl<SDValue> &OutVals,
2084 const SmallVectorImpl<ISD::InputArg> &Ins,
2085 DebugLoc dl, SelectionDAG &DAG,
2086 SmallVectorImpl<SDValue> &InVals) const {
2087 MachineFunction &MF = DAG.getMachineFunction();
2088 bool Is64Bit = Subtarget->is64Bit();
2089 bool IsWin64 = Subtarget->isTargetWin64();
2090 bool IsStructRet = CallIsStructReturn(Outs);
2091 bool IsSibcall = false;
2094 // Check if it's really possible to do a tail call.
2095 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2096 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2097 Outs, OutVals, Ins, DAG);
2099 // Sibcalls are automatically detected tailcalls which do not require
2101 if (!GuaranteedTailCallOpt && isTailCall)
2108 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2109 "Var args not supported with calling convention fastcc or ghc");
2111 // Analyze operands of the call, assigning locations to each operand.
2112 SmallVector<CCValAssign, 16> ArgLocs;
2113 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2114 ArgLocs, *DAG.getContext());
2116 // Allocate shadow area for Win64
2118 CCInfo.AllocateStack(32, 8);
2121 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2123 // Get a count of how many bytes are to be pushed on the stack.
2124 unsigned NumBytes = CCInfo.getNextStackOffset();
2126 // This is a sibcall. The memory operands are available in caller's
2127 // own caller's stack.
2129 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2130 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2133 if (isTailCall && !IsSibcall) {
2134 // Lower arguments at fp - stackoffset + fpdiff.
2135 unsigned NumBytesCallerPushed =
2136 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2137 FPDiff = NumBytesCallerPushed - NumBytes;
2139 // Set the delta of movement of the returnaddr stackslot.
2140 // But only set if delta is greater than previous delta.
2141 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2142 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2146 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2148 SDValue RetAddrFrIdx;
2149 // Load return address for tail calls.
2150 if (isTailCall && FPDiff)
2151 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2152 Is64Bit, FPDiff, dl);
2154 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2155 SmallVector<SDValue, 8> MemOpChains;
2158 // Walk the register/memloc assignments, inserting copies/loads. In the case
2159 // of tail call optimization arguments are handle later.
2160 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2161 CCValAssign &VA = ArgLocs[i];
2162 EVT RegVT = VA.getLocVT();
2163 SDValue Arg = OutVals[i];
2164 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2165 bool isByVal = Flags.isByVal();
2167 // Promote the value if needed.
2168 switch (VA.getLocInfo()) {
2169 default: llvm_unreachable("Unknown loc info!");
2170 case CCValAssign::Full: break;
2171 case CCValAssign::SExt:
2172 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2174 case CCValAssign::ZExt:
2175 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2177 case CCValAssign::AExt:
2178 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2179 // Special case: passing MMX values in XMM registers.
2180 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2181 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2182 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2184 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2186 case CCValAssign::BCvt:
2187 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2189 case CCValAssign::Indirect: {
2190 // Store the argument.
2191 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2192 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2193 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2194 MachinePointerInfo::getFixedStack(FI),
2201 if (VA.isRegLoc()) {
2202 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2203 if (isVarArg && IsWin64) {
2204 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2205 // shadow reg if callee is a varargs function.
2206 unsigned ShadowReg = 0;
2207 switch (VA.getLocReg()) {
2208 case X86::XMM0: ShadowReg = X86::RCX; break;
2209 case X86::XMM1: ShadowReg = X86::RDX; break;
2210 case X86::XMM2: ShadowReg = X86::R8; break;
2211 case X86::XMM3: ShadowReg = X86::R9; break;
2214 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2216 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2217 assert(VA.isMemLoc());
2218 if (StackPtr.getNode() == 0)
2219 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2220 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2221 dl, DAG, VA, Flags));
2225 if (!MemOpChains.empty())
2226 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2227 &MemOpChains[0], MemOpChains.size());
2229 // Build a sequence of copy-to-reg nodes chained together with token chain
2230 // and flag operands which copy the outgoing args into registers.
2232 // Tail call byval lowering might overwrite argument registers so in case of
2233 // tail call optimization the copies to registers are lowered later.
2235 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2236 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2237 RegsToPass[i].second, InFlag);
2238 InFlag = Chain.getValue(1);
2241 if (Subtarget->isPICStyleGOT()) {
2242 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2245 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2246 DAG.getNode(X86ISD::GlobalBaseReg,
2247 DebugLoc(), getPointerTy()),
2249 InFlag = Chain.getValue(1);
2251 // If we are tail calling and generating PIC/GOT style code load the
2252 // address of the callee into ECX. The value in ecx is used as target of
2253 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2254 // for tail calls on PIC/GOT architectures. Normally we would just put the
2255 // address of GOT into ebx and then call target@PLT. But for tail calls
2256 // ebx would be restored (since ebx is callee saved) before jumping to the
2259 // Note: The actual moving to ECX is done further down.
2260 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2261 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2262 !G->getGlobal()->hasProtectedVisibility())
2263 Callee = LowerGlobalAddress(Callee, DAG);
2264 else if (isa<ExternalSymbolSDNode>(Callee))
2265 Callee = LowerExternalSymbol(Callee, DAG);
2269 if (Is64Bit && isVarArg && !IsWin64) {
2270 // From AMD64 ABI document:
2271 // For calls that may call functions that use varargs or stdargs
2272 // (prototype-less calls or calls to functions containing ellipsis (...) in
2273 // the declaration) %al is used as hidden argument to specify the number
2274 // of SSE registers used. The contents of %al do not need to match exactly
2275 // the number of registers, but must be an ubound on the number of SSE
2276 // registers used and is in the range 0 - 8 inclusive.
2278 // Count the number of XMM registers allocated.
2279 static const unsigned XMMArgRegs[] = {
2280 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2281 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2283 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2284 assert((Subtarget->hasXMM() || !NumXMMRegs)
2285 && "SSE registers cannot be used when SSE is disabled");
2287 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2288 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2289 InFlag = Chain.getValue(1);
2293 // For tail calls lower the arguments to the 'real' stack slot.
2295 // Force all the incoming stack arguments to be loaded from the stack
2296 // before any new outgoing arguments are stored to the stack, because the
2297 // outgoing stack slots may alias the incoming argument stack slots, and
2298 // the alias isn't otherwise explicit. This is slightly more conservative
2299 // than necessary, because it means that each store effectively depends
2300 // on every argument instead of just those arguments it would clobber.
2301 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2303 SmallVector<SDValue, 8> MemOpChains2;
2306 // Do not flag preceding copytoreg stuff together with the following stuff.
2308 if (GuaranteedTailCallOpt) {
2309 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2310 CCValAssign &VA = ArgLocs[i];
2313 assert(VA.isMemLoc());
2314 SDValue Arg = OutVals[i];
2315 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2316 // Create frame index.
2317 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2318 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2319 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2320 FIN = DAG.getFrameIndex(FI, getPointerTy());
2322 if (Flags.isByVal()) {
2323 // Copy relative to framepointer.
2324 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2325 if (StackPtr.getNode() == 0)
2326 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2328 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2330 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2334 // Store relative to framepointer.
2335 MemOpChains2.push_back(
2336 DAG.getStore(ArgChain, dl, Arg, FIN,
2337 MachinePointerInfo::getFixedStack(FI),
2343 if (!MemOpChains2.empty())
2344 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2345 &MemOpChains2[0], MemOpChains2.size());
2347 // Copy arguments to their registers.
2348 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2349 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2350 RegsToPass[i].second, InFlag);
2351 InFlag = Chain.getValue(1);
2355 // Store the return address to the appropriate stack slot.
2356 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2360 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2361 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2362 // In the 64-bit large code model, we have to make all calls
2363 // through a register, since the call instruction's 32-bit
2364 // pc-relative offset may not be large enough to hold the whole
2366 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2367 // If the callee is a GlobalAddress node (quite common, every direct call
2368 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2371 // We should use extra load for direct calls to dllimported functions in
2373 const GlobalValue *GV = G->getGlobal();
2374 if (!GV->hasDLLImportLinkage()) {
2375 unsigned char OpFlags = 0;
2376 bool ExtraLoad = false;
2377 unsigned WrapperKind = ISD::DELETED_NODE;
2379 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2380 // external symbols most go through the PLT in PIC mode. If the symbol
2381 // has hidden or protected visibility, or if it is static or local, then
2382 // we don't need to use the PLT - we can directly call it.
2383 if (Subtarget->isTargetELF() &&
2384 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2385 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2386 OpFlags = X86II::MO_PLT;
2387 } else if (Subtarget->isPICStyleStubAny() &&
2388 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2389 (!Subtarget->getTargetTriple().isMacOSX() ||
2390 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2391 // PC-relative references to external symbols should go through $stub,
2392 // unless we're building with the leopard linker or later, which
2393 // automatically synthesizes these stubs.
2394 OpFlags = X86II::MO_DARWIN_STUB;
2395 } else if (Subtarget->isPICStyleRIPRel() &&
2396 isa<Function>(GV) &&
2397 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2398 // If the function is marked as non-lazy, generate an indirect call
2399 // which loads from the GOT directly. This avoids runtime overhead
2400 // at the cost of eager binding (and one extra byte of encoding).
2401 OpFlags = X86II::MO_GOTPCREL;
2402 WrapperKind = X86ISD::WrapperRIP;
2406 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2407 G->getOffset(), OpFlags);
2409 // Add a wrapper if needed.
2410 if (WrapperKind != ISD::DELETED_NODE)
2411 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2412 // Add extra indirection if needed.
2414 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2415 MachinePointerInfo::getGOT(),
2416 false, false, false, 0);
2418 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2419 unsigned char OpFlags = 0;
2421 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2422 // external symbols should go through the PLT.
2423 if (Subtarget->isTargetELF() &&
2424 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2425 OpFlags = X86II::MO_PLT;
2426 } else if (Subtarget->isPICStyleStubAny() &&
2427 (!Subtarget->getTargetTriple().isMacOSX() ||
2428 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2429 // PC-relative references to external symbols should go through $stub,
2430 // unless we're building with the leopard linker or later, which
2431 // automatically synthesizes these stubs.
2432 OpFlags = X86II::MO_DARWIN_STUB;
2435 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2439 // Returns a chain & a flag for retval copy to use.
2440 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2441 SmallVector<SDValue, 8> Ops;
2443 if (!IsSibcall && isTailCall) {
2444 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2445 DAG.getIntPtrConstant(0, true), InFlag);
2446 InFlag = Chain.getValue(1);
2449 Ops.push_back(Chain);
2450 Ops.push_back(Callee);
2453 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2455 // Add argument registers to the end of the list so that they are known live
2457 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2458 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2459 RegsToPass[i].second.getValueType()));
2461 // Add an implicit use GOT pointer in EBX.
2462 if (!isTailCall && Subtarget->isPICStyleGOT())
2463 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2465 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2466 if (Is64Bit && isVarArg && !IsWin64)
2467 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2469 if (InFlag.getNode())
2470 Ops.push_back(InFlag);
2474 //// If this is the first return lowered for this function, add the regs
2475 //// to the liveout set for the function.
2476 // This isn't right, although it's probably harmless on x86; liveouts
2477 // should be computed from returns not tail calls. Consider a void
2478 // function making a tail call to a function returning int.
2479 return DAG.getNode(X86ISD::TC_RETURN, dl,
2480 NodeTys, &Ops[0], Ops.size());
2483 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2484 InFlag = Chain.getValue(1);
2486 // Create the CALLSEQ_END node.
2487 unsigned NumBytesForCalleeToPush;
2488 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2489 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2490 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2491 // If this is a call to a struct-return function, the callee
2492 // pops the hidden struct pointer, so we have to push it back.
2493 // This is common for Darwin/X86, Linux & Mingw32 targets.
2494 NumBytesForCalleeToPush = 4;
2496 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2498 // Returns a flag for retval copy to use.
2500 Chain = DAG.getCALLSEQ_END(Chain,
2501 DAG.getIntPtrConstant(NumBytes, true),
2502 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2505 InFlag = Chain.getValue(1);
2508 // Handle result values, copying them out of physregs into vregs that we
2510 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2511 Ins, dl, DAG, InVals);
2515 //===----------------------------------------------------------------------===//
2516 // Fast Calling Convention (tail call) implementation
2517 //===----------------------------------------------------------------------===//
2519 // Like std call, callee cleans arguments, convention except that ECX is
2520 // reserved for storing the tail called function address. Only 2 registers are
2521 // free for argument passing (inreg). Tail call optimization is performed
2523 // * tailcallopt is enabled
2524 // * caller/callee are fastcc
2525 // On X86_64 architecture with GOT-style position independent code only local
2526 // (within module) calls are supported at the moment.
2527 // To keep the stack aligned according to platform abi the function
2528 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2529 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2530 // If a tail called function callee has more arguments than the caller the
2531 // caller needs to make sure that there is room to move the RETADDR to. This is
2532 // achieved by reserving an area the size of the argument delta right after the
2533 // original REtADDR, but before the saved framepointer or the spilled registers
2534 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2546 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2547 /// for a 16 byte align requirement.
2549 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2550 SelectionDAG& DAG) const {
2551 MachineFunction &MF = DAG.getMachineFunction();
2552 const TargetMachine &TM = MF.getTarget();
2553 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2554 unsigned StackAlignment = TFI.getStackAlignment();
2555 uint64_t AlignMask = StackAlignment - 1;
2556 int64_t Offset = StackSize;
2557 uint64_t SlotSize = TD->getPointerSize();
2558 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2559 // Number smaller than 12 so just add the difference.
2560 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2562 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2563 Offset = ((~AlignMask) & Offset) + StackAlignment +
2564 (StackAlignment-SlotSize);
2569 /// MatchingStackOffset - Return true if the given stack call argument is
2570 /// already available in the same position (relatively) of the caller's
2571 /// incoming argument stack.
2573 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2574 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2575 const X86InstrInfo *TII) {
2576 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2578 if (Arg.getOpcode() == ISD::CopyFromReg) {
2579 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2580 if (!TargetRegisterInfo::isVirtualRegister(VR))
2582 MachineInstr *Def = MRI->getVRegDef(VR);
2585 if (!Flags.isByVal()) {
2586 if (!TII->isLoadFromStackSlot(Def, FI))
2589 unsigned Opcode = Def->getOpcode();
2590 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2591 Def->getOperand(1).isFI()) {
2592 FI = Def->getOperand(1).getIndex();
2593 Bytes = Flags.getByValSize();
2597 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2598 if (Flags.isByVal())
2599 // ByVal argument is passed in as a pointer but it's now being
2600 // dereferenced. e.g.
2601 // define @foo(%struct.X* %A) {
2602 // tail call @bar(%struct.X* byval %A)
2605 SDValue Ptr = Ld->getBasePtr();
2606 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2609 FI = FINode->getIndex();
2610 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2611 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2612 FI = FINode->getIndex();
2613 Bytes = Flags.getByValSize();
2617 assert(FI != INT_MAX);
2618 if (!MFI->isFixedObjectIndex(FI))
2620 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2623 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2624 /// for tail call optimization. Targets which want to do tail call
2625 /// optimization should implement this function.
2627 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2628 CallingConv::ID CalleeCC,
2630 bool isCalleeStructRet,
2631 bool isCallerStructRet,
2632 const SmallVectorImpl<ISD::OutputArg> &Outs,
2633 const SmallVectorImpl<SDValue> &OutVals,
2634 const SmallVectorImpl<ISD::InputArg> &Ins,
2635 SelectionDAG& DAG) const {
2636 if (!IsTailCallConvention(CalleeCC) &&
2637 CalleeCC != CallingConv::C)
2640 // If -tailcallopt is specified, make fastcc functions tail-callable.
2641 const MachineFunction &MF = DAG.getMachineFunction();
2642 const Function *CallerF = DAG.getMachineFunction().getFunction();
2643 CallingConv::ID CallerCC = CallerF->getCallingConv();
2644 bool CCMatch = CallerCC == CalleeCC;
2646 if (GuaranteedTailCallOpt) {
2647 if (IsTailCallConvention(CalleeCC) && CCMatch)
2652 // Look for obvious safe cases to perform tail call optimization that do not
2653 // require ABI changes. This is what gcc calls sibcall.
2655 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2656 // emit a special epilogue.
2657 if (RegInfo->needsStackRealignment(MF))
2660 // Also avoid sibcall optimization if either caller or callee uses struct
2661 // return semantics.
2662 if (isCalleeStructRet || isCallerStructRet)
2665 // An stdcall caller is expected to clean up its arguments; the callee
2666 // isn't going to do that.
2667 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2670 // Do not sibcall optimize vararg calls unless all arguments are passed via
2672 if (isVarArg && !Outs.empty()) {
2674 // Optimizing for varargs on Win64 is unlikely to be safe without
2675 // additional testing.
2676 if (Subtarget->isTargetWin64())
2679 SmallVector<CCValAssign, 16> ArgLocs;
2680 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2681 getTargetMachine(), ArgLocs, *DAG.getContext());
2683 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2684 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2685 if (!ArgLocs[i].isRegLoc())
2689 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2690 // Therefore if it's not used by the call it is not safe to optimize this into
2692 bool Unused = false;
2693 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2700 SmallVector<CCValAssign, 16> RVLocs;
2701 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2702 getTargetMachine(), RVLocs, *DAG.getContext());
2703 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2704 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2705 CCValAssign &VA = RVLocs[i];
2706 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2711 // If the calling conventions do not match, then we'd better make sure the
2712 // results are returned in the same way as what the caller expects.
2714 SmallVector<CCValAssign, 16> RVLocs1;
2715 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2716 getTargetMachine(), RVLocs1, *DAG.getContext());
2717 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2719 SmallVector<CCValAssign, 16> RVLocs2;
2720 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2721 getTargetMachine(), RVLocs2, *DAG.getContext());
2722 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2724 if (RVLocs1.size() != RVLocs2.size())
2726 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2727 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2729 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2731 if (RVLocs1[i].isRegLoc()) {
2732 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2735 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2741 // If the callee takes no arguments then go on to check the results of the
2743 if (!Outs.empty()) {
2744 // Check if stack adjustment is needed. For now, do not do this if any
2745 // argument is passed on the stack.
2746 SmallVector<CCValAssign, 16> ArgLocs;
2747 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2748 getTargetMachine(), ArgLocs, *DAG.getContext());
2750 // Allocate shadow area for Win64
2751 if (Subtarget->isTargetWin64()) {
2752 CCInfo.AllocateStack(32, 8);
2755 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2756 if (CCInfo.getNextStackOffset()) {
2757 MachineFunction &MF = DAG.getMachineFunction();
2758 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2761 // Check if the arguments are already laid out in the right way as
2762 // the caller's fixed stack objects.
2763 MachineFrameInfo *MFI = MF.getFrameInfo();
2764 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2765 const X86InstrInfo *TII =
2766 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2767 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2768 CCValAssign &VA = ArgLocs[i];
2769 SDValue Arg = OutVals[i];
2770 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2771 if (VA.getLocInfo() == CCValAssign::Indirect)
2773 if (!VA.isRegLoc()) {
2774 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2781 // If the tailcall address may be in a register, then make sure it's
2782 // possible to register allocate for it. In 32-bit, the call address can
2783 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2784 // callee-saved registers are restored. These happen to be the same
2785 // registers used to pass 'inreg' arguments so watch out for those.
2786 if (!Subtarget->is64Bit() &&
2787 !isa<GlobalAddressSDNode>(Callee) &&
2788 !isa<ExternalSymbolSDNode>(Callee)) {
2789 unsigned NumInRegs = 0;
2790 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2791 CCValAssign &VA = ArgLocs[i];
2794 unsigned Reg = VA.getLocReg();
2797 case X86::EAX: case X86::EDX: case X86::ECX:
2798 if (++NumInRegs == 3)
2810 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2811 return X86::createFastISel(funcInfo);
2815 //===----------------------------------------------------------------------===//
2816 // Other Lowering Hooks
2817 //===----------------------------------------------------------------------===//
2819 static bool MayFoldLoad(SDValue Op) {
2820 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2823 static bool MayFoldIntoStore(SDValue Op) {
2824 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2827 static bool isTargetShuffle(unsigned Opcode) {
2829 default: return false;
2830 case X86ISD::PSHUFD:
2831 case X86ISD::PSHUFHW:
2832 case X86ISD::PSHUFLW:
2833 case X86ISD::SHUFPD:
2834 case X86ISD::PALIGN:
2835 case X86ISD::SHUFPS:
2836 case X86ISD::MOVLHPS:
2837 case X86ISD::MOVLHPD:
2838 case X86ISD::MOVHLPS:
2839 case X86ISD::MOVLPS:
2840 case X86ISD::MOVLPD:
2841 case X86ISD::MOVSHDUP:
2842 case X86ISD::MOVSLDUP:
2843 case X86ISD::MOVDDUP:
2846 case X86ISD::UNPCKLPS:
2847 case X86ISD::UNPCKLPD:
2848 case X86ISD::VUNPCKLPSY:
2849 case X86ISD::VUNPCKLPDY:
2850 case X86ISD::PUNPCKLWD:
2851 case X86ISD::PUNPCKLBW:
2852 case X86ISD::PUNPCKLDQ:
2853 case X86ISD::PUNPCKLQDQ:
2854 case X86ISD::VPUNPCKLWDY:
2855 case X86ISD::VPUNPCKLBWY:
2856 case X86ISD::VPUNPCKLDQY:
2857 case X86ISD::VPUNPCKLQDQY:
2858 case X86ISD::UNPCKHPS:
2859 case X86ISD::UNPCKHPD:
2860 case X86ISD::VUNPCKHPSY:
2861 case X86ISD::VUNPCKHPDY:
2862 case X86ISD::PUNPCKHWD:
2863 case X86ISD::PUNPCKHBW:
2864 case X86ISD::PUNPCKHDQ:
2865 case X86ISD::PUNPCKHQDQ:
2866 case X86ISD::VPUNPCKHWDY:
2867 case X86ISD::VPUNPCKHBWY:
2868 case X86ISD::VPUNPCKHDQY:
2869 case X86ISD::VPUNPCKHQDQY:
2870 case X86ISD::VPERMILPS:
2871 case X86ISD::VPERMILPSY:
2872 case X86ISD::VPERMILPD:
2873 case X86ISD::VPERMILPDY:
2874 case X86ISD::VPERM2F128:
2880 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2881 SDValue V1, SelectionDAG &DAG) {
2883 default: llvm_unreachable("Unknown x86 shuffle node");
2884 case X86ISD::MOVSHDUP:
2885 case X86ISD::MOVSLDUP:
2886 case X86ISD::MOVDDUP:
2887 return DAG.getNode(Opc, dl, VT, V1);
2893 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2894 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2896 default: llvm_unreachable("Unknown x86 shuffle node");
2897 case X86ISD::PSHUFD:
2898 case X86ISD::PSHUFHW:
2899 case X86ISD::PSHUFLW:
2900 case X86ISD::VPERMILPS:
2901 case X86ISD::VPERMILPSY:
2902 case X86ISD::VPERMILPD:
2903 case X86ISD::VPERMILPDY:
2904 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2910 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2911 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2913 default: llvm_unreachable("Unknown x86 shuffle node");
2914 case X86ISD::PALIGN:
2915 case X86ISD::SHUFPD:
2916 case X86ISD::SHUFPS:
2917 case X86ISD::VPERM2F128:
2918 return DAG.getNode(Opc, dl, VT, V1, V2,
2919 DAG.getConstant(TargetMask, MVT::i8));
2924 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2925 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2927 default: llvm_unreachable("Unknown x86 shuffle node");
2928 case X86ISD::MOVLHPS:
2929 case X86ISD::MOVLHPD:
2930 case X86ISD::MOVHLPS:
2931 case X86ISD::MOVLPS:
2932 case X86ISD::MOVLPD:
2935 case X86ISD::UNPCKLPS:
2936 case X86ISD::UNPCKLPD:
2937 case X86ISD::VUNPCKLPSY:
2938 case X86ISD::VUNPCKLPDY:
2939 case X86ISD::PUNPCKLWD:
2940 case X86ISD::PUNPCKLBW:
2941 case X86ISD::PUNPCKLDQ:
2942 case X86ISD::PUNPCKLQDQ:
2943 case X86ISD::VPUNPCKLWDY:
2944 case X86ISD::VPUNPCKLBWY:
2945 case X86ISD::VPUNPCKLDQY:
2946 case X86ISD::VPUNPCKLQDQY:
2947 case X86ISD::UNPCKHPS:
2948 case X86ISD::UNPCKHPD:
2949 case X86ISD::VUNPCKHPSY:
2950 case X86ISD::VUNPCKHPDY:
2951 case X86ISD::PUNPCKHWD:
2952 case X86ISD::PUNPCKHBW:
2953 case X86ISD::PUNPCKHDQ:
2954 case X86ISD::PUNPCKHQDQ:
2955 case X86ISD::VPUNPCKHWDY:
2956 case X86ISD::VPUNPCKHBWY:
2957 case X86ISD::VPUNPCKHDQY:
2958 case X86ISD::VPUNPCKHQDQY:
2959 return DAG.getNode(Opc, dl, VT, V1, V2);
2964 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2965 MachineFunction &MF = DAG.getMachineFunction();
2966 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2967 int ReturnAddrIndex = FuncInfo->getRAIndex();
2969 if (ReturnAddrIndex == 0) {
2970 // Set up a frame object for the return address.
2971 uint64_t SlotSize = TD->getPointerSize();
2972 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2974 FuncInfo->setRAIndex(ReturnAddrIndex);
2977 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2981 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2982 bool hasSymbolicDisplacement) {
2983 // Offset should fit into 32 bit immediate field.
2984 if (!isInt<32>(Offset))
2987 // If we don't have a symbolic displacement - we don't have any extra
2989 if (!hasSymbolicDisplacement)
2992 // FIXME: Some tweaks might be needed for medium code model.
2993 if (M != CodeModel::Small && M != CodeModel::Kernel)
2996 // For small code model we assume that latest object is 16MB before end of 31
2997 // bits boundary. We may also accept pretty large negative constants knowing
2998 // that all objects are in the positive half of address space.
2999 if (M == CodeModel::Small && Offset < 16*1024*1024)
3002 // For kernel code model we know that all object resist in the negative half
3003 // of 32bits address space. We may not accept negative offsets, since they may
3004 // be just off and we may accept pretty large positive ones.
3005 if (M == CodeModel::Kernel && Offset > 0)
3011 /// isCalleePop - Determines whether the callee is required to pop its
3012 /// own arguments. Callee pop is necessary to support tail calls.
3013 bool X86::isCalleePop(CallingConv::ID CallingConv,
3014 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3018 switch (CallingConv) {
3021 case CallingConv::X86_StdCall:
3023 case CallingConv::X86_FastCall:
3025 case CallingConv::X86_ThisCall:
3027 case CallingConv::Fast:
3029 case CallingConv::GHC:
3034 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3035 /// specific condition code, returning the condition code and the LHS/RHS of the
3036 /// comparison to make.
3037 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3038 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3040 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3041 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3042 // X > -1 -> X == 0, jump !sign.
3043 RHS = DAG.getConstant(0, RHS.getValueType());
3044 return X86::COND_NS;
3045 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3046 // X < 0 -> X == 0, jump on sign.
3048 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3050 RHS = DAG.getConstant(0, RHS.getValueType());
3051 return X86::COND_LE;
3055 switch (SetCCOpcode) {
3056 default: llvm_unreachable("Invalid integer condition!");
3057 case ISD::SETEQ: return X86::COND_E;
3058 case ISD::SETGT: return X86::COND_G;
3059 case ISD::SETGE: return X86::COND_GE;
3060 case ISD::SETLT: return X86::COND_L;
3061 case ISD::SETLE: return X86::COND_LE;
3062 case ISD::SETNE: return X86::COND_NE;
3063 case ISD::SETULT: return X86::COND_B;
3064 case ISD::SETUGT: return X86::COND_A;
3065 case ISD::SETULE: return X86::COND_BE;
3066 case ISD::SETUGE: return X86::COND_AE;
3070 // First determine if it is required or is profitable to flip the operands.
3072 // If LHS is a foldable load, but RHS is not, flip the condition.
3073 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3074 !ISD::isNON_EXTLoad(RHS.getNode())) {
3075 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3076 std::swap(LHS, RHS);
3079 switch (SetCCOpcode) {
3085 std::swap(LHS, RHS);
3089 // On a floating point condition, the flags are set as follows:
3091 // 0 | 0 | 0 | X > Y
3092 // 0 | 0 | 1 | X < Y
3093 // 1 | 0 | 0 | X == Y
3094 // 1 | 1 | 1 | unordered
3095 switch (SetCCOpcode) {
3096 default: llvm_unreachable("Condcode should be pre-legalized away");
3098 case ISD::SETEQ: return X86::COND_E;
3099 case ISD::SETOLT: // flipped
3101 case ISD::SETGT: return X86::COND_A;
3102 case ISD::SETOLE: // flipped
3104 case ISD::SETGE: return X86::COND_AE;
3105 case ISD::SETUGT: // flipped
3107 case ISD::SETLT: return X86::COND_B;
3108 case ISD::SETUGE: // flipped
3110 case ISD::SETLE: return X86::COND_BE;
3112 case ISD::SETNE: return X86::COND_NE;
3113 case ISD::SETUO: return X86::COND_P;
3114 case ISD::SETO: return X86::COND_NP;
3116 case ISD::SETUNE: return X86::COND_INVALID;
3120 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3121 /// code. Current x86 isa includes the following FP cmov instructions:
3122 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3123 static bool hasFPCMov(unsigned X86CC) {
3139 /// isFPImmLegal - Returns true if the target can instruction select the
3140 /// specified FP immediate natively. If false, the legalizer will
3141 /// materialize the FP immediate as a load from a constant pool.
3142 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3143 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3144 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3150 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3151 /// the specified range (L, H].
3152 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3153 return (Val < 0) || (Val >= Low && Val < Hi);
3156 /// isUndefOrInRange - Return true if every element in Mask, begining
3157 /// from position Pos and ending in Pos+Size, falls within the specified
3158 /// range (L, L+Pos]. or is undef.
3159 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3160 int Pos, int Size, int Low, int Hi) {
3161 for (int i = Pos, e = Pos+Size; i != e; ++i)
3162 if (!isUndefOrInRange(Mask[i], Low, Hi))
3167 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3168 /// specified value.
3169 static bool isUndefOrEqual(int Val, int CmpVal) {
3170 if (Val < 0 || Val == CmpVal)
3175 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3176 /// from position Pos and ending in Pos+Size, falls within the specified
3177 /// sequential range (L, L+Pos]. or is undef.
3178 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3179 int Pos, int Size, int Low) {
3180 for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3181 if (!isUndefOrEqual(Mask[i], Low))
3186 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3187 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3188 /// the second operand.
3189 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3190 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3191 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3192 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3193 return (Mask[0] < 2 && Mask[1] < 2);
3197 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3198 SmallVector<int, 8> M;
3200 return ::isPSHUFDMask(M, N->getValueType(0));
3203 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3204 /// is suitable for input to PSHUFHW.
3205 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3206 if (VT != MVT::v8i16)
3209 // Lower quadword copied in order or undef.
3210 for (int i = 0; i != 4; ++i)
3211 if (Mask[i] >= 0 && Mask[i] != i)
3214 // Upper quadword shuffled.
3215 for (int i = 4; i != 8; ++i)
3216 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3222 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3223 SmallVector<int, 8> M;
3225 return ::isPSHUFHWMask(M, N->getValueType(0));
3228 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3229 /// is suitable for input to PSHUFLW.
3230 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3231 if (VT != MVT::v8i16)
3234 // Upper quadword copied in order.
3235 for (int i = 4; i != 8; ++i)
3236 if (Mask[i] >= 0 && Mask[i] != i)
3239 // Lower quadword shuffled.
3240 for (int i = 0; i != 4; ++i)
3247 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3248 SmallVector<int, 8> M;
3250 return ::isPSHUFLWMask(M, N->getValueType(0));
3253 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3254 /// is suitable for input to PALIGNR.
3255 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3256 bool hasSSSE3OrAVX) {
3257 int i, e = VT.getVectorNumElements();
3258 if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3261 // Do not handle v2i64 / v2f64 shuffles with palignr.
3262 if (e < 4 || !hasSSSE3OrAVX)
3265 for (i = 0; i != e; ++i)
3269 // All undef, not a palignr.
3273 // Make sure we're shifting in the right direction.
3277 int s = Mask[i] - i;
3279 // Check the rest of the elements to see if they are consecutive.
3280 for (++i; i != e; ++i) {
3282 if (m >= 0 && m != s+i)
3288 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3289 /// specifies a shuffle of elements that is suitable for input to 256-bit
3291 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3292 const X86Subtarget *Subtarget) {
3293 int NumElems = VT.getVectorNumElements();
3295 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3301 // VSHUFPSY divides the resulting vector into 4 chunks.
3302 // The sources are also splitted into 4 chunks, and each destination
3303 // chunk must come from a different source chunk.
3305 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3306 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3308 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3309 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3311 int QuarterSize = NumElems/4;
3312 int HalfSize = QuarterSize*2;
3313 for (int i = 0; i < QuarterSize; ++i)
3314 if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3316 for (int i = QuarterSize; i < QuarterSize*2; ++i)
3317 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3320 // The mask of the second half must be the same as the first but with
3321 // the appropriate offsets. This works in the same way as VPERMILPS
3322 // works with masks.
3323 for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3324 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3326 int FstHalfIdx = i-HalfSize;
3327 if (Mask[FstHalfIdx] < 0)
3329 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3332 for (int i = QuarterSize*3; i < NumElems; ++i) {
3333 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3335 int FstHalfIdx = i-HalfSize;
3336 if (Mask[FstHalfIdx] < 0)
3338 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3346 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3347 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3348 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3349 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3350 EVT VT = SVOp->getValueType(0);
3351 int NumElems = VT.getVectorNumElements();
3353 assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3354 "Only supports v8i32 and v8f32 types");
3356 int HalfSize = NumElems/2;
3358 for (int i = 0; i != NumElems ; ++i) {
3359 if (SVOp->getMaskElt(i) < 0)
3361 // The mask of the first half must be equal to the second one.
3362 unsigned Shamt = (i%HalfSize)*2;
3363 unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3364 Mask |= Elt << Shamt;
3370 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3371 /// specifies a shuffle of elements that is suitable for input to 256-bit
3372 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3373 /// version and the mask of the second half isn't binded with the first
3375 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3376 const X86Subtarget *Subtarget) {
3377 int NumElems = VT.getVectorNumElements();
3379 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3385 // VSHUFPSY divides the resulting vector into 4 chunks.
3386 // The sources are also splitted into 4 chunks, and each destination
3387 // chunk must come from a different source chunk.
3389 // SRC1 => X3 X2 X1 X0
3390 // SRC2 => Y3 Y2 Y1 Y0
3392 // DST => Y2..Y3, X2..X3, Y1..Y0, X1..X0
3394 int QuarterSize = NumElems/4;
3395 int HalfSize = QuarterSize*2;
3396 for (int i = 0; i < QuarterSize; ++i)
3397 if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3399 for (int i = QuarterSize; i < QuarterSize*2; ++i)
3400 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3402 for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3403 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3405 for (int i = QuarterSize*3; i < NumElems; ++i)
3406 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3412 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3413 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3414 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3415 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3416 EVT VT = SVOp->getValueType(0);
3417 int NumElems = VT.getVectorNumElements();
3419 assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3420 "Only supports v4i64 and v4f64 types");
3422 int HalfSize = NumElems/2;
3424 for (int i = 0; i != NumElems ; ++i) {
3425 if (SVOp->getMaskElt(i) < 0)
3427 int Elt = SVOp->getMaskElt(i) % HalfSize;
3434 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3435 /// the two vector operands have swapped position.
3436 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3437 unsigned NumElems = VT.getVectorNumElements();
3438 for (unsigned i = 0; i != NumElems; ++i) {
3442 else if (idx < (int)NumElems)
3443 Mask[i] = idx + NumElems;
3445 Mask[i] = idx - NumElems;
3449 /// isCommutedVSHUFP() - Return true if swapping operands will
3450 /// allow to use the "vshufpd" or "vshufps" instruction
3451 /// for 256-bit vectors
3452 static bool isCommutedVSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3453 const X86Subtarget *Subtarget) {
3455 unsigned NumElems = VT.getVectorNumElements();
3456 if ((VT.getSizeInBits() != 256) || ((NumElems != 4) && (NumElems != 8)))
3459 SmallVector<int, 8> CommutedMask;
3460 for (unsigned i = 0; i < NumElems; ++i)
3461 CommutedMask.push_back(Mask[i]);
3463 CommuteVectorShuffleMask(CommutedMask, VT);
3464 return (NumElems == 4) ? isVSHUFPDYMask(CommutedMask, VT, Subtarget):
3465 isVSHUFPSYMask(CommutedMask, VT, Subtarget);
3469 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3470 /// specifies a shuffle of elements that is suitable for input to 128-bit
3471 /// SHUFPS and SHUFPD.
3472 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3473 int NumElems = VT.getVectorNumElements();
3475 if (VT.getSizeInBits() != 128)
3478 if (NumElems != 2 && NumElems != 4)
3481 int Half = NumElems / 2;
3482 for (int i = 0; i < Half; ++i)
3483 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3485 for (int i = Half; i < NumElems; ++i)
3486 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3492 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3493 SmallVector<int, 8> M;
3495 return ::isSHUFPMask(M, N->getValueType(0));
3498 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3499 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3500 /// half elements to come from vector 1 (which would equal the dest.) and
3501 /// the upper half to come from vector 2.
3502 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3503 int NumElems = VT.getVectorNumElements();
3505 if (NumElems != 2 && NumElems != 4)
3508 int Half = NumElems / 2;
3509 for (int i = 0; i < Half; ++i)
3510 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3512 for (int i = Half; i < NumElems; ++i)
3513 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3518 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3519 SmallVector<int, 8> M;
3521 return isCommutedSHUFPMask(M, N->getValueType(0));
3524 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3525 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3526 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3527 EVT VT = N->getValueType(0);
3528 unsigned NumElems = VT.getVectorNumElements();
3530 if (VT.getSizeInBits() != 128)
3536 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3537 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3538 isUndefOrEqual(N->getMaskElt(1), 7) &&
3539 isUndefOrEqual(N->getMaskElt(2), 2) &&
3540 isUndefOrEqual(N->getMaskElt(3), 3);
3543 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3544 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3546 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3547 EVT VT = N->getValueType(0);
3548 unsigned NumElems = VT.getVectorNumElements();
3550 if (VT.getSizeInBits() != 128)
3556 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3557 isUndefOrEqual(N->getMaskElt(1), 3) &&
3558 isUndefOrEqual(N->getMaskElt(2), 2) &&
3559 isUndefOrEqual(N->getMaskElt(3), 3);
3562 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3563 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3564 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3565 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3567 if (NumElems != 2 && NumElems != 4)
3570 for (unsigned i = 0; i < NumElems/2; ++i)
3571 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3574 for (unsigned i = NumElems/2; i < NumElems; ++i)
3575 if (!isUndefOrEqual(N->getMaskElt(i), i))
3581 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3582 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3583 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3584 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3586 if ((NumElems != 2 && NumElems != 4)
3587 || N->getValueType(0).getSizeInBits() > 128)
3590 for (unsigned i = 0; i < NumElems/2; ++i)
3591 if (!isUndefOrEqual(N->getMaskElt(i), i))
3594 for (unsigned i = 0; i < NumElems/2; ++i)
3595 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3601 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3602 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3603 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3604 bool HasAVX2, bool V2IsSplat = false) {
3605 int NumElts = VT.getVectorNumElements();
3607 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3608 "Unsupported vector type for unpckh");
3610 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3611 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3614 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3615 // independently on 128-bit lanes.
3616 unsigned NumLanes = VT.getSizeInBits()/128;
3617 unsigned NumLaneElts = NumElts/NumLanes;
3620 unsigned End = NumLaneElts;
3621 for (unsigned s = 0; s < NumLanes; ++s) {
3622 for (unsigned i = Start, j = s * NumLaneElts;
3626 int BitI1 = Mask[i+1];
3627 if (!isUndefOrEqual(BitI, j))
3630 if (!isUndefOrEqual(BitI1, NumElts))
3633 if (!isUndefOrEqual(BitI1, j + NumElts))
3637 // Process the next 128 bits.
3638 Start += NumLaneElts;
3645 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3646 SmallVector<int, 8> M;
3648 return ::isUNPCKLMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3651 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3652 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3653 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3654 bool HasAVX2, bool V2IsSplat = false) {
3655 int NumElts = VT.getVectorNumElements();
3657 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3658 "Unsupported vector type for unpckh");
3660 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3661 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3664 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3665 // independently on 128-bit lanes.
3666 unsigned NumLanes = VT.getSizeInBits()/128;
3667 unsigned NumLaneElts = NumElts/NumLanes;
3670 unsigned End = NumLaneElts;
3671 for (unsigned l = 0; l != NumLanes; ++l) {
3672 for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3673 i != End; i += 2, ++j) {
3675 int BitI1 = Mask[i+1];
3676 if (!isUndefOrEqual(BitI, j))
3679 if (isUndefOrEqual(BitI1, NumElts))
3682 if (!isUndefOrEqual(BitI1, j+NumElts))
3686 // Process the next 128 bits.
3687 Start += NumLaneElts;
3693 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3694 SmallVector<int, 8> M;
3696 return ::isUNPCKHMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3699 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3700 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3702 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3703 int NumElems = VT.getVectorNumElements();
3704 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3707 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3708 // FIXME: Need a better way to get rid of this, there's no latency difference
3709 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3710 // the former later. We should also remove the "_undef" special mask.
3711 if (NumElems == 4 && VT.getSizeInBits() == 256)
3714 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3715 // independently on 128-bit lanes.
3716 unsigned NumLanes = VT.getSizeInBits() / 128;
3717 unsigned NumLaneElts = NumElems / NumLanes;
3719 for (unsigned s = 0; s < NumLanes; ++s) {
3720 for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3721 i != NumLaneElts * (s + 1);
3724 int BitI1 = Mask[i+1];
3726 if (!isUndefOrEqual(BitI, j))
3728 if (!isUndefOrEqual(BitI1, j))
3736 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3737 SmallVector<int, 8> M;
3739 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3742 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3743 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3745 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3746 int NumElems = VT.getVectorNumElements();
3747 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3750 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3752 int BitI1 = Mask[i+1];
3753 if (!isUndefOrEqual(BitI, j))
3755 if (!isUndefOrEqual(BitI1, j))
3761 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3762 SmallVector<int, 8> M;
3764 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3767 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3768 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3769 /// MOVSD, and MOVD, i.e. setting the lowest element.
3770 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3771 if (VT.getVectorElementType().getSizeInBits() < 32)
3774 int NumElts = VT.getVectorNumElements();
3776 if (!isUndefOrEqual(Mask[0], NumElts))
3779 for (int i = 1; i < NumElts; ++i)
3780 if (!isUndefOrEqual(Mask[i], i))
3786 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3787 SmallVector<int, 8> M;
3789 return ::isMOVLMask(M, N->getValueType(0));
3792 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3793 /// as permutations between 128-bit chunks or halves. As an example: this
3795 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3796 /// The first half comes from the second half of V1 and the second half from the
3797 /// the second half of V2.
3798 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3799 const X86Subtarget *Subtarget) {
3800 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3803 // The shuffle result is divided into half A and half B. In total the two
3804 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3805 // B must come from C, D, E or F.
3806 int HalfSize = VT.getVectorNumElements()/2;
3807 bool MatchA = false, MatchB = false;
3809 // Check if A comes from one of C, D, E, F.
3810 for (int Half = 0; Half < 4; ++Half) {
3811 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3817 // Check if B comes from one of C, D, E, F.
3818 for (int Half = 0; Half < 4; ++Half) {
3819 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3825 return MatchA && MatchB;
3828 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3829 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3830 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3831 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3832 EVT VT = SVOp->getValueType(0);
3834 int HalfSize = VT.getVectorNumElements()/2;
3836 int FstHalf = 0, SndHalf = 0;
3837 for (int i = 0; i < HalfSize; ++i) {
3838 if (SVOp->getMaskElt(i) > 0) {
3839 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3843 for (int i = HalfSize; i < HalfSize*2; ++i) {
3844 if (SVOp->getMaskElt(i) > 0) {
3845 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3850 return (FstHalf | (SndHalf << 4));
3853 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3854 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3855 /// Note that VPERMIL mask matching is different depending whether theunderlying
3856 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3857 /// to the same elements of the low, but to the higher half of the source.
3858 /// In VPERMILPD the two lanes could be shuffled independently of each other
3859 /// with the same restriction that lanes can't be crossed.
3860 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3861 const X86Subtarget *Subtarget) {
3862 int NumElts = VT.getVectorNumElements();
3863 int NumLanes = VT.getSizeInBits()/128;
3865 if (!Subtarget->hasAVX())
3868 // Only match 256-bit with 64-bit types
3869 if (VT.getSizeInBits() != 256 || NumElts != 4)
3872 // The mask on the high lane is independent of the low. Both can match
3873 // any element in inside its own lane, but can't cross.
3874 int LaneSize = NumElts/NumLanes;
3875 for (int l = 0; l < NumLanes; ++l)
3876 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3877 int LaneStart = l*LaneSize;
3878 if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3885 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3886 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3887 /// Note that VPERMIL mask matching is different depending whether theunderlying
3888 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3889 /// to the same elements of the low, but to the higher half of the source.
3890 /// In VPERMILPD the two lanes could be shuffled independently of each other
3891 /// with the same restriction that lanes can't be crossed.
3892 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3893 const X86Subtarget *Subtarget) {
3894 unsigned NumElts = VT.getVectorNumElements();
3895 unsigned NumLanes = VT.getSizeInBits()/128;
3897 if (!Subtarget->hasAVX())
3900 // Only match 256-bit with 32-bit types
3901 if (VT.getSizeInBits() != 256 || NumElts != 8)
3904 // The mask on the high lane should be the same as the low. Actually,
3905 // they can differ if any of the corresponding index in a lane is undef
3906 // and the other stays in range.
3907 int LaneSize = NumElts/NumLanes;
3908 for (int i = 0; i < LaneSize; ++i) {
3909 int HighElt = i+LaneSize;
3910 bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3911 bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3913 if (!HighValid || !LowValid)
3915 if (Mask[i] < 0 || Mask[HighElt] < 0)
3917 if (Mask[HighElt]-Mask[i] != LaneSize)
3924 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3925 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3926 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3927 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3928 EVT VT = SVOp->getValueType(0);
3930 int NumElts = VT.getVectorNumElements();
3931 int NumLanes = VT.getSizeInBits()/128;
3932 int LaneSize = NumElts/NumLanes;
3934 // Although the mask is equal for both lanes do it twice to get the cases
3935 // where a mask will match because the same mask element is undef on the
3936 // first half but valid on the second. This would get pathological cases
3937 // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3939 for (int l = 0; l < NumLanes; ++l) {
3940 for (int i = 0; i < LaneSize; ++i) {
3941 int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3944 if (MaskElt >= LaneSize)
3945 MaskElt -= LaneSize;
3946 Mask |= MaskElt << (i*2);
3953 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3954 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3955 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3956 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3957 EVT VT = SVOp->getValueType(0);
3959 int NumElts = VT.getVectorNumElements();
3960 int NumLanes = VT.getSizeInBits()/128;
3963 int LaneSize = NumElts/NumLanes;
3964 for (int l = 0; l < NumLanes; ++l)
3965 for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3966 int MaskElt = SVOp->getMaskElt(i);
3969 Mask |= (MaskElt-l*LaneSize) << i;
3975 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3976 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3977 /// element of vector 2 and the other elements to come from vector 1 in order.
3978 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3979 bool V2IsSplat = false, bool V2IsUndef = false) {
3980 int NumOps = VT.getVectorNumElements();
3981 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3984 if (!isUndefOrEqual(Mask[0], 0))
3987 for (int i = 1; i < NumOps; ++i)
3988 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3989 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3990 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3996 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3997 bool V2IsUndef = false) {
3998 SmallVector<int, 8> M;
4000 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
4003 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4004 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4005 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4006 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
4007 const X86Subtarget *Subtarget) {
4008 if (!Subtarget->hasSSE3orAVX())
4011 // The second vector must be undef
4012 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
4015 EVT VT = N->getValueType(0);
4016 unsigned NumElems = VT.getVectorNumElements();
4018 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
4019 (VT.getSizeInBits() == 256 && NumElems != 8))
4022 // "i+1" is the value the indexed mask element must have
4023 for (unsigned i = 0; i < NumElems; i += 2)
4024 if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
4025 !isUndefOrEqual(N->getMaskElt(i+1), i+1))
4031 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4032 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4033 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4034 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
4035 const X86Subtarget *Subtarget) {
4036 if (!Subtarget->hasSSE3orAVX())
4039 // The second vector must be undef
4040 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
4043 EVT VT = N->getValueType(0);
4044 unsigned NumElems = VT.getVectorNumElements();
4046 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
4047 (VT.getSizeInBits() == 256 && NumElems != 8))
4050 // "i" is the value the indexed mask element must have
4051 for (unsigned i = 0; i < NumElems; i += 2)
4052 if (!isUndefOrEqual(N->getMaskElt(i), i) ||
4053 !isUndefOrEqual(N->getMaskElt(i+1), i))
4059 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4060 /// specifies a shuffle of elements that is suitable for input to 256-bit
4061 /// version of MOVDDUP.
4062 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
4063 const X86Subtarget *Subtarget) {
4064 EVT VT = N->getValueType(0);
4065 int NumElts = VT.getVectorNumElements();
4066 bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
4068 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
4069 !V2IsUndef || NumElts != 4)
4072 for (int i = 0; i != NumElts/2; ++i)
4073 if (!isUndefOrEqual(N->getMaskElt(i), 0))
4075 for (int i = NumElts/2; i != NumElts; ++i)
4076 if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
4081 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4082 /// specifies a shuffle of elements that is suitable for input to 128-bit
4083 /// version of MOVDDUP.
4084 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
4085 EVT VT = N->getValueType(0);
4087 if (VT.getSizeInBits() != 128)
4090 int e = VT.getVectorNumElements() / 2;
4091 for (int i = 0; i < e; ++i)
4092 if (!isUndefOrEqual(N->getMaskElt(i), i))
4094 for (int i = 0; i < e; ++i)
4095 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
4100 /// isVEXTRACTF128Index - Return true if the specified
4101 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4102 /// suitable for input to VEXTRACTF128.
4103 bool X86::isVEXTRACTF128Index(SDNode *N) {
4104 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4107 // The index should be aligned on a 128-bit boundary.
4109 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4111 unsigned VL = N->getValueType(0).getVectorNumElements();
4112 unsigned VBits = N->getValueType(0).getSizeInBits();
4113 unsigned ElSize = VBits / VL;
4114 bool Result = (Index * ElSize) % 128 == 0;
4119 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4120 /// operand specifies a subvector insert that is suitable for input to
4122 bool X86::isVINSERTF128Index(SDNode *N) {
4123 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4126 // The index should be aligned on a 128-bit boundary.
4128 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4130 unsigned VL = N->getValueType(0).getVectorNumElements();
4131 unsigned VBits = N->getValueType(0).getSizeInBits();
4132 unsigned ElSize = VBits / VL;
4133 bool Result = (Index * ElSize) % 128 == 0;
4138 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4139 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4140 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4141 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4142 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4144 unsigned Shift = (NumOperands == 4) ? 2 : 1;
4146 for (int i = 0; i < NumOperands; ++i) {
4147 int Val = SVOp->getMaskElt(NumOperands-i-1);
4148 if (Val < 0) Val = 0;
4149 if (Val >= NumOperands) Val -= NumOperands;
4151 if (i != NumOperands - 1)
4157 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4158 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4159 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4160 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4162 // 8 nodes, but we only care about the last 4.
4163 for (unsigned i = 7; i >= 4; --i) {
4164 int Val = SVOp->getMaskElt(i);
4173 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4174 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4175 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4176 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4178 // 8 nodes, but we only care about the first 4.
4179 for (int i = 3; i >= 0; --i) {
4180 int Val = SVOp->getMaskElt(i);
4189 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4190 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4191 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4192 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4193 EVT VVT = N->getValueType(0);
4194 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4198 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4199 Val = SVOp->getMaskElt(i);
4203 assert(Val - i > 0 && "PALIGNR imm should be positive");
4204 return (Val - i) * EltSize;
4207 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4208 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4210 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4211 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4212 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4215 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4217 EVT VecVT = N->getOperand(0).getValueType();
4218 EVT ElVT = VecVT.getVectorElementType();
4220 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4221 return Index / NumElemsPerChunk;
4224 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4225 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4227 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4228 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4229 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4232 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4234 EVT VecVT = N->getValueType(0);
4235 EVT ElVT = VecVT.getVectorElementType();
4237 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4238 return Index / NumElemsPerChunk;
4241 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4243 bool X86::isZeroNode(SDValue Elt) {
4244 return ((isa<ConstantSDNode>(Elt) &&
4245 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4246 (isa<ConstantFPSDNode>(Elt) &&
4247 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4250 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4251 /// their permute mask.
4252 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4253 SelectionDAG &DAG) {
4254 EVT VT = SVOp->getValueType(0);
4255 unsigned NumElems = VT.getVectorNumElements();
4256 SmallVector<int, 8> MaskVec;
4258 for (unsigned i = 0; i != NumElems; ++i) {
4259 int idx = SVOp->getMaskElt(i);
4261 MaskVec.push_back(idx);
4262 else if (idx < (int)NumElems)
4263 MaskVec.push_back(idx + NumElems);
4265 MaskVec.push_back(idx - NumElems);
4267 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4268 SVOp->getOperand(0), &MaskVec[0]);
4271 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4272 /// match movhlps. The lower half elements should come from upper half of
4273 /// V1 (and in order), and the upper half elements should come from the upper
4274 /// half of V2 (and in order).
4275 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4276 EVT VT = Op->getValueType(0);
4277 if (VT.getSizeInBits() != 128)
4279 if (VT.getVectorNumElements() != 4)
4281 for (unsigned i = 0, e = 2; i != e; ++i)
4282 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4284 for (unsigned i = 2; i != 4; ++i)
4285 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4290 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4291 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4293 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4294 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4296 N = N->getOperand(0).getNode();
4297 if (!ISD::isNON_EXTLoad(N))
4300 *LD = cast<LoadSDNode>(N);
4304 // Test whether the given value is a vector value which will be legalized
4306 static bool WillBeConstantPoolLoad(SDNode *N) {
4307 if (N->getOpcode() != ISD::BUILD_VECTOR)
4310 // Check for any non-constant elements.
4311 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4312 switch (N->getOperand(i).getNode()->getOpcode()) {
4314 case ISD::ConstantFP:
4321 // Vectors of all-zeros and all-ones are materialized with special
4322 // instructions rather than being loaded.
4323 return !ISD::isBuildVectorAllZeros(N) &&
4324 !ISD::isBuildVectorAllOnes(N);
4327 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4328 /// match movlp{s|d}. The lower half elements should come from lower half of
4329 /// V1 (and in order), and the upper half elements should come from the upper
4330 /// half of V2 (and in order). And since V1 will become the source of the
4331 /// MOVLP, it must be either a vector load or a scalar load to vector.
4332 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4333 ShuffleVectorSDNode *Op) {
4334 EVT VT = Op->getValueType(0);
4335 if (VT.getSizeInBits() != 128)
4338 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4340 // Is V2 is a vector load, don't do this transformation. We will try to use
4341 // load folding shufps op.
4342 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4345 unsigned NumElems = VT.getVectorNumElements();
4347 if (NumElems != 2 && NumElems != 4)
4349 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4350 if (!isUndefOrEqual(Op->getMaskElt(i), i))
4352 for (unsigned i = NumElems/2; i != NumElems; ++i)
4353 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4358 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4360 static bool isSplatVector(SDNode *N) {
4361 if (N->getOpcode() != ISD::BUILD_VECTOR)
4364 SDValue SplatValue = N->getOperand(0);
4365 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4366 if (N->getOperand(i) != SplatValue)
4371 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4372 /// to an zero vector.
4373 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4374 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4375 SDValue V1 = N->getOperand(0);
4376 SDValue V2 = N->getOperand(1);
4377 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4378 for (unsigned i = 0; i != NumElems; ++i) {
4379 int Idx = N->getMaskElt(i);
4380 if (Idx >= (int)NumElems) {
4381 unsigned Opc = V2.getOpcode();
4382 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4384 if (Opc != ISD::BUILD_VECTOR ||
4385 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4387 } else if (Idx >= 0) {
4388 unsigned Opc = V1.getOpcode();
4389 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4391 if (Opc != ISD::BUILD_VECTOR ||
4392 !X86::isZeroNode(V1.getOperand(Idx)))
4399 /// getZeroVector - Returns a vector of specified type with all zero elements.
4401 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4403 assert(VT.isVector() && "Expected a vector type");
4405 // Always build SSE zero vectors as <4 x i32> bitcasted
4406 // to their dest type. This ensures they get CSE'd.
4408 if (VT.getSizeInBits() == 128) { // SSE
4409 if (HasXMMInt) { // SSE2
4410 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4411 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4413 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4414 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4416 } else if (VT.getSizeInBits() == 256) { // AVX
4417 // 256-bit logic and arithmetic instructions in AVX are
4418 // all floating-point, no support for integer ops. Default
4419 // to emitting fp zeroed vectors then.
4420 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4421 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4422 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4424 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4427 /// getOnesVector - Returns a vector of specified type with all bits set.
4428 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4429 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4430 /// Then bitcast to their original type, ensuring they get CSE'd.
4431 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4433 assert(VT.isVector() && "Expected a vector type");
4434 assert((VT.is128BitVector() || VT.is256BitVector())
4435 && "Expected a 128-bit or 256-bit vector type");
4437 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4439 if (VT.getSizeInBits() == 256) {
4440 if (HasAVX2) { // AVX2
4441 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4442 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4444 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4445 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4446 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4447 Vec = Insert128BitVector(InsV, Vec,
4448 DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4451 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4454 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4457 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4458 /// that point to V2 points to its first element.
4459 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4460 EVT VT = SVOp->getValueType(0);
4461 unsigned NumElems = VT.getVectorNumElements();
4463 bool Changed = false;
4464 SmallVector<int, 8> MaskVec;
4465 SVOp->getMask(MaskVec);
4467 for (unsigned i = 0; i != NumElems; ++i) {
4468 if (MaskVec[i] > (int)NumElems) {
4469 MaskVec[i] = NumElems;
4474 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4475 SVOp->getOperand(1), &MaskVec[0]);
4476 return SDValue(SVOp, 0);
4479 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4480 /// operation of specified width.
4481 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4483 unsigned NumElems = VT.getVectorNumElements();
4484 SmallVector<int, 8> Mask;
4485 Mask.push_back(NumElems);
4486 for (unsigned i = 1; i != NumElems; ++i)
4488 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4491 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4492 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4494 unsigned NumElems = VT.getVectorNumElements();
4495 SmallVector<int, 8> Mask;
4496 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4498 Mask.push_back(i + NumElems);
4500 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4503 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4504 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4506 unsigned NumElems = VT.getVectorNumElements();
4507 unsigned Half = NumElems/2;
4508 SmallVector<int, 8> Mask;
4509 for (unsigned i = 0; i != Half; ++i) {
4510 Mask.push_back(i + Half);
4511 Mask.push_back(i + NumElems + Half);
4513 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4516 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4517 // a generic shuffle instruction because the target has no such instructions.
4518 // Generate shuffles which repeat i16 and i8 several times until they can be
4519 // represented by v4f32 and then be manipulated by target suported shuffles.
4520 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4521 EVT VT = V.getValueType();
4522 int NumElems = VT.getVectorNumElements();
4523 DebugLoc dl = V.getDebugLoc();
4525 while (NumElems > 4) {
4526 if (EltNo < NumElems/2) {
4527 V = getUnpackl(DAG, dl, VT, V, V);
4529 V = getUnpackh(DAG, dl, VT, V, V);
4530 EltNo -= NumElems/2;
4537 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4538 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4539 EVT VT = V.getValueType();
4540 DebugLoc dl = V.getDebugLoc();
4541 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4542 && "Vector size not supported");
4544 if (VT.getSizeInBits() == 128) {
4545 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4546 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4547 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4550 // To use VPERMILPS to splat scalars, the second half of indicies must
4551 // refer to the higher part, which is a duplication of the lower one,
4552 // because VPERMILPS can only handle in-lane permutations.
4553 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4554 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4556 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4557 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4561 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4564 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4565 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4566 EVT SrcVT = SV->getValueType(0);
4567 SDValue V1 = SV->getOperand(0);
4568 DebugLoc dl = SV->getDebugLoc();
4570 int EltNo = SV->getSplatIndex();
4571 int NumElems = SrcVT.getVectorNumElements();
4572 unsigned Size = SrcVT.getSizeInBits();
4574 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4575 "Unknown how to promote splat for type");
4577 // Extract the 128-bit part containing the splat element and update
4578 // the splat element index when it refers to the higher register.
4580 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4581 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4583 EltNo -= NumElems/2;
4586 // All i16 and i8 vector types can't be used directly by a generic shuffle
4587 // instruction because the target has no such instruction. Generate shuffles
4588 // which repeat i16 and i8 several times until they fit in i32, and then can
4589 // be manipulated by target suported shuffles.
4590 EVT EltVT = SrcVT.getVectorElementType();
4591 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4592 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4594 // Recreate the 256-bit vector and place the same 128-bit vector
4595 // into the low and high part. This is necessary because we want
4596 // to use VPERM* to shuffle the vectors
4598 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4599 DAG.getConstant(0, MVT::i32), DAG, dl);
4600 V1 = Insert128BitVector(InsV, V1,
4601 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4604 return getLegalSplat(DAG, V1, EltNo);
4607 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4608 /// vector of zero or undef vector. This produces a shuffle where the low
4609 /// element of V2 is swizzled into the zero/undef vector, landing at element
4610 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4611 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4612 bool isZero, bool HasXMMInt,
4613 SelectionDAG &DAG) {
4614 EVT VT = V2.getValueType();
4616 ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4617 unsigned NumElems = VT.getVectorNumElements();
4618 SmallVector<int, 16> MaskVec;
4619 for (unsigned i = 0; i != NumElems; ++i)
4620 // If this is the insertion idx, put the low elt of V2 here.
4621 MaskVec.push_back(i == Idx ? NumElems : i);
4622 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4625 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4626 /// element of the result of the vector shuffle.
4627 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4630 return SDValue(); // Limit search depth.
4632 SDValue V = SDValue(N, 0);
4633 EVT VT = V.getValueType();
4634 unsigned Opcode = V.getOpcode();
4636 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4637 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4638 Index = SV->getMaskElt(Index);
4641 return DAG.getUNDEF(VT.getVectorElementType());
4643 int NumElems = VT.getVectorNumElements();
4644 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4645 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4648 // Recurse into target specific vector shuffles to find scalars.
4649 if (isTargetShuffle(Opcode)) {
4650 int NumElems = VT.getVectorNumElements();
4651 SmallVector<unsigned, 16> ShuffleMask;
4655 case X86ISD::SHUFPS:
4656 case X86ISD::SHUFPD:
4657 ImmN = N->getOperand(N->getNumOperands()-1);
4658 DecodeSHUFPSMask(NumElems,
4659 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4662 case X86ISD::PUNPCKHBW:
4663 case X86ISD::PUNPCKHWD:
4664 case X86ISD::PUNPCKHDQ:
4665 case X86ISD::PUNPCKHQDQ:
4666 case X86ISD::VPUNPCKHBWY:
4667 case X86ISD::VPUNPCKHWDY:
4668 case X86ISD::VPUNPCKHDQY:
4669 case X86ISD::VPUNPCKHQDQY:
4670 DecodePUNPCKHMask(NumElems, ShuffleMask);
4672 case X86ISD::UNPCKHPS:
4673 case X86ISD::UNPCKHPD:
4674 case X86ISD::VUNPCKHPSY:
4675 case X86ISD::VUNPCKHPDY:
4676 DecodeUNPCKHPMask(VT, ShuffleMask);
4678 case X86ISD::PUNPCKLBW:
4679 case X86ISD::PUNPCKLWD:
4680 case X86ISD::PUNPCKLDQ:
4681 case X86ISD::PUNPCKLQDQ:
4682 case X86ISD::VPUNPCKLBWY:
4683 case X86ISD::VPUNPCKLWDY:
4684 case X86ISD::VPUNPCKLDQY:
4685 case X86ISD::VPUNPCKLQDQY:
4686 DecodePUNPCKLMask(VT, ShuffleMask);
4688 case X86ISD::UNPCKLPS:
4689 case X86ISD::UNPCKLPD:
4690 case X86ISD::VUNPCKLPSY:
4691 case X86ISD::VUNPCKLPDY:
4692 DecodeUNPCKLPMask(VT, ShuffleMask);
4694 case X86ISD::MOVHLPS:
4695 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4697 case X86ISD::MOVLHPS:
4698 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4700 case X86ISD::PSHUFD:
4701 ImmN = N->getOperand(N->getNumOperands()-1);
4702 DecodePSHUFMask(NumElems,
4703 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4706 case X86ISD::PSHUFHW:
4707 ImmN = N->getOperand(N->getNumOperands()-1);
4708 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4711 case X86ISD::PSHUFLW:
4712 ImmN = N->getOperand(N->getNumOperands()-1);
4713 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4717 case X86ISD::MOVSD: {
4718 // The index 0 always comes from the first element of the second source,
4719 // this is why MOVSS and MOVSD are used in the first place. The other
4720 // elements come from the other positions of the first source vector.
4721 unsigned OpNum = (Index == 0) ? 1 : 0;
4722 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4725 case X86ISD::VPERMILPS:
4726 ImmN = N->getOperand(N->getNumOperands()-1);
4727 DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4730 case X86ISD::VPERMILPSY:
4731 ImmN = N->getOperand(N->getNumOperands()-1);
4732 DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4735 case X86ISD::VPERMILPD:
4736 ImmN = N->getOperand(N->getNumOperands()-1);
4737 DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4740 case X86ISD::VPERMILPDY:
4741 ImmN = N->getOperand(N->getNumOperands()-1);
4742 DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4745 case X86ISD::VPERM2F128:
4746 ImmN = N->getOperand(N->getNumOperands()-1);
4747 DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4750 case X86ISD::MOVDDUP:
4751 case X86ISD::MOVLHPD:
4752 case X86ISD::MOVLPD:
4753 case X86ISD::MOVLPS:
4754 case X86ISD::MOVSHDUP:
4755 case X86ISD::MOVSLDUP:
4756 case X86ISD::PALIGN:
4757 return SDValue(); // Not yet implemented.
4759 assert(0 && "unknown target shuffle node");
4763 Index = ShuffleMask[Index];
4765 return DAG.getUNDEF(VT.getVectorElementType());
4767 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4768 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4772 // Actual nodes that may contain scalar elements
4773 if (Opcode == ISD::BITCAST) {
4774 V = V.getOperand(0);
4775 EVT SrcVT = V.getValueType();
4776 unsigned NumElems = VT.getVectorNumElements();
4778 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4782 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4783 return (Index == 0) ? V.getOperand(0)
4784 : DAG.getUNDEF(VT.getVectorElementType());
4786 if (V.getOpcode() == ISD::BUILD_VECTOR)
4787 return V.getOperand(Index);
4792 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4793 /// shuffle operation which come from a consecutively from a zero. The
4794 /// search can start in two different directions, from left or right.
4796 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4797 bool ZerosFromLeft, SelectionDAG &DAG) {
4800 while (i < NumElems) {
4801 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4802 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4803 if (!(Elt.getNode() &&
4804 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4812 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4813 /// MaskE correspond consecutively to elements from one of the vector operands,
4814 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4816 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4817 int OpIdx, int NumElems, unsigned &OpNum) {
4818 bool SeenV1 = false;
4819 bool SeenV2 = false;
4821 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4822 int Idx = SVOp->getMaskElt(i);
4823 // Ignore undef indicies
4832 // Only accept consecutive elements from the same vector
4833 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4837 OpNum = SeenV1 ? 0 : 1;
4841 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4842 /// logical left shift of a vector.
4843 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4844 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4845 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4846 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4847 false /* check zeros from right */, DAG);
4853 // Considering the elements in the mask that are not consecutive zeros,
4854 // check if they consecutively come from only one of the source vectors.
4856 // V1 = {X, A, B, C} 0
4858 // vector_shuffle V1, V2 <1, 2, 3, X>
4860 if (!isShuffleMaskConsecutive(SVOp,
4861 0, // Mask Start Index
4862 NumElems-NumZeros-1, // Mask End Index
4863 NumZeros, // Where to start looking in the src vector
4864 NumElems, // Number of elements in vector
4865 OpSrc)) // Which source operand ?
4870 ShVal = SVOp->getOperand(OpSrc);
4874 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4875 /// logical left shift of a vector.
4876 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4877 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4878 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4879 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4880 true /* check zeros from left */, DAG);
4886 // Considering the elements in the mask that are not consecutive zeros,
4887 // check if they consecutively come from only one of the source vectors.
4889 // 0 { A, B, X, X } = V2
4891 // vector_shuffle V1, V2 <X, X, 4, 5>
4893 if (!isShuffleMaskConsecutive(SVOp,
4894 NumZeros, // Mask Start Index
4895 NumElems-1, // Mask End Index
4896 0, // Where to start looking in the src vector
4897 NumElems, // Number of elements in vector
4898 OpSrc)) // Which source operand ?
4903 ShVal = SVOp->getOperand(OpSrc);
4907 /// isVectorShift - Returns true if the shuffle can be implemented as a
4908 /// logical left or right shift of a vector.
4909 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4910 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4911 // Although the logic below support any bitwidth size, there are no
4912 // shift instructions which handle more than 128-bit vectors.
4913 if (SVOp->getValueType(0).getSizeInBits() > 128)
4916 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4917 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4923 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4925 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4926 unsigned NumNonZero, unsigned NumZero,
4928 const TargetLowering &TLI) {
4932 DebugLoc dl = Op.getDebugLoc();
4935 for (unsigned i = 0; i < 16; ++i) {
4936 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4937 if (ThisIsNonZero && First) {
4939 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4941 V = DAG.getUNDEF(MVT::v8i16);
4946 SDValue ThisElt(0, 0), LastElt(0, 0);
4947 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4948 if (LastIsNonZero) {
4949 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4950 MVT::i16, Op.getOperand(i-1));
4952 if (ThisIsNonZero) {
4953 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4954 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4955 ThisElt, DAG.getConstant(8, MVT::i8));
4957 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4961 if (ThisElt.getNode())
4962 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4963 DAG.getIntPtrConstant(i/2));
4967 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4970 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4972 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4973 unsigned NumNonZero, unsigned NumZero,
4975 const TargetLowering &TLI) {
4979 DebugLoc dl = Op.getDebugLoc();
4982 for (unsigned i = 0; i < 8; ++i) {
4983 bool isNonZero = (NonZeros & (1 << i)) != 0;
4987 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4989 V = DAG.getUNDEF(MVT::v8i16);
4992 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4993 MVT::v8i16, V, Op.getOperand(i),
4994 DAG.getIntPtrConstant(i));
5001 /// getVShift - Return a vector logical shift node.
5003 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5004 unsigned NumBits, SelectionDAG &DAG,
5005 const TargetLowering &TLI, DebugLoc dl) {
5006 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
5007 EVT ShVT = MVT::v2i64;
5008 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
5009 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5010 return DAG.getNode(ISD::BITCAST, dl, VT,
5011 DAG.getNode(Opc, dl, ShVT, SrcOp,
5012 DAG.getConstant(NumBits,
5013 TLI.getShiftAmountTy(SrcOp.getValueType()))));
5017 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
5018 SelectionDAG &DAG) const {
5020 // Check if the scalar load can be widened into a vector load. And if
5021 // the address is "base + cst" see if the cst can be "absorbed" into
5022 // the shuffle mask.
5023 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5024 SDValue Ptr = LD->getBasePtr();
5025 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5027 EVT PVT = LD->getValueType(0);
5028 if (PVT != MVT::i32 && PVT != MVT::f32)
5033 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5034 FI = FINode->getIndex();
5036 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5037 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5038 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5039 Offset = Ptr.getConstantOperandVal(1);
5040 Ptr = Ptr.getOperand(0);
5045 // FIXME: 256-bit vector instructions don't require a strict alignment,
5046 // improve this code to support it better.
5047 unsigned RequiredAlign = VT.getSizeInBits()/8;
5048 SDValue Chain = LD->getChain();
5049 // Make sure the stack object alignment is at least 16 or 32.
5050 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5051 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5052 if (MFI->isFixedObjectIndex(FI)) {
5053 // Can't change the alignment. FIXME: It's possible to compute
5054 // the exact stack offset and reference FI + adjust offset instead.
5055 // If someone *really* cares about this. That's the way to implement it.
5058 MFI->setObjectAlignment(FI, RequiredAlign);
5062 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5063 // Ptr + (Offset & ~15).
5066 if ((Offset % RequiredAlign) & 3)
5068 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5070 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5071 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5073 int EltNo = (Offset - StartOffset) >> 2;
5074 int NumElems = VT.getVectorNumElements();
5076 EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
5077 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5078 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5079 LD->getPointerInfo().getWithOffset(StartOffset),
5080 false, false, false, 0);
5082 // Canonicalize it to a v4i32 or v8i32 shuffle.
5083 SmallVector<int, 8> Mask;
5084 for (int i = 0; i < NumElems; ++i)
5085 Mask.push_back(EltNo);
5087 V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
5088 return DAG.getNode(ISD::BITCAST, dl, NVT,
5089 DAG.getVectorShuffle(CanonVT, dl, V1,
5090 DAG.getUNDEF(CanonVT),&Mask[0]));
5096 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5097 /// vector of type 'VT', see if the elements can be replaced by a single large
5098 /// load which has the same value as a build_vector whose operands are 'elts'.
5100 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5102 /// FIXME: we'd also like to handle the case where the last elements are zero
5103 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5104 /// There's even a handy isZeroNode for that purpose.
5105 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5106 DebugLoc &DL, SelectionDAG &DAG) {
5107 EVT EltVT = VT.getVectorElementType();
5108 unsigned NumElems = Elts.size();
5110 LoadSDNode *LDBase = NULL;
5111 unsigned LastLoadedElt = -1U;
5113 // For each element in the initializer, see if we've found a load or an undef.
5114 // If we don't find an initial load element, or later load elements are
5115 // non-consecutive, bail out.
5116 for (unsigned i = 0; i < NumElems; ++i) {
5117 SDValue Elt = Elts[i];
5119 if (!Elt.getNode() ||
5120 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5123 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5125 LDBase = cast<LoadSDNode>(Elt.getNode());
5129 if (Elt.getOpcode() == ISD::UNDEF)
5132 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5133 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5138 // If we have found an entire vector of loads and undefs, then return a large
5139 // load of the entire vector width starting at the base pointer. If we found
5140 // consecutive loads for the low half, generate a vzext_load node.
5141 if (LastLoadedElt == NumElems - 1) {
5142 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5143 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5144 LDBase->getPointerInfo(),
5145 LDBase->isVolatile(), LDBase->isNonTemporal(),
5146 LDBase->isInvariant(), 0);
5147 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5148 LDBase->getPointerInfo(),
5149 LDBase->isVolatile(), LDBase->isNonTemporal(),
5150 LDBase->isInvariant(), LDBase->getAlignment());
5151 } else if (NumElems == 4 && LastLoadedElt == 1 &&
5152 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5153 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5154 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5156 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5157 LDBase->getPointerInfo(),
5158 LDBase->getAlignment(),
5159 false/*isVolatile*/, true/*ReadMem*/,
5161 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5166 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
5167 /// a vbroadcast node. We support two patterns:
5168 /// 1. A splat BUILD_VECTOR which uses a single scalar load.
5169 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5171 /// The scalar load node is returned when a pattern is found,
5172 /// or SDValue() otherwise.
5173 static SDValue isVectorBroadcast(SDValue &Op, bool hasAVX2) {
5174 EVT VT = Op.getValueType();
5177 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5178 V = V.getOperand(0);
5180 //A suspected load to be broadcasted.
5183 switch (V.getOpcode()) {
5185 // Unknown pattern found.
5188 case ISD::BUILD_VECTOR: {
5189 // The BUILD_VECTOR node must be a splat.
5190 if (!isSplatVector(V.getNode()))
5193 Ld = V.getOperand(0);
5195 // The suspected load node has several users. Make sure that all
5196 // of its users are from the BUILD_VECTOR node.
5197 if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5202 case ISD::VECTOR_SHUFFLE: {
5203 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5205 // Shuffles must have a splat mask where the first element is
5207 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5210 SDValue Sc = Op.getOperand(0);
5211 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
5214 Ld = Sc.getOperand(0);
5216 // The scalar_to_vector node and the suspected
5217 // load node must have exactly one user.
5218 if (!Sc.hasOneUse() || !Ld.hasOneUse())
5224 // The scalar source must be a normal load.
5225 if (!ISD::isNormalLoad(Ld.getNode()))
5228 bool Is256 = VT.getSizeInBits() == 256;
5229 bool Is128 = VT.getSizeInBits() == 128;
5230 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5233 // VBroadcast to YMM
5234 if (Is256 && (ScalarSize == 8 || ScalarSize == 16 ||
5235 ScalarSize == 32 || ScalarSize == 64 ))
5238 // VBroadcast to XMM
5239 if (Is128 && (ScalarSize == 8 || ScalarSize == 32 ||
5240 ScalarSize == 16 || ScalarSize == 64 ))
5244 // VBroadcast to YMM
5245 if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
5248 // VBroadcast to XMM
5249 if (Is128 && (ScalarSize == 32))
5253 // Unsupported broadcast.
5258 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5259 DebugLoc dl = Op.getDebugLoc();
5261 EVT VT = Op.getValueType();
5262 EVT ExtVT = VT.getVectorElementType();
5263 unsigned NumElems = Op.getNumOperands();
5265 // Vectors containing all zeros can be matched by pxor and xorps later
5266 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5267 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5268 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5269 if (Op.getValueType() == MVT::v4i32 ||
5270 Op.getValueType() == MVT::v8i32)
5273 return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5276 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5277 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5278 // vpcmpeqd on 256-bit vectors.
5279 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5280 if (Op.getValueType() == MVT::v4i32 ||
5281 (Op.getValueType() == MVT::v8i32 && Subtarget->hasAVX2()))
5284 return getOnesVector(Op.getValueType(), Subtarget->hasAVX2(), DAG, dl);
5287 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
5288 if (Subtarget->hasAVX() && LD.getNode())
5289 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5291 unsigned EVTBits = ExtVT.getSizeInBits();
5293 unsigned NumZero = 0;
5294 unsigned NumNonZero = 0;
5295 unsigned NonZeros = 0;
5296 bool IsAllConstants = true;
5297 SmallSet<SDValue, 8> Values;
5298 for (unsigned i = 0; i < NumElems; ++i) {
5299 SDValue Elt = Op.getOperand(i);
5300 if (Elt.getOpcode() == ISD::UNDEF)
5303 if (Elt.getOpcode() != ISD::Constant &&
5304 Elt.getOpcode() != ISD::ConstantFP)
5305 IsAllConstants = false;
5306 if (X86::isZeroNode(Elt))
5309 NonZeros |= (1 << i);
5314 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5315 if (NumNonZero == 0)
5316 return DAG.getUNDEF(VT);
5318 // Special case for single non-zero, non-undef, element.
5319 if (NumNonZero == 1) {
5320 unsigned Idx = CountTrailingZeros_32(NonZeros);
5321 SDValue Item = Op.getOperand(Idx);
5323 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5324 // the value are obviously zero, truncate the value to i32 and do the
5325 // insertion that way. Only do this if the value is non-constant or if the
5326 // value is a constant being inserted into element 0. It is cheaper to do
5327 // a constant pool load than it is to do a movd + shuffle.
5328 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5329 (!IsAllConstants || Idx == 0)) {
5330 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5332 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5333 EVT VecVT = MVT::v4i32;
5334 unsigned VecElts = 4;
5336 // Truncate the value (which may itself be a constant) to i32, and
5337 // convert it to a vector with movd (S2V+shuffle to zero extend).
5338 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5339 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5340 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5341 Subtarget->hasXMMInt(), DAG);
5343 // Now we have our 32-bit value zero extended in the low element of
5344 // a vector. If Idx != 0, swizzle it into place.
5346 SmallVector<int, 4> Mask;
5347 Mask.push_back(Idx);
5348 for (unsigned i = 1; i != VecElts; ++i)
5350 Item = DAG.getVectorShuffle(VecVT, dl, Item,
5351 DAG.getUNDEF(Item.getValueType()),
5354 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5358 // If we have a constant or non-constant insertion into the low element of
5359 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5360 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5361 // depending on what the source datatype is.
5364 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5365 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5366 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5367 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5368 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5369 return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5371 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5372 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5373 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5374 EVT MiddleVT = MVT::v4i32;
5375 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5376 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5377 Subtarget->hasXMMInt(), DAG);
5378 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5382 // Is it a vector logical left shift?
5383 if (NumElems == 2 && Idx == 1 &&
5384 X86::isZeroNode(Op.getOperand(0)) &&
5385 !X86::isZeroNode(Op.getOperand(1))) {
5386 unsigned NumBits = VT.getSizeInBits();
5387 return getVShift(true, VT,
5388 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5389 VT, Op.getOperand(1)),
5390 NumBits/2, DAG, *this, dl);
5393 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5396 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5397 // is a non-constant being inserted into an element other than the low one,
5398 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5399 // movd/movss) to move this into the low element, then shuffle it into
5401 if (EVTBits == 32) {
5402 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5404 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5405 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5406 Subtarget->hasXMMInt(), DAG);
5407 SmallVector<int, 8> MaskVec;
5408 for (unsigned i = 0; i < NumElems; i++)
5409 MaskVec.push_back(i == Idx ? 0 : 1);
5410 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5414 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5415 if (Values.size() == 1) {
5416 if (EVTBits == 32) {
5417 // Instead of a shuffle like this:
5418 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5419 // Check if it's possible to issue this instead.
5420 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5421 unsigned Idx = CountTrailingZeros_32(NonZeros);
5422 SDValue Item = Op.getOperand(Idx);
5423 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5424 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5429 // A vector full of immediates; various special cases are already
5430 // handled, so this is best done with a single constant-pool load.
5434 // For AVX-length vectors, build the individual 128-bit pieces and use
5435 // shuffles to put them in place.
5436 if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5437 SmallVector<SDValue, 32> V;
5438 for (unsigned i = 0; i < NumElems; ++i)
5439 V.push_back(Op.getOperand(i));
5441 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5443 // Build both the lower and upper subvector.
5444 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5445 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5448 // Recreate the wider vector with the lower and upper part.
5449 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5450 DAG.getConstant(0, MVT::i32), DAG, dl);
5451 return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5455 // Let legalizer expand 2-wide build_vectors.
5456 if (EVTBits == 64) {
5457 if (NumNonZero == 1) {
5458 // One half is zero or undef.
5459 unsigned Idx = CountTrailingZeros_32(NonZeros);
5460 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5461 Op.getOperand(Idx));
5462 return getShuffleVectorZeroOrUndef(V2, Idx, true,
5463 Subtarget->hasXMMInt(), DAG);
5468 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5469 if (EVTBits == 8 && NumElems == 16) {
5470 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5472 if (V.getNode()) return V;
5475 if (EVTBits == 16 && NumElems == 8) {
5476 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5478 if (V.getNode()) return V;
5481 // If element VT is == 32 bits, turn it into a number of shuffles.
5482 SmallVector<SDValue, 8> V;
5484 if (NumElems == 4 && NumZero > 0) {
5485 for (unsigned i = 0; i < 4; ++i) {
5486 bool isZero = !(NonZeros & (1 << i));
5488 V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5490 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5493 for (unsigned i = 0; i < 2; ++i) {
5494 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5497 V[i] = V[i*2]; // Must be a zero vector.
5500 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5503 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5506 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5511 SmallVector<int, 8> MaskVec;
5512 bool Reverse = (NonZeros & 0x3) == 2;
5513 for (unsigned i = 0; i < 2; ++i)
5514 MaskVec.push_back(Reverse ? 1-i : i);
5515 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5516 for (unsigned i = 0; i < 2; ++i)
5517 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5518 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5521 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5522 // Check for a build vector of consecutive loads.
5523 for (unsigned i = 0; i < NumElems; ++i)
5524 V[i] = Op.getOperand(i);
5526 // Check for elements which are consecutive loads.
5527 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5531 // For SSE 4.1, use insertps to put the high elements into the low element.
5532 if (getSubtarget()->hasSSE41orAVX()) {
5534 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5535 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5537 Result = DAG.getUNDEF(VT);
5539 for (unsigned i = 1; i < NumElems; ++i) {
5540 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5541 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5542 Op.getOperand(i), DAG.getIntPtrConstant(i));
5547 // Otherwise, expand into a number of unpckl*, start by extending each of
5548 // our (non-undef) elements to the full vector width with the element in the
5549 // bottom slot of the vector (which generates no code for SSE).
5550 for (unsigned i = 0; i < NumElems; ++i) {
5551 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5552 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5554 V[i] = DAG.getUNDEF(VT);
5557 // Next, we iteratively mix elements, e.g. for v4f32:
5558 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5559 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5560 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5561 unsigned EltStride = NumElems >> 1;
5562 while (EltStride != 0) {
5563 for (unsigned i = 0; i < EltStride; ++i) {
5564 // If V[i+EltStride] is undef and this is the first round of mixing,
5565 // then it is safe to just drop this shuffle: V[i] is already in the
5566 // right place, the one element (since it's the first round) being
5567 // inserted as undef can be dropped. This isn't safe for successive
5568 // rounds because they will permute elements within both vectors.
5569 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5570 EltStride == NumElems/2)
5573 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5582 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5583 // them in a MMX register. This is better than doing a stack convert.
5584 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5585 DebugLoc dl = Op.getDebugLoc();
5586 EVT ResVT = Op.getValueType();
5588 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5589 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5591 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5592 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5593 InVec = Op.getOperand(1);
5594 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5595 unsigned NumElts = ResVT.getVectorNumElements();
5596 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5597 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5598 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5600 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5601 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5602 Mask[0] = 0; Mask[1] = 2;
5603 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5605 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5608 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5609 // to create 256-bit vectors from two other 128-bit ones.
5610 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5611 DebugLoc dl = Op.getDebugLoc();
5612 EVT ResVT = Op.getValueType();
5614 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5616 SDValue V1 = Op.getOperand(0);
5617 SDValue V2 = Op.getOperand(1);
5618 unsigned NumElems = ResVT.getVectorNumElements();
5620 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5621 DAG.getConstant(0, MVT::i32), DAG, dl);
5622 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5627 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5628 EVT ResVT = Op.getValueType();
5630 assert(Op.getNumOperands() == 2);
5631 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5632 "Unsupported CONCAT_VECTORS for value type");
5634 // We support concatenate two MMX registers and place them in a MMX register.
5635 // This is better than doing a stack convert.
5636 if (ResVT.is128BitVector())
5637 return LowerMMXCONCAT_VECTORS(Op, DAG);
5639 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5640 // from two other 128-bit ones.
5641 return LowerAVXCONCAT_VECTORS(Op, DAG);
5644 // v8i16 shuffles - Prefer shuffles in the following order:
5645 // 1. [all] pshuflw, pshufhw, optional move
5646 // 2. [ssse3] 1 x pshufb
5647 // 3. [ssse3] 2 x pshufb + 1 x por
5648 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5650 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5651 SelectionDAG &DAG) const {
5652 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5653 SDValue V1 = SVOp->getOperand(0);
5654 SDValue V2 = SVOp->getOperand(1);
5655 DebugLoc dl = SVOp->getDebugLoc();
5656 SmallVector<int, 8> MaskVals;
5658 // Determine if more than 1 of the words in each of the low and high quadwords
5659 // of the result come from the same quadword of one of the two inputs. Undef
5660 // mask values count as coming from any quadword, for better codegen.
5661 unsigned LoQuad[] = { 0, 0, 0, 0 };
5662 unsigned HiQuad[] = { 0, 0, 0, 0 };
5663 BitVector InputQuads(4);
5664 for (unsigned i = 0; i < 8; ++i) {
5665 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5666 int EltIdx = SVOp->getMaskElt(i);
5667 MaskVals.push_back(EltIdx);
5676 InputQuads.set(EltIdx / 4);
5679 int BestLoQuad = -1;
5680 unsigned MaxQuad = 1;
5681 for (unsigned i = 0; i < 4; ++i) {
5682 if (LoQuad[i] > MaxQuad) {
5684 MaxQuad = LoQuad[i];
5688 int BestHiQuad = -1;
5690 for (unsigned i = 0; i < 4; ++i) {
5691 if (HiQuad[i] > MaxQuad) {
5693 MaxQuad = HiQuad[i];
5697 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5698 // of the two input vectors, shuffle them into one input vector so only a
5699 // single pshufb instruction is necessary. If There are more than 2 input
5700 // quads, disable the next transformation since it does not help SSSE3.
5701 bool V1Used = InputQuads[0] || InputQuads[1];
5702 bool V2Used = InputQuads[2] || InputQuads[3];
5703 if (Subtarget->hasSSSE3orAVX()) {
5704 if (InputQuads.count() == 2 && V1Used && V2Used) {
5705 BestLoQuad = InputQuads.find_first();
5706 BestHiQuad = InputQuads.find_next(BestLoQuad);
5708 if (InputQuads.count() > 2) {
5714 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5715 // the shuffle mask. If a quad is scored as -1, that means that it contains
5716 // words from all 4 input quadwords.
5718 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5719 SmallVector<int, 8> MaskV;
5720 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5721 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5722 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5723 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5724 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5725 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5727 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5728 // source words for the shuffle, to aid later transformations.
5729 bool AllWordsInNewV = true;
5730 bool InOrder[2] = { true, true };
5731 for (unsigned i = 0; i != 8; ++i) {
5732 int idx = MaskVals[i];
5734 InOrder[i/4] = false;
5735 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5737 AllWordsInNewV = false;
5741 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5742 if (AllWordsInNewV) {
5743 for (int i = 0; i != 8; ++i) {
5744 int idx = MaskVals[i];
5747 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5748 if ((idx != i) && idx < 4)
5750 if ((idx != i) && idx > 3)
5759 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5760 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5761 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5762 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5763 unsigned TargetMask = 0;
5764 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5765 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5766 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5767 X86::getShufflePSHUFLWImmediate(NewV.getNode());
5768 V1 = NewV.getOperand(0);
5769 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5773 // If we have SSSE3, and all words of the result are from 1 input vector,
5774 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5775 // is present, fall back to case 4.
5776 if (Subtarget->hasSSSE3orAVX()) {
5777 SmallVector<SDValue,16> pshufbMask;
5779 // If we have elements from both input vectors, set the high bit of the
5780 // shuffle mask element to zero out elements that come from V2 in the V1
5781 // mask, and elements that come from V1 in the V2 mask, so that the two
5782 // results can be OR'd together.
5783 bool TwoInputs = V1Used && V2Used;
5784 for (unsigned i = 0; i != 8; ++i) {
5785 int EltIdx = MaskVals[i] * 2;
5786 if (TwoInputs && (EltIdx >= 16)) {
5787 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5788 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5791 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5792 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5794 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5795 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5796 DAG.getNode(ISD::BUILD_VECTOR, dl,
5797 MVT::v16i8, &pshufbMask[0], 16));
5799 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5801 // Calculate the shuffle mask for the second input, shuffle it, and
5802 // OR it with the first shuffled input.
5804 for (unsigned i = 0; i != 8; ++i) {
5805 int EltIdx = MaskVals[i] * 2;
5807 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5808 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5811 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5812 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5814 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5815 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5816 DAG.getNode(ISD::BUILD_VECTOR, dl,
5817 MVT::v16i8, &pshufbMask[0], 16));
5818 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5819 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5822 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5823 // and update MaskVals with new element order.
5824 BitVector InOrder(8);
5825 if (BestLoQuad >= 0) {
5826 SmallVector<int, 8> MaskV;
5827 for (int i = 0; i != 4; ++i) {
5828 int idx = MaskVals[i];
5830 MaskV.push_back(-1);
5832 } else if ((idx / 4) == BestLoQuad) {
5833 MaskV.push_back(idx & 3);
5836 MaskV.push_back(-1);
5839 for (unsigned i = 4; i != 8; ++i)
5841 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5844 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5845 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5847 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5851 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5852 // and update MaskVals with the new element order.
5853 if (BestHiQuad >= 0) {
5854 SmallVector<int, 8> MaskV;
5855 for (unsigned i = 0; i != 4; ++i)
5857 for (unsigned i = 4; i != 8; ++i) {
5858 int idx = MaskVals[i];
5860 MaskV.push_back(-1);
5862 } else if ((idx / 4) == BestHiQuad) {
5863 MaskV.push_back((idx & 3) + 4);
5866 MaskV.push_back(-1);
5869 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5872 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5873 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5875 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5879 // In case BestHi & BestLo were both -1, which means each quadword has a word
5880 // from each of the four input quadwords, calculate the InOrder bitvector now
5881 // before falling through to the insert/extract cleanup.
5882 if (BestLoQuad == -1 && BestHiQuad == -1) {
5884 for (int i = 0; i != 8; ++i)
5885 if (MaskVals[i] < 0 || MaskVals[i] == i)
5889 // The other elements are put in the right place using pextrw and pinsrw.
5890 for (unsigned i = 0; i != 8; ++i) {
5893 int EltIdx = MaskVals[i];
5896 SDValue ExtOp = (EltIdx < 8)
5897 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5898 DAG.getIntPtrConstant(EltIdx))
5899 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5900 DAG.getIntPtrConstant(EltIdx - 8));
5901 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5902 DAG.getIntPtrConstant(i));
5907 // v16i8 shuffles - Prefer shuffles in the following order:
5908 // 1. [ssse3] 1 x pshufb
5909 // 2. [ssse3] 2 x pshufb + 1 x por
5910 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5912 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5914 const X86TargetLowering &TLI) {
5915 SDValue V1 = SVOp->getOperand(0);
5916 SDValue V2 = SVOp->getOperand(1);
5917 DebugLoc dl = SVOp->getDebugLoc();
5918 SmallVector<int, 16> MaskVals;
5919 SVOp->getMask(MaskVals);
5921 // If we have SSSE3, case 1 is generated when all result bytes come from
5922 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5923 // present, fall back to case 3.
5924 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5927 for (unsigned i = 0; i < 16; ++i) {
5928 int EltIdx = MaskVals[i];
5937 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5938 if (TLI.getSubtarget()->hasSSSE3orAVX()) {
5939 SmallVector<SDValue,16> pshufbMask;
5941 // If all result elements are from one input vector, then only translate
5942 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5944 // Otherwise, we have elements from both input vectors, and must zero out
5945 // elements that come from V2 in the first mask, and V1 in the second mask
5946 // so that we can OR them together.
5947 bool TwoInputs = !(V1Only || V2Only);
5948 for (unsigned i = 0; i != 16; ++i) {
5949 int EltIdx = MaskVals[i];
5950 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5951 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5954 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5956 // If all the elements are from V2, assign it to V1 and return after
5957 // building the first pshufb.
5960 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5961 DAG.getNode(ISD::BUILD_VECTOR, dl,
5962 MVT::v16i8, &pshufbMask[0], 16));
5966 // Calculate the shuffle mask for the second input, shuffle it, and
5967 // OR it with the first shuffled input.
5969 for (unsigned i = 0; i != 16; ++i) {
5970 int EltIdx = MaskVals[i];
5972 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5975 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5977 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5978 DAG.getNode(ISD::BUILD_VECTOR, dl,
5979 MVT::v16i8, &pshufbMask[0], 16));
5980 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5983 // No SSSE3 - Calculate in place words and then fix all out of place words
5984 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5985 // the 16 different words that comprise the two doublequadword input vectors.
5986 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5987 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5988 SDValue NewV = V2Only ? V2 : V1;
5989 for (int i = 0; i != 8; ++i) {
5990 int Elt0 = MaskVals[i*2];
5991 int Elt1 = MaskVals[i*2+1];
5993 // This word of the result is all undef, skip it.
5994 if (Elt0 < 0 && Elt1 < 0)
5997 // This word of the result is already in the correct place, skip it.
5998 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
6000 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
6003 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6004 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6007 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6008 // using a single extract together, load it and store it.
6009 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6010 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6011 DAG.getIntPtrConstant(Elt1 / 2));
6012 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6013 DAG.getIntPtrConstant(i));
6017 // If Elt1 is defined, extract it from the appropriate source. If the
6018 // source byte is not also odd, shift the extracted word left 8 bits
6019 // otherwise clear the bottom 8 bits if we need to do an or.
6021 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6022 DAG.getIntPtrConstant(Elt1 / 2));
6023 if ((Elt1 & 1) == 0)
6024 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6026 TLI.getShiftAmountTy(InsElt.getValueType())));
6028 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6029 DAG.getConstant(0xFF00, MVT::i16));
6031 // If Elt0 is defined, extract it from the appropriate source. If the
6032 // source byte is not also even, shift the extracted word right 8 bits. If
6033 // Elt1 was also defined, OR the extracted values together before
6034 // inserting them in the result.
6036 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6037 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6038 if ((Elt0 & 1) != 0)
6039 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6041 TLI.getShiftAmountTy(InsElt0.getValueType())));
6043 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6044 DAG.getConstant(0x00FF, MVT::i16));
6045 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6048 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6049 DAG.getIntPtrConstant(i));
6051 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6054 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6055 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6056 /// done when every pair / quad of shuffle mask elements point to elements in
6057 /// the right sequence. e.g.
6058 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6060 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6061 SelectionDAG &DAG, DebugLoc dl) {
6062 EVT VT = SVOp->getValueType(0);
6063 SDValue V1 = SVOp->getOperand(0);
6064 SDValue V2 = SVOp->getOperand(1);
6065 unsigned NumElems = VT.getVectorNumElements();
6066 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
6068 switch (VT.getSimpleVT().SimpleTy) {
6069 default: assert(false && "Unexpected!");
6070 case MVT::v4f32: NewVT = MVT::v2f64; break;
6071 case MVT::v4i32: NewVT = MVT::v2i64; break;
6072 case MVT::v8i16: NewVT = MVT::v4i32; break;
6073 case MVT::v16i8: NewVT = MVT::v4i32; break;
6076 int Scale = NumElems / NewWidth;
6077 SmallVector<int, 8> MaskVec;
6078 for (unsigned i = 0; i < NumElems; i += Scale) {
6080 for (int j = 0; j < Scale; ++j) {
6081 int EltIdx = SVOp->getMaskElt(i+j);
6085 StartIdx = EltIdx - (EltIdx % Scale);
6086 if (EltIdx != StartIdx + j)
6090 MaskVec.push_back(-1);
6092 MaskVec.push_back(StartIdx / Scale);
6095 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
6096 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
6097 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6100 /// getVZextMovL - Return a zero-extending vector move low node.
6102 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6103 SDValue SrcOp, SelectionDAG &DAG,
6104 const X86Subtarget *Subtarget, DebugLoc dl) {
6105 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6106 LoadSDNode *LD = NULL;
6107 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6108 LD = dyn_cast<LoadSDNode>(SrcOp);
6110 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6112 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6113 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6114 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6115 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6116 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6118 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6119 return DAG.getNode(ISD::BITCAST, dl, VT,
6120 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6121 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6129 return DAG.getNode(ISD::BITCAST, dl, VT,
6130 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6131 DAG.getNode(ISD::BITCAST, dl,
6135 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
6136 /// shuffle node referes to only one lane in the sources.
6137 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
6138 EVT VT = SVOp->getValueType(0);
6139 int NumElems = VT.getVectorNumElements();
6140 int HalfSize = NumElems/2;
6141 SmallVector<int, 16> M;
6143 bool MatchA = false, MatchB = false;
6145 for (int l = 0; l < NumElems*2; l += HalfSize) {
6146 if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
6152 for (int l = 0; l < NumElems*2; l += HalfSize) {
6153 if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
6159 return MatchA && MatchB;
6162 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6163 /// which could not be matched by any known target speficic shuffle
6165 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6166 if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
6167 // If each half of a vector shuffle node referes to only one lane in the
6168 // source vectors, extract each used 128-bit lane and shuffle them using
6169 // 128-bit shuffles. Then, concatenate the results. Otherwise leave
6170 // the work to the legalizer.
6171 DebugLoc dl = SVOp->getDebugLoc();
6172 EVT VT = SVOp->getValueType(0);
6173 int NumElems = VT.getVectorNumElements();
6174 int HalfSize = NumElems/2;
6176 // Extract the reference for each half
6177 int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
6178 int FstVecOpNum = 0, SndVecOpNum = 0;
6179 for (int i = 0; i < HalfSize; ++i) {
6180 int Elt = SVOp->getMaskElt(i);
6181 if (SVOp->getMaskElt(i) < 0)
6183 FstVecOpNum = Elt/NumElems;
6184 FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6187 for (int i = HalfSize; i < NumElems; ++i) {
6188 int Elt = SVOp->getMaskElt(i);
6189 if (SVOp->getMaskElt(i) < 0)
6191 SndVecOpNum = Elt/NumElems;
6192 SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6196 // Extract the subvectors
6197 SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
6198 DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
6199 SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
6200 DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
6202 // Generate 128-bit shuffles
6203 SmallVector<int, 16> MaskV1, MaskV2;
6204 for (int i = 0; i < HalfSize; ++i) {
6205 int Elt = SVOp->getMaskElt(i);
6206 MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6208 for (int i = HalfSize; i < NumElems; ++i) {
6209 int Elt = SVOp->getMaskElt(i);
6210 MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6213 EVT NVT = V1.getValueType();
6214 V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
6215 V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
6217 // Concatenate the result back
6218 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6219 DAG.getConstant(0, MVT::i32), DAG, dl);
6220 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6227 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6228 /// 4 elements, and match them with several different shuffle types.
6230 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6231 SDValue V1 = SVOp->getOperand(0);
6232 SDValue V2 = SVOp->getOperand(1);
6233 DebugLoc dl = SVOp->getDebugLoc();
6234 EVT VT = SVOp->getValueType(0);
6236 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6238 SmallVector<std::pair<int, int>, 8> Locs;
6240 SmallVector<int, 8> Mask1(4U, -1);
6241 SmallVector<int, 8> PermMask;
6242 SVOp->getMask(PermMask);
6246 for (unsigned i = 0; i != 4; ++i) {
6247 int Idx = PermMask[i];
6249 Locs[i] = std::make_pair(-1, -1);
6251 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6253 Locs[i] = std::make_pair(0, NumLo);
6257 Locs[i] = std::make_pair(1, NumHi);
6259 Mask1[2+NumHi] = Idx;
6265 if (NumLo <= 2 && NumHi <= 2) {
6266 // If no more than two elements come from either vector. This can be
6267 // implemented with two shuffles. First shuffle gather the elements.
6268 // The second shuffle, which takes the first shuffle as both of its
6269 // vector operands, put the elements into the right order.
6270 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6272 SmallVector<int, 8> Mask2(4U, -1);
6274 for (unsigned i = 0; i != 4; ++i) {
6275 if (Locs[i].first == -1)
6278 unsigned Idx = (i < 2) ? 0 : 4;
6279 Idx += Locs[i].first * 2 + Locs[i].second;
6284 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6285 } else if (NumLo == 3 || NumHi == 3) {
6286 // Otherwise, we must have three elements from one vector, call it X, and
6287 // one element from the other, call it Y. First, use a shufps to build an
6288 // intermediate vector with the one element from Y and the element from X
6289 // that will be in the same half in the final destination (the indexes don't
6290 // matter). Then, use a shufps to build the final vector, taking the half
6291 // containing the element from Y from the intermediate, and the other half
6294 // Normalize it so the 3 elements come from V1.
6295 CommuteVectorShuffleMask(PermMask, VT);
6299 // Find the element from V2.
6301 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6302 int Val = PermMask[HiIndex];
6309 Mask1[0] = PermMask[HiIndex];
6311 Mask1[2] = PermMask[HiIndex^1];
6313 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6316 Mask1[0] = PermMask[0];
6317 Mask1[1] = PermMask[1];
6318 Mask1[2] = HiIndex & 1 ? 6 : 4;
6319 Mask1[3] = HiIndex & 1 ? 4 : 6;
6320 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6322 Mask1[0] = HiIndex & 1 ? 2 : 0;
6323 Mask1[1] = HiIndex & 1 ? 0 : 2;
6324 Mask1[2] = PermMask[2];
6325 Mask1[3] = PermMask[3];
6330 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6334 // Break it into (shuffle shuffle_hi, shuffle_lo).
6337 SmallVector<int,8> LoMask(4U, -1);
6338 SmallVector<int,8> HiMask(4U, -1);
6340 SmallVector<int,8> *MaskPtr = &LoMask;
6341 unsigned MaskIdx = 0;
6344 for (unsigned i = 0; i != 4; ++i) {
6351 int Idx = PermMask[i];
6353 Locs[i] = std::make_pair(-1, -1);
6354 } else if (Idx < 4) {
6355 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6356 (*MaskPtr)[LoIdx] = Idx;
6359 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6360 (*MaskPtr)[HiIdx] = Idx;
6365 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6366 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6367 SmallVector<int, 8> MaskOps;
6368 for (unsigned i = 0; i != 4; ++i) {
6369 if (Locs[i].first == -1) {
6370 MaskOps.push_back(-1);
6372 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6373 MaskOps.push_back(Idx);
6376 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6379 static bool MayFoldVectorLoad(SDValue V) {
6380 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6381 V = V.getOperand(0);
6382 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6383 V = V.getOperand(0);
6384 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6385 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6386 // BUILD_VECTOR (load), undef
6387 V = V.getOperand(0);
6393 // FIXME: the version above should always be used. Since there's
6394 // a bug where several vector shuffles can't be folded because the
6395 // DAG is not updated during lowering and a node claims to have two
6396 // uses while it only has one, use this version, and let isel match
6397 // another instruction if the load really happens to have more than
6398 // one use. Remove this version after this bug get fixed.
6399 // rdar://8434668, PR8156
6400 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6401 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6402 V = V.getOperand(0);
6403 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6404 V = V.getOperand(0);
6405 if (ISD::isNormalLoad(V.getNode()))
6410 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6411 /// a vector extract, and if both can be later optimized into a single load.
6412 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6413 /// here because otherwise a target specific shuffle node is going to be
6414 /// emitted for this shuffle, and the optimization not done.
6415 /// FIXME: This is probably not the best approach, but fix the problem
6416 /// until the right path is decided.
6418 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6419 const TargetLowering &TLI) {
6420 EVT VT = V.getValueType();
6421 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6423 // Be sure that the vector shuffle is present in a pattern like this:
6424 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6428 SDNode *N = *V.getNode()->use_begin();
6429 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6432 SDValue EltNo = N->getOperand(1);
6433 if (!isa<ConstantSDNode>(EltNo))
6436 // If the bit convert changed the number of elements, it is unsafe
6437 // to examine the mask.
6438 bool HasShuffleIntoBitcast = false;
6439 if (V.getOpcode() == ISD::BITCAST) {
6440 EVT SrcVT = V.getOperand(0).getValueType();
6441 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6443 V = V.getOperand(0);
6444 HasShuffleIntoBitcast = true;
6447 // Select the input vector, guarding against out of range extract vector.
6448 unsigned NumElems = VT.getVectorNumElements();
6449 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6450 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6451 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6453 // Skip one more bit_convert if necessary
6454 if (V.getOpcode() == ISD::BITCAST)
6455 V = V.getOperand(0);
6457 if (ISD::isNormalLoad(V.getNode())) {
6458 // Is the original load suitable?
6459 LoadSDNode *LN0 = cast<LoadSDNode>(V);
6461 // FIXME: avoid the multi-use bug that is preventing lots of
6462 // of foldings to be detected, this is still wrong of course, but
6463 // give the temporary desired behavior, and if it happens that
6464 // the load has real more uses, during isel it will not fold, and
6465 // will generate poor code.
6466 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6469 if (!HasShuffleIntoBitcast)
6472 // If there's a bitcast before the shuffle, check if the load type and
6473 // alignment is valid.
6474 unsigned Align = LN0->getAlignment();
6476 TLI.getTargetData()->getABITypeAlignment(
6477 VT.getTypeForEVT(*DAG.getContext()));
6479 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6487 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6488 EVT VT = Op.getValueType();
6490 // Canonizalize to v2f64.
6491 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6492 return DAG.getNode(ISD::BITCAST, dl, VT,
6493 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6498 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6500 SDValue V1 = Op.getOperand(0);
6501 SDValue V2 = Op.getOperand(1);
6502 EVT VT = Op.getValueType();
6504 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6506 if (HasXMMInt && VT == MVT::v2f64)
6507 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6509 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6510 return DAG.getNode(ISD::BITCAST, dl, VT,
6511 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6512 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6513 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6517 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6518 SDValue V1 = Op.getOperand(0);
6519 SDValue V2 = Op.getOperand(1);
6520 EVT VT = Op.getValueType();
6522 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6523 "unsupported shuffle type");
6525 if (V2.getOpcode() == ISD::UNDEF)
6529 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6532 static inline unsigned getSHUFPOpcode(EVT VT) {
6533 switch(VT.getSimpleVT().SimpleTy) {
6534 case MVT::v8i32: // Use fp unit for int unpack.
6536 case MVT::v4i32: // Use fp unit for int unpack.
6537 case MVT::v4f32: return X86ISD::SHUFPS;
6538 case MVT::v4i64: // Use fp unit for int unpack.
6540 case MVT::v2i64: // Use fp unit for int unpack.
6541 case MVT::v2f64: return X86ISD::SHUFPD;
6543 llvm_unreachable("Unknown type for shufp*");
6549 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6550 SDValue V1 = Op.getOperand(0);
6551 SDValue V2 = Op.getOperand(1);
6552 EVT VT = Op.getValueType();
6553 unsigned NumElems = VT.getVectorNumElements();
6555 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6556 // operand of these instructions is only memory, so check if there's a
6557 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6559 bool CanFoldLoad = false;
6561 // Trivial case, when V2 comes from a load.
6562 if (MayFoldVectorLoad(V2))
6565 // When V1 is a load, it can be folded later into a store in isel, example:
6566 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6568 // (MOVLPSmr addr:$src1, VR128:$src2)
6569 // So, recognize this potential and also use MOVLPS or MOVLPD
6570 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6573 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6575 if (HasXMMInt && NumElems == 2)
6576 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6579 // If we don't care about the second element, procede to use movss.
6580 if (SVOp->getMaskElt(1) != -1)
6581 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6584 // movl and movlp will both match v2i64, but v2i64 is never matched by
6585 // movl earlier because we make it strict to avoid messing with the movlp load
6586 // folding logic (see the code above getMOVLP call). Match it here then,
6587 // this is horrible, but will stay like this until we move all shuffle
6588 // matching to x86 specific nodes. Note that for the 1st condition all
6589 // types are matched with movsd.
6591 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6592 // as to remove this logic from here, as much as possible
6593 if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6594 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6595 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6598 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6600 // Invert the operand order and use SHUFPS to match it.
6601 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6602 X86::getShuffleSHUFImmediate(SVOp), DAG);
6605 static inline unsigned getUNPCKLOpcode(EVT VT, bool HasAVX2) {
6606 switch(VT.getSimpleVT().SimpleTy) {
6607 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6608 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6609 case MVT::v4f32: return X86ISD::UNPCKLPS;
6610 case MVT::v2f64: return X86ISD::UNPCKLPD;
6612 if (HasAVX2) return X86ISD::VPUNPCKLDQY;
6613 // else use fp unit for int unpack.
6614 case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6616 if (HasAVX2) return X86ISD::VPUNPCKLQDQY;
6617 // else use fp unit for int unpack.
6618 case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6619 case MVT::v16i8: return X86ISD::PUNPCKLBW;
6620 case MVT::v8i16: return X86ISD::PUNPCKLWD;
6621 case MVT::v16i16: return X86ISD::VPUNPCKLWDY;
6622 case MVT::v32i8: return X86ISD::VPUNPCKLBWY;
6624 llvm_unreachable("Unknown type for unpckl");
6629 static inline unsigned getUNPCKHOpcode(EVT VT, bool HasAVX2) {
6630 switch(VT.getSimpleVT().SimpleTy) {
6631 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6632 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6633 case MVT::v4f32: return X86ISD::UNPCKHPS;
6634 case MVT::v2f64: return X86ISD::UNPCKHPD;
6636 if (HasAVX2) return X86ISD::VPUNPCKHDQY;
6637 // else use fp unit for int unpack.
6638 case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6640 if (HasAVX2) return X86ISD::VPUNPCKHQDQY;
6641 // else use fp unit for int unpack.
6642 case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6643 case MVT::v16i8: return X86ISD::PUNPCKHBW;
6644 case MVT::v8i16: return X86ISD::PUNPCKHWD;
6645 case MVT::v16i16: return X86ISD::VPUNPCKHWDY;
6646 case MVT::v32i8: return X86ISD::VPUNPCKHBWY;
6648 llvm_unreachable("Unknown type for unpckh");
6653 static inline unsigned getVPERMILOpcode(EVT VT) {
6654 switch(VT.getSimpleVT().SimpleTy) {
6656 case MVT::v4f32: return X86ISD::VPERMILPS;
6658 case MVT::v2f64: return X86ISD::VPERMILPD;
6660 case MVT::v8f32: return X86ISD::VPERMILPSY;
6662 case MVT::v4f64: return X86ISD::VPERMILPDY;
6664 llvm_unreachable("Unknown type for vpermil");
6670 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6671 const TargetLowering &TLI,
6672 const X86Subtarget *Subtarget) {
6673 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6674 EVT VT = Op.getValueType();
6675 DebugLoc dl = Op.getDebugLoc();
6676 SDValue V1 = Op.getOperand(0);
6677 SDValue V2 = Op.getOperand(1);
6679 if (isZeroShuffle(SVOp))
6680 return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6682 // Handle splat operations
6683 if (SVOp->isSplat()) {
6684 unsigned NumElem = VT.getVectorNumElements();
6685 int Size = VT.getSizeInBits();
6686 // Special case, this is the only place now where it's allowed to return
6687 // a vector_shuffle operation without using a target specific node, because
6688 // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6689 // this be moved to DAGCombine instead?
6690 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6693 // Use vbroadcast whenever the splat comes from a foldable load
6694 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
6695 if (Subtarget->hasAVX() && LD.getNode())
6696 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6698 // Handle splats by matching through known shuffle masks
6699 if ((Size == 128 && NumElem <= 4) ||
6700 (Size == 256 && NumElem < 8))
6703 // All remaning splats are promoted to target supported vector shuffles.
6704 return PromoteSplat(SVOp, DAG);
6707 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6709 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6710 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6711 if (NewOp.getNode())
6712 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6713 } else if ((VT == MVT::v4i32 ||
6714 (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6715 // FIXME: Figure out a cleaner way to do this.
6716 // Try to make use of movq to zero out the top part.
6717 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6718 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6719 if (NewOp.getNode()) {
6720 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6721 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6722 DAG, Subtarget, dl);
6724 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6725 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6726 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6727 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6728 DAG, Subtarget, dl);
6735 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6736 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6737 SDValue V1 = Op.getOperand(0);
6738 SDValue V2 = Op.getOperand(1);
6739 EVT VT = Op.getValueType();
6740 DebugLoc dl = Op.getDebugLoc();
6741 unsigned NumElems = VT.getVectorNumElements();
6742 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6743 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6744 bool V1IsSplat = false;
6745 bool V2IsSplat = false;
6746 bool HasXMMInt = Subtarget->hasXMMInt();
6747 bool HasAVX2 = Subtarget->hasAVX2();
6748 MachineFunction &MF = DAG.getMachineFunction();
6749 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6751 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6753 // Vector shuffle lowering takes 3 steps:
6755 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6756 // narrowing and commutation of operands should be handled.
6757 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6759 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6760 // so the shuffle can be broken into other shuffles and the legalizer can
6761 // try the lowering again.
6763 // The general idea is that no vector_shuffle operation should be left to
6764 // be matched during isel, all of them must be converted to a target specific
6767 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6768 // narrowing and commutation of operands should be handled. The actual code
6769 // doesn't include all of those, work in progress...
6770 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6771 if (NewOp.getNode())
6774 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6775 // unpckh_undef). Only use pshufd if speed is more important than size.
6776 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6777 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V1,
6779 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6780 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6783 if (X86::isMOVDDUPMask(SVOp) && Subtarget->hasSSE3orAVX() &&
6784 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6785 return getMOVDDup(Op, dl, V1, DAG);
6787 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6788 return getMOVHighToLow(Op, dl, DAG);
6790 // Use to match splats
6791 if (HasXMMInt && X86::isUNPCKHMask(SVOp, HasAVX2) && V2IsUndef &&
6792 (VT == MVT::v2f64 || VT == MVT::v2i64))
6793 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6796 if (X86::isPSHUFDMask(SVOp)) {
6797 // The actual implementation will match the mask in the if above and then
6798 // during isel it can match several different instructions, not only pshufd
6799 // as its name says, sad but true, emulate the behavior for now...
6800 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6801 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6803 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6805 if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6806 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6808 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6812 // Check if this can be converted into a logical shift.
6813 bool isLeft = false;
6816 bool isShift = HasXMMInt && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6817 if (isShift && ShVal.hasOneUse()) {
6818 // If the shifted value has multiple uses, it may be cheaper to use
6819 // v_set0 + movlhps or movhlps, etc.
6820 EVT EltVT = VT.getVectorElementType();
6821 ShAmt *= EltVT.getSizeInBits();
6822 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6825 if (X86::isMOVLMask(SVOp)) {
6828 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6829 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6830 if (!X86::isMOVLPMask(SVOp)) {
6831 if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6832 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6834 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6835 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6839 // FIXME: fold these into legal mask.
6840 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp, HasAVX2))
6841 return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6843 if (X86::isMOVHLPSMask(SVOp))
6844 return getMOVHighToLow(Op, dl, DAG);
6846 if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6847 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6849 if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6850 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6852 if (X86::isMOVLPMask(SVOp))
6853 return getMOVLP(Op, dl, DAG, HasXMMInt);
6855 if (ShouldXformToMOVHLPS(SVOp) ||
6856 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6857 return CommuteVectorShuffle(SVOp, DAG);
6860 // No better options. Use a vshl / vsrl.
6861 EVT EltVT = VT.getVectorElementType();
6862 ShAmt *= EltVT.getSizeInBits();
6863 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6866 bool Commuted = false;
6867 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6868 // 1,1,1,1 -> v8i16 though.
6869 V1IsSplat = isSplatVector(V1.getNode());
6870 V2IsSplat = isSplatVector(V2.getNode());
6872 // Canonicalize the splat or undef, if present, to be on the RHS.
6873 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6874 Op = CommuteVectorShuffle(SVOp, DAG);
6875 SVOp = cast<ShuffleVectorSDNode>(Op);
6876 V1 = SVOp->getOperand(0);
6877 V2 = SVOp->getOperand(1);
6878 std::swap(V1IsSplat, V2IsSplat);
6879 std::swap(V1IsUndef, V2IsUndef);
6883 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6884 // Shuffling low element of v1 into undef, just return v1.
6887 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6888 // the instruction selector will not match, so get a canonical MOVL with
6889 // swapped operands to undo the commute.
6890 return getMOVL(DAG, dl, VT, V2, V1);
6893 if (X86::isUNPCKLMask(SVOp, HasAVX2))
6894 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V2,
6897 if (X86::isUNPCKHMask(SVOp, HasAVX2))
6898 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V2,
6902 // Normalize mask so all entries that point to V2 points to its first
6903 // element then try to match unpck{h|l} again. If match, return a
6904 // new vector_shuffle with the corrected mask.
6905 SDValue NewMask = NormalizeMask(SVOp, DAG);
6906 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6907 if (NSVOp != SVOp) {
6908 if (X86::isUNPCKLMask(NSVOp, HasAVX2, true)) {
6910 } else if (X86::isUNPCKHMask(NSVOp, HasAVX2, true)) {
6917 // Commute is back and try unpck* again.
6918 // FIXME: this seems wrong.
6919 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6920 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6922 if (X86::isUNPCKLMask(NewSVOp, HasAVX2))
6923 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V2, V1,
6926 if (X86::isUNPCKHMask(NewSVOp, HasAVX2))
6927 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V2, V1,
6931 // Normalize the node to match x86 shuffle ops if needed
6932 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6933 return CommuteVectorShuffle(SVOp, DAG);
6935 // The checks below are all present in isShuffleMaskLegal, but they are
6936 // inlined here right now to enable us to directly emit target specific
6937 // nodes, and remove one by one until they don't return Op anymore.
6938 SmallVector<int, 16> M;
6941 if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()))
6942 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6943 X86::getShufflePALIGNRImmediate(SVOp),
6946 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6947 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6948 if (VT == MVT::v2f64)
6949 return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6950 if (VT == MVT::v2i64)
6951 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6954 if (isPSHUFHWMask(M, VT))
6955 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6956 X86::getShufflePSHUFHWImmediate(SVOp),
6959 if (isPSHUFLWMask(M, VT))
6960 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6961 X86::getShufflePSHUFLWImmediate(SVOp),
6964 if (isSHUFPMask(M, VT))
6965 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6966 X86::getShuffleSHUFImmediate(SVOp), DAG);
6968 if (X86::isUNPCKL_v_undef_Mask(SVOp))
6969 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V1,
6971 if (X86::isUNPCKH_v_undef_Mask(SVOp))
6972 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6975 //===--------------------------------------------------------------------===//
6976 // Generate target specific nodes for 128 or 256-bit shuffles only
6977 // supported in the AVX instruction set.
6980 // Handle VMOVDDUPY permutations
6981 if (isMOVDDUPYMask(SVOp, Subtarget))
6982 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6984 // Handle VPERMILPS* permutations
6985 if (isVPERMILPSMask(M, VT, Subtarget))
6986 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6987 getShuffleVPERMILPSImmediate(SVOp), DAG);
6989 // Handle VPERMILPD* permutations
6990 if (isVPERMILPDMask(M, VT, Subtarget))
6991 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6992 getShuffleVPERMILPDImmediate(SVOp), DAG);
6994 // Handle VPERM2F128 permutations
6995 if (isVPERM2F128Mask(M, VT, Subtarget))
6996 return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6997 getShuffleVPERM2F128Immediate(SVOp), DAG);
6999 // Handle VSHUFPSY permutations
7000 if (isVSHUFPSYMask(M, VT, Subtarget))
7001 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
7002 getShuffleVSHUFPSYImmediate(SVOp), DAG);
7004 // Handle VSHUFPDY permutations
7005 if (isVSHUFPDYMask(M, VT, Subtarget))
7006 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
7007 getShuffleVSHUFPDYImmediate(SVOp), DAG);
7009 // Try to swap operands in the node to match x86 shuffle ops
7010 if (isCommutedVSHUFPMask(M, VT, Subtarget)) {
7011 // Now we need to commute operands.
7012 SVOp = cast<ShuffleVectorSDNode>(CommuteVectorShuffle(SVOp, DAG));
7013 V1 = SVOp->getOperand(0);
7014 V2 = SVOp->getOperand(1);
7015 unsigned Immediate = (NumElems == 4) ? getShuffleVSHUFPDYImmediate(SVOp):
7016 getShuffleVSHUFPSYImmediate(SVOp);
7017 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2, Immediate, DAG);
7020 //===--------------------------------------------------------------------===//
7021 // Since no target specific shuffle was selected for this generic one,
7022 // lower it into other known shuffles. FIXME: this isn't true yet, but
7023 // this is the plan.
7026 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7027 if (VT == MVT::v8i16) {
7028 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
7029 if (NewOp.getNode())
7033 if (VT == MVT::v16i8) {
7034 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7035 if (NewOp.getNode())
7039 // Handle all 128-bit wide vectors with 4 elements, and match them with
7040 // several different shuffle types.
7041 if (NumElems == 4 && VT.getSizeInBits() == 128)
7042 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7044 // Handle general 256-bit shuffles
7045 if (VT.is256BitVector())
7046 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7052 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7053 SelectionDAG &DAG) const {
7054 EVT VT = Op.getValueType();
7055 DebugLoc dl = Op.getDebugLoc();
7057 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
7060 if (VT.getSizeInBits() == 8) {
7061 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7062 Op.getOperand(0), Op.getOperand(1));
7063 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7064 DAG.getValueType(VT));
7065 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7066 } else if (VT.getSizeInBits() == 16) {
7067 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7068 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7070 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7071 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7072 DAG.getNode(ISD::BITCAST, dl,
7076 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7077 Op.getOperand(0), Op.getOperand(1));
7078 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7079 DAG.getValueType(VT));
7080 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7081 } else if (VT == MVT::f32) {
7082 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7083 // the result back to FR32 register. It's only worth matching if the
7084 // result has a single use which is a store or a bitcast to i32. And in
7085 // the case of a store, it's not worth it if the index is a constant 0,
7086 // because a MOVSSmr can be used instead, which is smaller and faster.
7087 if (!Op.hasOneUse())
7089 SDNode *User = *Op.getNode()->use_begin();
7090 if ((User->getOpcode() != ISD::STORE ||
7091 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7092 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7093 (User->getOpcode() != ISD::BITCAST ||
7094 User->getValueType(0) != MVT::i32))
7096 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7097 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7100 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7101 } else if (VT == MVT::i32 || VT == MVT::i64) {
7102 // ExtractPS/pextrq works with constant index.
7103 if (isa<ConstantSDNode>(Op.getOperand(1)))
7111 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7112 SelectionDAG &DAG) const {
7113 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7116 SDValue Vec = Op.getOperand(0);
7117 EVT VecVT = Vec.getValueType();
7119 // If this is a 256-bit vector result, first extract the 128-bit vector and
7120 // then extract the element from the 128-bit vector.
7121 if (VecVT.getSizeInBits() == 256) {
7122 DebugLoc dl = Op.getNode()->getDebugLoc();
7123 unsigned NumElems = VecVT.getVectorNumElements();
7124 SDValue Idx = Op.getOperand(1);
7125 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7127 // Get the 128-bit vector.
7128 bool Upper = IdxVal >= NumElems/2;
7129 Vec = Extract128BitVector(Vec,
7130 DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
7132 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7133 Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
7136 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
7138 if (Subtarget->hasSSE41orAVX()) {
7139 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7144 EVT VT = Op.getValueType();
7145 DebugLoc dl = Op.getDebugLoc();
7146 // TODO: handle v16i8.
7147 if (VT.getSizeInBits() == 16) {
7148 SDValue Vec = Op.getOperand(0);
7149 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7151 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7152 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7153 DAG.getNode(ISD::BITCAST, dl,
7156 // Transform it so it match pextrw which produces a 32-bit result.
7157 EVT EltVT = MVT::i32;
7158 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7159 Op.getOperand(0), Op.getOperand(1));
7160 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7161 DAG.getValueType(VT));
7162 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7163 } else if (VT.getSizeInBits() == 32) {
7164 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7168 // SHUFPS the element to the lowest double word, then movss.
7169 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7170 EVT VVT = Op.getOperand(0).getValueType();
7171 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7172 DAG.getUNDEF(VVT), Mask);
7173 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7174 DAG.getIntPtrConstant(0));
7175 } else if (VT.getSizeInBits() == 64) {
7176 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7177 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7178 // to match extract_elt for f64.
7179 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7183 // UNPCKHPD the element to the lowest double word, then movsd.
7184 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7185 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7186 int Mask[2] = { 1, -1 };
7187 EVT VVT = Op.getOperand(0).getValueType();
7188 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7189 DAG.getUNDEF(VVT), Mask);
7190 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7191 DAG.getIntPtrConstant(0));
7198 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7199 SelectionDAG &DAG) const {
7200 EVT VT = Op.getValueType();
7201 EVT EltVT = VT.getVectorElementType();
7202 DebugLoc dl = Op.getDebugLoc();
7204 SDValue N0 = Op.getOperand(0);
7205 SDValue N1 = Op.getOperand(1);
7206 SDValue N2 = Op.getOperand(2);
7208 if (VT.getSizeInBits() == 256)
7211 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7212 isa<ConstantSDNode>(N2)) {
7214 if (VT == MVT::v8i16)
7215 Opc = X86ISD::PINSRW;
7216 else if (VT == MVT::v16i8)
7217 Opc = X86ISD::PINSRB;
7219 Opc = X86ISD::PINSRB;
7221 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7223 if (N1.getValueType() != MVT::i32)
7224 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7225 if (N2.getValueType() != MVT::i32)
7226 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7227 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7228 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7229 // Bits [7:6] of the constant are the source select. This will always be
7230 // zero here. The DAG Combiner may combine an extract_elt index into these
7231 // bits. For example (insert (extract, 3), 2) could be matched by putting
7232 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7233 // Bits [5:4] of the constant are the destination select. This is the
7234 // value of the incoming immediate.
7235 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7236 // combine either bitwise AND or insert of float 0.0 to set these bits.
7237 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7238 // Create this as a scalar to vector..
7239 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7240 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7241 } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) &&
7242 isa<ConstantSDNode>(N2)) {
7243 // PINSR* works with constant index.
7250 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7251 EVT VT = Op.getValueType();
7252 EVT EltVT = VT.getVectorElementType();
7254 DebugLoc dl = Op.getDebugLoc();
7255 SDValue N0 = Op.getOperand(0);
7256 SDValue N1 = Op.getOperand(1);
7257 SDValue N2 = Op.getOperand(2);
7259 // If this is a 256-bit vector result, first extract the 128-bit vector,
7260 // insert the element into the extracted half and then place it back.
7261 if (VT.getSizeInBits() == 256) {
7262 if (!isa<ConstantSDNode>(N2))
7265 // Get the desired 128-bit vector half.
7266 unsigned NumElems = VT.getVectorNumElements();
7267 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7268 bool Upper = IdxVal >= NumElems/2;
7269 SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7270 SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7272 // Insert the element into the desired half.
7273 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7274 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7276 // Insert the changed part back to the 256-bit vector
7277 return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7280 if (Subtarget->hasSSE41orAVX())
7281 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7283 if (EltVT == MVT::i8)
7286 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7287 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7288 // as its second argument.
7289 if (N1.getValueType() != MVT::i32)
7290 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7291 if (N2.getValueType() != MVT::i32)
7292 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7293 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7299 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7300 LLVMContext *Context = DAG.getContext();
7301 DebugLoc dl = Op.getDebugLoc();
7302 EVT OpVT = Op.getValueType();
7304 // If this is a 256-bit vector result, first insert into a 128-bit
7305 // vector and then insert into the 256-bit vector.
7306 if (OpVT.getSizeInBits() > 128) {
7307 // Insert into a 128-bit vector.
7308 EVT VT128 = EVT::getVectorVT(*Context,
7309 OpVT.getVectorElementType(),
7310 OpVT.getVectorNumElements() / 2);
7312 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7314 // Insert the 128-bit vector.
7315 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7316 DAG.getConstant(0, MVT::i32),
7320 if (Op.getValueType() == MVT::v1i64 &&
7321 Op.getOperand(0).getValueType() == MVT::i64)
7322 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7324 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7325 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7326 "Expected an SSE type!");
7327 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7328 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7331 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7332 // a simple subregister reference or explicit instructions to grab
7333 // upper bits of a vector.
7335 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7336 if (Subtarget->hasAVX()) {
7337 DebugLoc dl = Op.getNode()->getDebugLoc();
7338 SDValue Vec = Op.getNode()->getOperand(0);
7339 SDValue Idx = Op.getNode()->getOperand(1);
7341 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7342 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7343 return Extract128BitVector(Vec, Idx, DAG, dl);
7349 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7350 // simple superregister reference or explicit instructions to insert
7351 // the upper bits of a vector.
7353 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7354 if (Subtarget->hasAVX()) {
7355 DebugLoc dl = Op.getNode()->getDebugLoc();
7356 SDValue Vec = Op.getNode()->getOperand(0);
7357 SDValue SubVec = Op.getNode()->getOperand(1);
7358 SDValue Idx = Op.getNode()->getOperand(2);
7360 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7361 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7362 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7368 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7369 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7370 // one of the above mentioned nodes. It has to be wrapped because otherwise
7371 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7372 // be used to form addressing mode. These wrapped nodes will be selected
7375 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7376 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7378 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7380 unsigned char OpFlag = 0;
7381 unsigned WrapperKind = X86ISD::Wrapper;
7382 CodeModel::Model M = getTargetMachine().getCodeModel();
7384 if (Subtarget->isPICStyleRIPRel() &&
7385 (M == CodeModel::Small || M == CodeModel::Kernel))
7386 WrapperKind = X86ISD::WrapperRIP;
7387 else if (Subtarget->isPICStyleGOT())
7388 OpFlag = X86II::MO_GOTOFF;
7389 else if (Subtarget->isPICStyleStubPIC())
7390 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7392 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7394 CP->getOffset(), OpFlag);
7395 DebugLoc DL = CP->getDebugLoc();
7396 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7397 // With PIC, the address is actually $g + Offset.
7399 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7400 DAG.getNode(X86ISD::GlobalBaseReg,
7401 DebugLoc(), getPointerTy()),
7408 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7409 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7411 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7413 unsigned char OpFlag = 0;
7414 unsigned WrapperKind = X86ISD::Wrapper;
7415 CodeModel::Model M = getTargetMachine().getCodeModel();
7417 if (Subtarget->isPICStyleRIPRel() &&
7418 (M == CodeModel::Small || M == CodeModel::Kernel))
7419 WrapperKind = X86ISD::WrapperRIP;
7420 else if (Subtarget->isPICStyleGOT())
7421 OpFlag = X86II::MO_GOTOFF;
7422 else if (Subtarget->isPICStyleStubPIC())
7423 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7425 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7427 DebugLoc DL = JT->getDebugLoc();
7428 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7430 // With PIC, the address is actually $g + Offset.
7432 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7433 DAG.getNode(X86ISD::GlobalBaseReg,
7434 DebugLoc(), getPointerTy()),
7441 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7442 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7444 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7446 unsigned char OpFlag = 0;
7447 unsigned WrapperKind = X86ISD::Wrapper;
7448 CodeModel::Model M = getTargetMachine().getCodeModel();
7450 if (Subtarget->isPICStyleRIPRel() &&
7451 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7452 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7453 OpFlag = X86II::MO_GOTPCREL;
7454 WrapperKind = X86ISD::WrapperRIP;
7455 } else if (Subtarget->isPICStyleGOT()) {
7456 OpFlag = X86II::MO_GOT;
7457 } else if (Subtarget->isPICStyleStubPIC()) {
7458 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7459 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7460 OpFlag = X86II::MO_DARWIN_NONLAZY;
7463 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7465 DebugLoc DL = Op.getDebugLoc();
7466 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7469 // With PIC, the address is actually $g + Offset.
7470 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7471 !Subtarget->is64Bit()) {
7472 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7473 DAG.getNode(X86ISD::GlobalBaseReg,
7474 DebugLoc(), getPointerTy()),
7478 // For symbols that require a load from a stub to get the address, emit the
7480 if (isGlobalStubReference(OpFlag))
7481 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7482 MachinePointerInfo::getGOT(), false, false, false, 0);
7488 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7489 // Create the TargetBlockAddressAddress node.
7490 unsigned char OpFlags =
7491 Subtarget->ClassifyBlockAddressReference();
7492 CodeModel::Model M = getTargetMachine().getCodeModel();
7493 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7494 DebugLoc dl = Op.getDebugLoc();
7495 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7496 /*isTarget=*/true, OpFlags);
7498 if (Subtarget->isPICStyleRIPRel() &&
7499 (M == CodeModel::Small || M == CodeModel::Kernel))
7500 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7502 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7504 // With PIC, the address is actually $g + Offset.
7505 if (isGlobalRelativeToPICBase(OpFlags)) {
7506 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7507 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7515 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7517 SelectionDAG &DAG) const {
7518 // Create the TargetGlobalAddress node, folding in the constant
7519 // offset if it is legal.
7520 unsigned char OpFlags =
7521 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7522 CodeModel::Model M = getTargetMachine().getCodeModel();
7524 if (OpFlags == X86II::MO_NO_FLAG &&
7525 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7526 // A direct static reference to a global.
7527 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7530 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7533 if (Subtarget->isPICStyleRIPRel() &&
7534 (M == CodeModel::Small || M == CodeModel::Kernel))
7535 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7537 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7539 // With PIC, the address is actually $g + Offset.
7540 if (isGlobalRelativeToPICBase(OpFlags)) {
7541 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7542 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7546 // For globals that require a load from a stub to get the address, emit the
7548 if (isGlobalStubReference(OpFlags))
7549 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7550 MachinePointerInfo::getGOT(), false, false, false, 0);
7552 // If there was a non-zero offset that we didn't fold, create an explicit
7555 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7556 DAG.getConstant(Offset, getPointerTy()));
7562 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7563 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7564 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7565 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7569 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7570 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7571 unsigned char OperandFlags) {
7572 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7573 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7574 DebugLoc dl = GA->getDebugLoc();
7575 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7576 GA->getValueType(0),
7580 SDValue Ops[] = { Chain, TGA, *InFlag };
7581 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7583 SDValue Ops[] = { Chain, TGA };
7584 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7587 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7588 MFI->setAdjustsStack(true);
7590 SDValue Flag = Chain.getValue(1);
7591 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7594 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7596 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7599 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7600 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7601 DAG.getNode(X86ISD::GlobalBaseReg,
7602 DebugLoc(), PtrVT), InFlag);
7603 InFlag = Chain.getValue(1);
7605 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7608 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7610 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7612 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7613 X86::RAX, X86II::MO_TLSGD);
7616 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7617 // "local exec" model.
7618 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7619 const EVT PtrVT, TLSModel::Model model,
7621 DebugLoc dl = GA->getDebugLoc();
7623 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7624 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7625 is64Bit ? 257 : 256));
7627 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7628 DAG.getIntPtrConstant(0),
7629 MachinePointerInfo(Ptr),
7630 false, false, false, 0);
7632 unsigned char OperandFlags = 0;
7633 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7635 unsigned WrapperKind = X86ISD::Wrapper;
7636 if (model == TLSModel::LocalExec) {
7637 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7638 } else if (is64Bit) {
7639 assert(model == TLSModel::InitialExec);
7640 OperandFlags = X86II::MO_GOTTPOFF;
7641 WrapperKind = X86ISD::WrapperRIP;
7643 assert(model == TLSModel::InitialExec);
7644 OperandFlags = X86II::MO_INDNTPOFF;
7647 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7649 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7650 GA->getValueType(0),
7651 GA->getOffset(), OperandFlags);
7652 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7654 if (model == TLSModel::InitialExec)
7655 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7656 MachinePointerInfo::getGOT(), false, false, false, 0);
7658 // The address of the thread local variable is the add of the thread
7659 // pointer with the offset of the variable.
7660 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7664 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7666 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7667 const GlobalValue *GV = GA->getGlobal();
7669 if (Subtarget->isTargetELF()) {
7670 // TODO: implement the "local dynamic" model
7671 // TODO: implement the "initial exec"model for pic executables
7673 // If GV is an alias then use the aliasee for determining
7674 // thread-localness.
7675 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7676 GV = GA->resolveAliasedGlobal(false);
7678 TLSModel::Model model
7679 = getTLSModel(GV, getTargetMachine().getRelocationModel());
7682 case TLSModel::GeneralDynamic:
7683 case TLSModel::LocalDynamic: // not implemented
7684 if (Subtarget->is64Bit())
7685 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7686 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7688 case TLSModel::InitialExec:
7689 case TLSModel::LocalExec:
7690 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7691 Subtarget->is64Bit());
7693 } else if (Subtarget->isTargetDarwin()) {
7694 // Darwin only has one model of TLS. Lower to that.
7695 unsigned char OpFlag = 0;
7696 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7697 X86ISD::WrapperRIP : X86ISD::Wrapper;
7699 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7701 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7702 !Subtarget->is64Bit();
7704 OpFlag = X86II::MO_TLVP_PIC_BASE;
7706 OpFlag = X86II::MO_TLVP;
7707 DebugLoc DL = Op.getDebugLoc();
7708 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7709 GA->getValueType(0),
7710 GA->getOffset(), OpFlag);
7711 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7713 // With PIC32, the address is actually $g + Offset.
7715 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7716 DAG.getNode(X86ISD::GlobalBaseReg,
7717 DebugLoc(), getPointerTy()),
7720 // Lowering the machine isd will make sure everything is in the right
7722 SDValue Chain = DAG.getEntryNode();
7723 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7724 SDValue Args[] = { Chain, Offset };
7725 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7727 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7728 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7729 MFI->setAdjustsStack(true);
7731 // And our return value (tls address) is in the standard call return value
7733 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7734 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7739 "TLS not implemented for this target.");
7741 llvm_unreachable("Unreachable");
7746 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7747 /// take a 2 x i32 value to shift plus a shift amount.
7748 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7749 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7750 EVT VT = Op.getValueType();
7751 unsigned VTBits = VT.getSizeInBits();
7752 DebugLoc dl = Op.getDebugLoc();
7753 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7754 SDValue ShOpLo = Op.getOperand(0);
7755 SDValue ShOpHi = Op.getOperand(1);
7756 SDValue ShAmt = Op.getOperand(2);
7757 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7758 DAG.getConstant(VTBits - 1, MVT::i8))
7759 : DAG.getConstant(0, VT);
7762 if (Op.getOpcode() == ISD::SHL_PARTS) {
7763 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7764 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7766 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7767 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7770 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7771 DAG.getConstant(VTBits, MVT::i8));
7772 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7773 AndNode, DAG.getConstant(0, MVT::i8));
7776 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7777 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7778 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7780 if (Op.getOpcode() == ISD::SHL_PARTS) {
7781 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7782 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7784 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7785 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7788 SDValue Ops[2] = { Lo, Hi };
7789 return DAG.getMergeValues(Ops, 2, dl);
7792 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7793 SelectionDAG &DAG) const {
7794 EVT SrcVT = Op.getOperand(0).getValueType();
7796 if (SrcVT.isVector())
7799 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7800 "Unknown SINT_TO_FP to lower!");
7802 // These are really Legal; return the operand so the caller accepts it as
7804 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7806 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7807 Subtarget->is64Bit()) {
7811 DebugLoc dl = Op.getDebugLoc();
7812 unsigned Size = SrcVT.getSizeInBits()/8;
7813 MachineFunction &MF = DAG.getMachineFunction();
7814 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7815 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7816 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7818 MachinePointerInfo::getFixedStack(SSFI),
7820 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7823 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7825 SelectionDAG &DAG) const {
7827 DebugLoc DL = Op.getDebugLoc();
7829 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7831 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7833 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7835 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7837 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7838 MachineMemOperand *MMO;
7840 int SSFI = FI->getIndex();
7842 DAG.getMachineFunction()
7843 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7844 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7846 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7847 StackSlot = StackSlot.getOperand(1);
7849 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7850 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7852 Tys, Ops, array_lengthof(Ops),
7856 Chain = Result.getValue(1);
7857 SDValue InFlag = Result.getValue(2);
7859 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7860 // shouldn't be necessary except that RFP cannot be live across
7861 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7862 MachineFunction &MF = DAG.getMachineFunction();
7863 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7864 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7865 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7866 Tys = DAG.getVTList(MVT::Other);
7868 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7870 MachineMemOperand *MMO =
7871 DAG.getMachineFunction()
7872 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7873 MachineMemOperand::MOStore, SSFISize, SSFISize);
7875 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7876 Ops, array_lengthof(Ops),
7877 Op.getValueType(), MMO);
7878 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7879 MachinePointerInfo::getFixedStack(SSFI),
7880 false, false, false, 0);
7886 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7887 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7888 SelectionDAG &DAG) const {
7889 // This algorithm is not obvious. Here it is in C code, more or less:
7891 double uint64_to_double( uint32_t hi, uint32_t lo ) {
7892 static const __m128i exp = { 0x4330000045300000ULL, 0 };
7893 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7895 // Copy ints to xmm registers.
7896 __m128i xh = _mm_cvtsi32_si128( hi );
7897 __m128i xl = _mm_cvtsi32_si128( lo );
7899 // Combine into low half of a single xmm register.
7900 __m128i x = _mm_unpacklo_epi32( xh, xl );
7904 // Merge in appropriate exponents to give the integer bits the right
7906 x = _mm_unpacklo_epi32( x, exp );
7908 // Subtract away the biases to deal with the IEEE-754 double precision
7910 d = _mm_sub_pd( (__m128d) x, bias );
7912 // All conversions up to here are exact. The correctly rounded result is
7913 // calculated using the current rounding mode using the following
7915 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7916 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
7917 // store doesn't really need to be here (except
7918 // maybe to zero the other double)
7923 DebugLoc dl = Op.getDebugLoc();
7924 LLVMContext *Context = DAG.getContext();
7926 // Build some magic constants.
7927 std::vector<Constant*> CV0;
7928 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7929 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7930 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7931 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7932 Constant *C0 = ConstantVector::get(CV0);
7933 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7935 std::vector<Constant*> CV1;
7937 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7939 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7940 Constant *C1 = ConstantVector::get(CV1);
7941 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7943 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7944 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7946 DAG.getIntPtrConstant(1)));
7947 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7948 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7950 DAG.getIntPtrConstant(0)));
7951 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7952 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7953 MachinePointerInfo::getConstantPool(),
7954 false, false, false, 16);
7955 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7956 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7957 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7958 MachinePointerInfo::getConstantPool(),
7959 false, false, false, 16);
7960 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7962 // Add the halves; easiest way is to swap them into another reg first.
7963 int ShufMask[2] = { 1, -1 };
7964 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7965 DAG.getUNDEF(MVT::v2f64), ShufMask);
7966 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7967 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7968 DAG.getIntPtrConstant(0));
7971 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7972 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7973 SelectionDAG &DAG) const {
7974 DebugLoc dl = Op.getDebugLoc();
7975 // FP constant to bias correct the final result.
7976 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7979 // Load the 32-bit value into an XMM register.
7980 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7983 // Zero out the upper parts of the register.
7984 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7987 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7988 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7989 DAG.getIntPtrConstant(0));
7991 // Or the load with the bias.
7992 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7993 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7994 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7996 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7997 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7998 MVT::v2f64, Bias)));
7999 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8000 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8001 DAG.getIntPtrConstant(0));
8003 // Subtract the bias.
8004 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8006 // Handle final rounding.
8007 EVT DestVT = Op.getValueType();
8009 if (DestVT.bitsLT(MVT::f64)) {
8010 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8011 DAG.getIntPtrConstant(0));
8012 } else if (DestVT.bitsGT(MVT::f64)) {
8013 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8016 // Handle final rounding.
8020 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8021 SelectionDAG &DAG) const {
8022 SDValue N0 = Op.getOperand(0);
8023 DebugLoc dl = Op.getDebugLoc();
8025 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8026 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8027 // the optimization here.
8028 if (DAG.SignBitIsZero(N0))
8029 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8031 EVT SrcVT = N0.getValueType();
8032 EVT DstVT = Op.getValueType();
8033 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8034 return LowerUINT_TO_FP_i64(Op, DAG);
8035 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8036 return LowerUINT_TO_FP_i32(Op, DAG);
8038 // Make a 64-bit buffer, and use it to build an FILD.
8039 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8040 if (SrcVT == MVT::i32) {
8041 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8042 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8043 getPointerTy(), StackSlot, WordOff);
8044 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8045 StackSlot, MachinePointerInfo(),
8047 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8048 OffsetSlot, MachinePointerInfo(),
8050 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8054 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8055 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8056 StackSlot, MachinePointerInfo(),
8058 // For i64 source, we need to add the appropriate power of 2 if the input
8059 // was negative. This is the same as the optimization in
8060 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8061 // we must be careful to do the computation in x87 extended precision, not
8062 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8063 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8064 MachineMemOperand *MMO =
8065 DAG.getMachineFunction()
8066 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8067 MachineMemOperand::MOLoad, 8, 8);
8069 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8070 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8071 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8074 APInt FF(32, 0x5F800000ULL);
8076 // Check whether the sign bit is set.
8077 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8078 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8081 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8082 SDValue FudgePtr = DAG.getConstantPool(
8083 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8086 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8087 SDValue Zero = DAG.getIntPtrConstant(0);
8088 SDValue Four = DAG.getIntPtrConstant(4);
8089 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8091 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8093 // Load the value out, extending it from f32 to f80.
8094 // FIXME: Avoid the extend by constructing the right constant pool?
8095 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8096 FudgePtr, MachinePointerInfo::getConstantPool(),
8097 MVT::f32, false, false, 4);
8098 // Extend everything to 80 bits to force it to be done on x87.
8099 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8100 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8103 std::pair<SDValue,SDValue> X86TargetLowering::
8104 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
8105 DebugLoc DL = Op.getDebugLoc();
8107 EVT DstTy = Op.getValueType();
8110 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8114 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8115 DstTy.getSimpleVT() >= MVT::i16 &&
8116 "Unknown FP_TO_SINT to lower!");
8118 // These are really Legal.
8119 if (DstTy == MVT::i32 &&
8120 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8121 return std::make_pair(SDValue(), SDValue());
8122 if (Subtarget->is64Bit() &&
8123 DstTy == MVT::i64 &&
8124 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8125 return std::make_pair(SDValue(), SDValue());
8127 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
8129 MachineFunction &MF = DAG.getMachineFunction();
8130 unsigned MemSize = DstTy.getSizeInBits()/8;
8131 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8132 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8137 switch (DstTy.getSimpleVT().SimpleTy) {
8138 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8139 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8140 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8141 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8144 SDValue Chain = DAG.getEntryNode();
8145 SDValue Value = Op.getOperand(0);
8146 EVT TheVT = Op.getOperand(0).getValueType();
8147 if (isScalarFPTypeInSSEReg(TheVT)) {
8148 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8149 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8150 MachinePointerInfo::getFixedStack(SSFI),
8152 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8154 Chain, StackSlot, DAG.getValueType(TheVT)
8157 MachineMemOperand *MMO =
8158 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8159 MachineMemOperand::MOLoad, MemSize, MemSize);
8160 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8162 Chain = Value.getValue(1);
8163 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8164 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8167 MachineMemOperand *MMO =
8168 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8169 MachineMemOperand::MOStore, MemSize, MemSize);
8171 // Build the FP_TO_INT*_IN_MEM
8172 SDValue Ops[] = { Chain, Value, StackSlot };
8173 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8174 Ops, 3, DstTy, MMO);
8176 return std::make_pair(FIST, StackSlot);
8179 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8180 SelectionDAG &DAG) const {
8181 if (Op.getValueType().isVector())
8184 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
8185 SDValue FIST = Vals.first, StackSlot = Vals.second;
8186 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8187 if (FIST.getNode() == 0) return Op;
8190 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8191 FIST, StackSlot, MachinePointerInfo(),
8192 false, false, false, 0);
8195 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8196 SelectionDAG &DAG) const {
8197 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
8198 SDValue FIST = Vals.first, StackSlot = Vals.second;
8199 assert(FIST.getNode() && "Unexpected failure");
8202 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8203 FIST, StackSlot, MachinePointerInfo(),
8204 false, false, false, 0);
8207 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8208 SelectionDAG &DAG) const {
8209 LLVMContext *Context = DAG.getContext();
8210 DebugLoc dl = Op.getDebugLoc();
8211 EVT VT = Op.getValueType();
8214 EltVT = VT.getVectorElementType();
8215 std::vector<Constant*> CV;
8216 if (EltVT == MVT::f64) {
8217 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8221 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8227 Constant *C = ConstantVector::get(CV);
8228 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8229 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8230 MachinePointerInfo::getConstantPool(),
8231 false, false, false, 16);
8232 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8235 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8236 LLVMContext *Context = DAG.getContext();
8237 DebugLoc dl = Op.getDebugLoc();
8238 EVT VT = Op.getValueType();
8241 EltVT = VT.getVectorElementType();
8242 std::vector<Constant*> CV;
8243 if (EltVT == MVT::f64) {
8244 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8248 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8254 Constant *C = ConstantVector::get(CV);
8255 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8256 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8257 MachinePointerInfo::getConstantPool(),
8258 false, false, false, 16);
8259 if (VT.isVector()) {
8260 return DAG.getNode(ISD::BITCAST, dl, VT,
8261 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8262 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8264 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8266 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8270 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8271 LLVMContext *Context = DAG.getContext();
8272 SDValue Op0 = Op.getOperand(0);
8273 SDValue Op1 = Op.getOperand(1);
8274 DebugLoc dl = Op.getDebugLoc();
8275 EVT VT = Op.getValueType();
8276 EVT SrcVT = Op1.getValueType();
8278 // If second operand is smaller, extend it first.
8279 if (SrcVT.bitsLT(VT)) {
8280 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8283 // And if it is bigger, shrink it first.
8284 if (SrcVT.bitsGT(VT)) {
8285 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8289 // At this point the operands and the result should have the same
8290 // type, and that won't be f80 since that is not custom lowered.
8292 // First get the sign bit of second operand.
8293 std::vector<Constant*> CV;
8294 if (SrcVT == MVT::f64) {
8295 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8296 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8298 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8299 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8300 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8301 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8303 Constant *C = ConstantVector::get(CV);
8304 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8305 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8306 MachinePointerInfo::getConstantPool(),
8307 false, false, false, 16);
8308 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8310 // Shift sign bit right or left if the two operands have different types.
8311 if (SrcVT.bitsGT(VT)) {
8312 // Op0 is MVT::f32, Op1 is MVT::f64.
8313 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8314 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8315 DAG.getConstant(32, MVT::i32));
8316 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8317 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8318 DAG.getIntPtrConstant(0));
8321 // Clear first operand sign bit.
8323 if (VT == MVT::f64) {
8324 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8325 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8327 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8328 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8329 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8330 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8332 C = ConstantVector::get(CV);
8333 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8334 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8335 MachinePointerInfo::getConstantPool(),
8336 false, false, false, 16);
8337 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8339 // Or the value with the sign bit.
8340 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8343 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8344 SDValue N0 = Op.getOperand(0);
8345 DebugLoc dl = Op.getDebugLoc();
8346 EVT VT = Op.getValueType();
8348 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8349 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8350 DAG.getConstant(1, VT));
8351 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8354 /// Emit nodes that will be selected as "test Op0,Op0", or something
8356 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8357 SelectionDAG &DAG) const {
8358 DebugLoc dl = Op.getDebugLoc();
8360 // CF and OF aren't always set the way we want. Determine which
8361 // of these we need.
8362 bool NeedCF = false;
8363 bool NeedOF = false;
8366 case X86::COND_A: case X86::COND_AE:
8367 case X86::COND_B: case X86::COND_BE:
8370 case X86::COND_G: case X86::COND_GE:
8371 case X86::COND_L: case X86::COND_LE:
8372 case X86::COND_O: case X86::COND_NO:
8377 // See if we can use the EFLAGS value from the operand instead of
8378 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8379 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8380 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8381 // Emit a CMP with 0, which is the TEST pattern.
8382 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8383 DAG.getConstant(0, Op.getValueType()));
8385 unsigned Opcode = 0;
8386 unsigned NumOperands = 0;
8387 switch (Op.getNode()->getOpcode()) {
8389 // Due to an isel shortcoming, be conservative if this add is likely to be
8390 // selected as part of a load-modify-store instruction. When the root node
8391 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8392 // uses of other nodes in the match, such as the ADD in this case. This
8393 // leads to the ADD being left around and reselected, with the result being
8394 // two adds in the output. Alas, even if none our users are stores, that
8395 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8396 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8397 // climbing the DAG back to the root, and it doesn't seem to be worth the
8399 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8400 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8401 if (UI->getOpcode() != ISD::CopyToReg &&
8402 UI->getOpcode() != ISD::SETCC &&
8403 UI->getOpcode() != ISD::STORE)
8406 if (ConstantSDNode *C =
8407 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8408 // An add of one will be selected as an INC.
8409 if (C->getAPIntValue() == 1) {
8410 Opcode = X86ISD::INC;
8415 // An add of negative one (subtract of one) will be selected as a DEC.
8416 if (C->getAPIntValue().isAllOnesValue()) {
8417 Opcode = X86ISD::DEC;
8423 // Otherwise use a regular EFLAGS-setting add.
8424 Opcode = X86ISD::ADD;
8428 // If the primary and result isn't used, don't bother using X86ISD::AND,
8429 // because a TEST instruction will be better.
8430 bool NonFlagUse = false;
8431 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8432 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8434 unsigned UOpNo = UI.getOperandNo();
8435 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8436 // Look pass truncate.
8437 UOpNo = User->use_begin().getOperandNo();
8438 User = *User->use_begin();
8441 if (User->getOpcode() != ISD::BRCOND &&
8442 User->getOpcode() != ISD::SETCC &&
8443 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8456 // Due to the ISEL shortcoming noted above, be conservative if this op is
8457 // likely to be selected as part of a load-modify-store instruction.
8458 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8459 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8460 if (UI->getOpcode() == ISD::STORE)
8463 // Otherwise use a regular EFLAGS-setting instruction.
8464 switch (Op.getNode()->getOpcode()) {
8465 default: llvm_unreachable("unexpected operator!");
8466 case ISD::SUB: Opcode = X86ISD::SUB; break;
8467 case ISD::OR: Opcode = X86ISD::OR; break;
8468 case ISD::XOR: Opcode = X86ISD::XOR; break;
8469 case ISD::AND: Opcode = X86ISD::AND; break;
8481 return SDValue(Op.getNode(), 1);
8488 // Emit a CMP with 0, which is the TEST pattern.
8489 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8490 DAG.getConstant(0, Op.getValueType()));
8492 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8493 SmallVector<SDValue, 4> Ops;
8494 for (unsigned i = 0; i != NumOperands; ++i)
8495 Ops.push_back(Op.getOperand(i));
8497 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8498 DAG.ReplaceAllUsesWith(Op, New);
8499 return SDValue(New.getNode(), 1);
8502 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8504 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8505 SelectionDAG &DAG) const {
8506 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8507 if (C->getAPIntValue() == 0)
8508 return EmitTest(Op0, X86CC, DAG);
8510 DebugLoc dl = Op0.getDebugLoc();
8511 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8514 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8515 /// if it's possible.
8516 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8517 DebugLoc dl, SelectionDAG &DAG) const {
8518 SDValue Op0 = And.getOperand(0);
8519 SDValue Op1 = And.getOperand(1);
8520 if (Op0.getOpcode() == ISD::TRUNCATE)
8521 Op0 = Op0.getOperand(0);
8522 if (Op1.getOpcode() == ISD::TRUNCATE)
8523 Op1 = Op1.getOperand(0);
8526 if (Op1.getOpcode() == ISD::SHL)
8527 std::swap(Op0, Op1);
8528 if (Op0.getOpcode() == ISD::SHL) {
8529 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8530 if (And00C->getZExtValue() == 1) {
8531 // If we looked past a truncate, check that it's only truncating away
8533 unsigned BitWidth = Op0.getValueSizeInBits();
8534 unsigned AndBitWidth = And.getValueSizeInBits();
8535 if (BitWidth > AndBitWidth) {
8536 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8537 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8538 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8542 RHS = Op0.getOperand(1);
8544 } else if (Op1.getOpcode() == ISD::Constant) {
8545 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8546 SDValue AndLHS = Op0;
8547 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8548 LHS = AndLHS.getOperand(0);
8549 RHS = AndLHS.getOperand(1);
8553 if (LHS.getNode()) {
8554 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8555 // instruction. Since the shift amount is in-range-or-undefined, we know
8556 // that doing a bittest on the i32 value is ok. We extend to i32 because
8557 // the encoding for the i16 version is larger than the i32 version.
8558 // Also promote i16 to i32 for performance / code size reason.
8559 if (LHS.getValueType() == MVT::i8 ||
8560 LHS.getValueType() == MVT::i16)
8561 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8563 // If the operand types disagree, extend the shift amount to match. Since
8564 // BT ignores high bits (like shifts) we can use anyextend.
8565 if (LHS.getValueType() != RHS.getValueType())
8566 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8568 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8569 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8570 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8571 DAG.getConstant(Cond, MVT::i8), BT);
8577 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8579 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8581 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8582 SDValue Op0 = Op.getOperand(0);
8583 SDValue Op1 = Op.getOperand(1);
8584 DebugLoc dl = Op.getDebugLoc();
8585 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8587 // Optimize to BT if possible.
8588 // Lower (X & (1 << N)) == 0 to BT(X, N).
8589 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8590 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8591 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8592 Op1.getOpcode() == ISD::Constant &&
8593 cast<ConstantSDNode>(Op1)->isNullValue() &&
8594 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8595 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8596 if (NewSetCC.getNode())
8600 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8602 if (Op1.getOpcode() == ISD::Constant &&
8603 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8604 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8605 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8607 // If the input is a setcc, then reuse the input setcc or use a new one with
8608 // the inverted condition.
8609 if (Op0.getOpcode() == X86ISD::SETCC) {
8610 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8611 bool Invert = (CC == ISD::SETNE) ^
8612 cast<ConstantSDNode>(Op1)->isNullValue();
8613 if (!Invert) return Op0;
8615 CCode = X86::GetOppositeBranchCondition(CCode);
8616 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8617 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8621 bool isFP = Op1.getValueType().isFloatingPoint();
8622 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8623 if (X86CC == X86::COND_INVALID)
8626 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8627 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8628 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8631 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8632 // ones, and then concatenate the result back.
8633 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8634 EVT VT = Op.getValueType();
8636 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8637 "Unsupported value type for operation");
8639 int NumElems = VT.getVectorNumElements();
8640 DebugLoc dl = Op.getDebugLoc();
8641 SDValue CC = Op.getOperand(2);
8642 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8643 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8645 // Extract the LHS vectors
8646 SDValue LHS = Op.getOperand(0);
8647 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8648 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8650 // Extract the RHS vectors
8651 SDValue RHS = Op.getOperand(1);
8652 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8653 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8655 // Issue the operation on the smaller types and concatenate the result back
8656 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8657 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8658 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8659 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8660 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8664 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8666 SDValue Op0 = Op.getOperand(0);
8667 SDValue Op1 = Op.getOperand(1);
8668 SDValue CC = Op.getOperand(2);
8669 EVT VT = Op.getValueType();
8670 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8671 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8672 DebugLoc dl = Op.getDebugLoc();
8676 EVT EltVT = Op0.getValueType().getVectorElementType();
8677 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8679 unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8682 // SSE Condition code mapping:
8691 switch (SetCCOpcode) {
8694 case ISD::SETEQ: SSECC = 0; break;
8696 case ISD::SETGT: Swap = true; // Fallthrough
8698 case ISD::SETOLT: SSECC = 1; break;
8700 case ISD::SETGE: Swap = true; // Fallthrough
8702 case ISD::SETOLE: SSECC = 2; break;
8703 case ISD::SETUO: SSECC = 3; break;
8705 case ISD::SETNE: SSECC = 4; break;
8706 case ISD::SETULE: Swap = true;
8707 case ISD::SETUGE: SSECC = 5; break;
8708 case ISD::SETULT: Swap = true;
8709 case ISD::SETUGT: SSECC = 6; break;
8710 case ISD::SETO: SSECC = 7; break;
8713 std::swap(Op0, Op1);
8715 // In the two special cases we can't handle, emit two comparisons.
8717 if (SetCCOpcode == ISD::SETUEQ) {
8719 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8720 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8721 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8722 } else if (SetCCOpcode == ISD::SETONE) {
8724 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8725 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8726 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8728 llvm_unreachable("Illegal FP comparison");
8730 // Handle all other FP comparisons here.
8731 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8734 // Break 256-bit integer vector compare into smaller ones.
8735 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8736 return Lower256IntVSETCC(Op, DAG);
8738 // We are handling one of the integer comparisons here. Since SSE only has
8739 // GT and EQ comparisons for integer, swapping operands and multiple
8740 // operations may be required for some comparisons.
8741 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8742 bool Swap = false, Invert = false, FlipSigns = false;
8744 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8746 case MVT::i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8747 case MVT::i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8748 case MVT::i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8749 case MVT::i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8752 switch (SetCCOpcode) {
8754 case ISD::SETNE: Invert = true;
8755 case ISD::SETEQ: Opc = EQOpc; break;
8756 case ISD::SETLT: Swap = true;
8757 case ISD::SETGT: Opc = GTOpc; break;
8758 case ISD::SETGE: Swap = true;
8759 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
8760 case ISD::SETULT: Swap = true;
8761 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8762 case ISD::SETUGE: Swap = true;
8763 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8766 std::swap(Op0, Op1);
8768 // Check that the operation in question is available (most are plain SSE2,
8769 // but PCMPGTQ and PCMPEQQ have different requirements).
8770 if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42orAVX())
8772 if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41orAVX())
8775 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8776 // bits of the inputs before performing those operations.
8778 EVT EltVT = VT.getVectorElementType();
8779 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8781 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8782 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8784 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8785 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8788 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8790 // If the logical-not of the result is required, perform that now.
8792 Result = DAG.getNOT(dl, Result, VT);
8797 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8798 static bool isX86LogicalCmp(SDValue Op) {
8799 unsigned Opc = Op.getNode()->getOpcode();
8800 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8802 if (Op.getResNo() == 1 &&
8803 (Opc == X86ISD::ADD ||
8804 Opc == X86ISD::SUB ||
8805 Opc == X86ISD::ADC ||
8806 Opc == X86ISD::SBB ||
8807 Opc == X86ISD::SMUL ||
8808 Opc == X86ISD::UMUL ||
8809 Opc == X86ISD::INC ||
8810 Opc == X86ISD::DEC ||
8811 Opc == X86ISD::OR ||
8812 Opc == X86ISD::XOR ||
8813 Opc == X86ISD::AND))
8816 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8822 static bool isZero(SDValue V) {
8823 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8824 return C && C->isNullValue();
8827 static bool isAllOnes(SDValue V) {
8828 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8829 return C && C->isAllOnesValue();
8832 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8833 bool addTest = true;
8834 SDValue Cond = Op.getOperand(0);
8835 SDValue Op1 = Op.getOperand(1);
8836 SDValue Op2 = Op.getOperand(2);
8837 DebugLoc DL = Op.getDebugLoc();
8840 if (Cond.getOpcode() == ISD::SETCC) {
8841 SDValue NewCond = LowerSETCC(Cond, DAG);
8842 if (NewCond.getNode())
8846 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8847 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8848 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8849 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8850 if (Cond.getOpcode() == X86ISD::SETCC &&
8851 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8852 isZero(Cond.getOperand(1).getOperand(1))) {
8853 SDValue Cmp = Cond.getOperand(1);
8855 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8857 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8858 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8859 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8861 SDValue CmpOp0 = Cmp.getOperand(0);
8862 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8863 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8865 SDValue Res = // Res = 0 or -1.
8866 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8867 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8869 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8870 Res = DAG.getNOT(DL, Res, Res.getValueType());
8872 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8873 if (N2C == 0 || !N2C->isNullValue())
8874 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8879 // Look past (and (setcc_carry (cmp ...)), 1).
8880 if (Cond.getOpcode() == ISD::AND &&
8881 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8882 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8883 if (C && C->getAPIntValue() == 1)
8884 Cond = Cond.getOperand(0);
8887 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8888 // setting operand in place of the X86ISD::SETCC.
8889 unsigned CondOpcode = Cond.getOpcode();
8890 if (CondOpcode == X86ISD::SETCC ||
8891 CondOpcode == X86ISD::SETCC_CARRY) {
8892 CC = Cond.getOperand(0);
8894 SDValue Cmp = Cond.getOperand(1);
8895 unsigned Opc = Cmp.getOpcode();
8896 EVT VT = Op.getValueType();
8898 bool IllegalFPCMov = false;
8899 if (VT.isFloatingPoint() && !VT.isVector() &&
8900 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8901 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8903 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8904 Opc == X86ISD::BT) { // FIXME
8908 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8909 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8910 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8911 Cond.getOperand(0).getValueType() != MVT::i8)) {
8912 SDValue LHS = Cond.getOperand(0);
8913 SDValue RHS = Cond.getOperand(1);
8917 switch (CondOpcode) {
8918 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8919 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8920 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8921 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8922 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8923 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8924 default: llvm_unreachable("unexpected overflowing operator");
8926 if (CondOpcode == ISD::UMULO)
8927 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8930 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8932 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8934 if (CondOpcode == ISD::UMULO)
8935 Cond = X86Op.getValue(2);
8937 Cond = X86Op.getValue(1);
8939 CC = DAG.getConstant(X86Cond, MVT::i8);
8944 // Look pass the truncate.
8945 if (Cond.getOpcode() == ISD::TRUNCATE)
8946 Cond = Cond.getOperand(0);
8948 // We know the result of AND is compared against zero. Try to match
8950 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8951 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8952 if (NewSetCC.getNode()) {
8953 CC = NewSetCC.getOperand(0);
8954 Cond = NewSetCC.getOperand(1);
8961 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8962 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8965 // a < b ? -1 : 0 -> RES = ~setcc_carry
8966 // a < b ? 0 : -1 -> RES = setcc_carry
8967 // a >= b ? -1 : 0 -> RES = setcc_carry
8968 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8969 if (Cond.getOpcode() == X86ISD::CMP) {
8970 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8972 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8973 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8974 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8975 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8976 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8977 return DAG.getNOT(DL, Res, Res.getValueType());
8982 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8983 // condition is true.
8984 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8985 SDValue Ops[] = { Op2, Op1, CC, Cond };
8986 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8989 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8990 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8991 // from the AND / OR.
8992 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8993 Opc = Op.getOpcode();
8994 if (Opc != ISD::OR && Opc != ISD::AND)
8996 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8997 Op.getOperand(0).hasOneUse() &&
8998 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8999 Op.getOperand(1).hasOneUse());
9002 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9003 // 1 and that the SETCC node has a single use.
9004 static bool isXor1OfSetCC(SDValue Op) {
9005 if (Op.getOpcode() != ISD::XOR)
9007 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9008 if (N1C && N1C->getAPIntValue() == 1) {
9009 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9010 Op.getOperand(0).hasOneUse();
9015 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9016 bool addTest = true;
9017 SDValue Chain = Op.getOperand(0);
9018 SDValue Cond = Op.getOperand(1);
9019 SDValue Dest = Op.getOperand(2);
9020 DebugLoc dl = Op.getDebugLoc();
9022 bool Inverted = false;
9024 if (Cond.getOpcode() == ISD::SETCC) {
9025 // Check for setcc([su]{add,sub,mul}o == 0).
9026 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9027 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9028 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9029 Cond.getOperand(0).getResNo() == 1 &&
9030 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9031 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9032 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9033 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9034 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9035 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9037 Cond = Cond.getOperand(0);
9039 SDValue NewCond = LowerSETCC(Cond, DAG);
9040 if (NewCond.getNode())
9045 // FIXME: LowerXALUO doesn't handle these!!
9046 else if (Cond.getOpcode() == X86ISD::ADD ||
9047 Cond.getOpcode() == X86ISD::SUB ||
9048 Cond.getOpcode() == X86ISD::SMUL ||
9049 Cond.getOpcode() == X86ISD::UMUL)
9050 Cond = LowerXALUO(Cond, DAG);
9053 // Look pass (and (setcc_carry (cmp ...)), 1).
9054 if (Cond.getOpcode() == ISD::AND &&
9055 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9056 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9057 if (C && C->getAPIntValue() == 1)
9058 Cond = Cond.getOperand(0);
9061 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9062 // setting operand in place of the X86ISD::SETCC.
9063 unsigned CondOpcode = Cond.getOpcode();
9064 if (CondOpcode == X86ISD::SETCC ||
9065 CondOpcode == X86ISD::SETCC_CARRY) {
9066 CC = Cond.getOperand(0);
9068 SDValue Cmp = Cond.getOperand(1);
9069 unsigned Opc = Cmp.getOpcode();
9070 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9071 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9075 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9079 // These can only come from an arithmetic instruction with overflow,
9080 // e.g. SADDO, UADDO.
9081 Cond = Cond.getNode()->getOperand(1);
9087 CondOpcode = Cond.getOpcode();
9088 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9089 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9090 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9091 Cond.getOperand(0).getValueType() != MVT::i8)) {
9092 SDValue LHS = Cond.getOperand(0);
9093 SDValue RHS = Cond.getOperand(1);
9097 switch (CondOpcode) {
9098 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9099 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9100 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9101 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9102 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9103 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9104 default: llvm_unreachable("unexpected overflowing operator");
9107 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9108 if (CondOpcode == ISD::UMULO)
9109 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9112 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9114 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9116 if (CondOpcode == ISD::UMULO)
9117 Cond = X86Op.getValue(2);
9119 Cond = X86Op.getValue(1);
9121 CC = DAG.getConstant(X86Cond, MVT::i8);
9125 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9126 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9127 if (CondOpc == ISD::OR) {
9128 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9129 // two branches instead of an explicit OR instruction with a
9131 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9132 isX86LogicalCmp(Cmp)) {
9133 CC = Cond.getOperand(0).getOperand(0);
9134 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9135 Chain, Dest, CC, Cmp);
9136 CC = Cond.getOperand(1).getOperand(0);
9140 } else { // ISD::AND
9141 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9142 // two branches instead of an explicit AND instruction with a
9143 // separate test. However, we only do this if this block doesn't
9144 // have a fall-through edge, because this requires an explicit
9145 // jmp when the condition is false.
9146 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9147 isX86LogicalCmp(Cmp) &&
9148 Op.getNode()->hasOneUse()) {
9149 X86::CondCode CCode =
9150 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9151 CCode = X86::GetOppositeBranchCondition(CCode);
9152 CC = DAG.getConstant(CCode, MVT::i8);
9153 SDNode *User = *Op.getNode()->use_begin();
9154 // Look for an unconditional branch following this conditional branch.
9155 // We need this because we need to reverse the successors in order
9156 // to implement FCMP_OEQ.
9157 if (User->getOpcode() == ISD::BR) {
9158 SDValue FalseBB = User->getOperand(1);
9160 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9161 assert(NewBR == User);
9165 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9166 Chain, Dest, CC, Cmp);
9167 X86::CondCode CCode =
9168 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9169 CCode = X86::GetOppositeBranchCondition(CCode);
9170 CC = DAG.getConstant(CCode, MVT::i8);
9176 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9177 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9178 // It should be transformed during dag combiner except when the condition
9179 // is set by a arithmetics with overflow node.
9180 X86::CondCode CCode =
9181 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9182 CCode = X86::GetOppositeBranchCondition(CCode);
9183 CC = DAG.getConstant(CCode, MVT::i8);
9184 Cond = Cond.getOperand(0).getOperand(1);
9186 } else if (Cond.getOpcode() == ISD::SETCC &&
9187 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9188 // For FCMP_OEQ, we can emit
9189 // two branches instead of an explicit AND instruction with a
9190 // separate test. However, we only do this if this block doesn't
9191 // have a fall-through edge, because this requires an explicit
9192 // jmp when the condition is false.
9193 if (Op.getNode()->hasOneUse()) {
9194 SDNode *User = *Op.getNode()->use_begin();
9195 // Look for an unconditional branch following this conditional branch.
9196 // We need this because we need to reverse the successors in order
9197 // to implement FCMP_OEQ.
9198 if (User->getOpcode() == ISD::BR) {
9199 SDValue FalseBB = User->getOperand(1);
9201 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9202 assert(NewBR == User);
9206 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9207 Cond.getOperand(0), Cond.getOperand(1));
9208 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9209 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9210 Chain, Dest, CC, Cmp);
9211 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9216 } else if (Cond.getOpcode() == ISD::SETCC &&
9217 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9218 // For FCMP_UNE, we can emit
9219 // two branches instead of an explicit AND instruction with a
9220 // separate test. However, we only do this if this block doesn't
9221 // have a fall-through edge, because this requires an explicit
9222 // jmp when the condition is false.
9223 if (Op.getNode()->hasOneUse()) {
9224 SDNode *User = *Op.getNode()->use_begin();
9225 // Look for an unconditional branch following this conditional branch.
9226 // We need this because we need to reverse the successors in order
9227 // to implement FCMP_UNE.
9228 if (User->getOpcode() == ISD::BR) {
9229 SDValue FalseBB = User->getOperand(1);
9231 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9232 assert(NewBR == User);
9235 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9236 Cond.getOperand(0), Cond.getOperand(1));
9237 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9238 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9239 Chain, Dest, CC, Cmp);
9240 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9250 // Look pass the truncate.
9251 if (Cond.getOpcode() == ISD::TRUNCATE)
9252 Cond = Cond.getOperand(0);
9254 // We know the result of AND is compared against zero. Try to match
9256 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9257 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9258 if (NewSetCC.getNode()) {
9259 CC = NewSetCC.getOperand(0);
9260 Cond = NewSetCC.getOperand(1);
9267 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9268 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9270 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9271 Chain, Dest, CC, Cond);
9275 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9276 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9277 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9278 // that the guard pages used by the OS virtual memory manager are allocated in
9279 // correct sequence.
9281 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9282 SelectionDAG &DAG) const {
9283 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9284 EnableSegmentedStacks) &&
9285 "This should be used only on Windows targets or when segmented stacks "
9287 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9288 DebugLoc dl = Op.getDebugLoc();
9291 SDValue Chain = Op.getOperand(0);
9292 SDValue Size = Op.getOperand(1);
9293 // FIXME: Ensure alignment here
9295 bool Is64Bit = Subtarget->is64Bit();
9296 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9298 if (EnableSegmentedStacks) {
9299 MachineFunction &MF = DAG.getMachineFunction();
9300 MachineRegisterInfo &MRI = MF.getRegInfo();
9303 // The 64 bit implementation of segmented stacks needs to clobber both r10
9304 // r11. This makes it impossible to use it along with nested parameters.
9305 const Function *F = MF.getFunction();
9307 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9309 if (I->hasNestAttr())
9310 report_fatal_error("Cannot use segmented stacks with functions that "
9311 "have nested arguments.");
9314 const TargetRegisterClass *AddrRegClass =
9315 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9316 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9317 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9318 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9319 DAG.getRegister(Vreg, SPTy));
9320 SDValue Ops1[2] = { Value, Chain };
9321 return DAG.getMergeValues(Ops1, 2, dl);
9324 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9326 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9327 Flag = Chain.getValue(1);
9328 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9330 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9331 Flag = Chain.getValue(1);
9333 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9335 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9336 return DAG.getMergeValues(Ops1, 2, dl);
9340 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9341 MachineFunction &MF = DAG.getMachineFunction();
9342 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9344 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9345 DebugLoc DL = Op.getDebugLoc();
9347 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9348 // vastart just stores the address of the VarArgsFrameIndex slot into the
9349 // memory location argument.
9350 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9352 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9353 MachinePointerInfo(SV), false, false, 0);
9357 // gp_offset (0 - 6 * 8)
9358 // fp_offset (48 - 48 + 8 * 16)
9359 // overflow_arg_area (point to parameters coming in memory).
9361 SmallVector<SDValue, 8> MemOps;
9362 SDValue FIN = Op.getOperand(1);
9364 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9365 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9367 FIN, MachinePointerInfo(SV), false, false, 0);
9368 MemOps.push_back(Store);
9371 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9372 FIN, DAG.getIntPtrConstant(4));
9373 Store = DAG.getStore(Op.getOperand(0), DL,
9374 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9376 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9377 MemOps.push_back(Store);
9379 // Store ptr to overflow_arg_area
9380 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9381 FIN, DAG.getIntPtrConstant(4));
9382 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9384 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9385 MachinePointerInfo(SV, 8),
9387 MemOps.push_back(Store);
9389 // Store ptr to reg_save_area.
9390 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9391 FIN, DAG.getIntPtrConstant(8));
9392 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9394 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9395 MachinePointerInfo(SV, 16), false, false, 0);
9396 MemOps.push_back(Store);
9397 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9398 &MemOps[0], MemOps.size());
9401 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9402 assert(Subtarget->is64Bit() &&
9403 "LowerVAARG only handles 64-bit va_arg!");
9404 assert((Subtarget->isTargetLinux() ||
9405 Subtarget->isTargetDarwin()) &&
9406 "Unhandled target in LowerVAARG");
9407 assert(Op.getNode()->getNumOperands() == 4);
9408 SDValue Chain = Op.getOperand(0);
9409 SDValue SrcPtr = Op.getOperand(1);
9410 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9411 unsigned Align = Op.getConstantOperandVal(3);
9412 DebugLoc dl = Op.getDebugLoc();
9414 EVT ArgVT = Op.getNode()->getValueType(0);
9415 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9416 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9419 // Decide which area this value should be read from.
9420 // TODO: Implement the AMD64 ABI in its entirety. This simple
9421 // selection mechanism works only for the basic types.
9422 if (ArgVT == MVT::f80) {
9423 llvm_unreachable("va_arg for f80 not yet implemented");
9424 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9425 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9426 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9427 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9429 llvm_unreachable("Unhandled argument type in LowerVAARG");
9433 // Sanity Check: Make sure using fp_offset makes sense.
9434 assert(!UseSoftFloat &&
9435 !(DAG.getMachineFunction()
9436 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9437 Subtarget->hasXMM());
9440 // Insert VAARG_64 node into the DAG
9441 // VAARG_64 returns two values: Variable Argument Address, Chain
9442 SmallVector<SDValue, 11> InstOps;
9443 InstOps.push_back(Chain);
9444 InstOps.push_back(SrcPtr);
9445 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9446 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9447 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9448 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9449 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9450 VTs, &InstOps[0], InstOps.size(),
9452 MachinePointerInfo(SV),
9457 Chain = VAARG.getValue(1);
9459 // Load the next argument and return it
9460 return DAG.getLoad(ArgVT, dl,
9463 MachinePointerInfo(),
9464 false, false, false, 0);
9467 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9468 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9469 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9470 SDValue Chain = Op.getOperand(0);
9471 SDValue DstPtr = Op.getOperand(1);
9472 SDValue SrcPtr = Op.getOperand(2);
9473 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9474 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9475 DebugLoc DL = Op.getDebugLoc();
9477 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9478 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9480 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9484 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9485 DebugLoc dl = Op.getDebugLoc();
9486 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9488 default: return SDValue(); // Don't custom lower most intrinsics.
9489 // Comparison intrinsics.
9490 case Intrinsic::x86_sse_comieq_ss:
9491 case Intrinsic::x86_sse_comilt_ss:
9492 case Intrinsic::x86_sse_comile_ss:
9493 case Intrinsic::x86_sse_comigt_ss:
9494 case Intrinsic::x86_sse_comige_ss:
9495 case Intrinsic::x86_sse_comineq_ss:
9496 case Intrinsic::x86_sse_ucomieq_ss:
9497 case Intrinsic::x86_sse_ucomilt_ss:
9498 case Intrinsic::x86_sse_ucomile_ss:
9499 case Intrinsic::x86_sse_ucomigt_ss:
9500 case Intrinsic::x86_sse_ucomige_ss:
9501 case Intrinsic::x86_sse_ucomineq_ss:
9502 case Intrinsic::x86_sse2_comieq_sd:
9503 case Intrinsic::x86_sse2_comilt_sd:
9504 case Intrinsic::x86_sse2_comile_sd:
9505 case Intrinsic::x86_sse2_comigt_sd:
9506 case Intrinsic::x86_sse2_comige_sd:
9507 case Intrinsic::x86_sse2_comineq_sd:
9508 case Intrinsic::x86_sse2_ucomieq_sd:
9509 case Intrinsic::x86_sse2_ucomilt_sd:
9510 case Intrinsic::x86_sse2_ucomile_sd:
9511 case Intrinsic::x86_sse2_ucomigt_sd:
9512 case Intrinsic::x86_sse2_ucomige_sd:
9513 case Intrinsic::x86_sse2_ucomineq_sd: {
9515 ISD::CondCode CC = ISD::SETCC_INVALID;
9518 case Intrinsic::x86_sse_comieq_ss:
9519 case Intrinsic::x86_sse2_comieq_sd:
9523 case Intrinsic::x86_sse_comilt_ss:
9524 case Intrinsic::x86_sse2_comilt_sd:
9528 case Intrinsic::x86_sse_comile_ss:
9529 case Intrinsic::x86_sse2_comile_sd:
9533 case Intrinsic::x86_sse_comigt_ss:
9534 case Intrinsic::x86_sse2_comigt_sd:
9538 case Intrinsic::x86_sse_comige_ss:
9539 case Intrinsic::x86_sse2_comige_sd:
9543 case Intrinsic::x86_sse_comineq_ss:
9544 case Intrinsic::x86_sse2_comineq_sd:
9548 case Intrinsic::x86_sse_ucomieq_ss:
9549 case Intrinsic::x86_sse2_ucomieq_sd:
9550 Opc = X86ISD::UCOMI;
9553 case Intrinsic::x86_sse_ucomilt_ss:
9554 case Intrinsic::x86_sse2_ucomilt_sd:
9555 Opc = X86ISD::UCOMI;
9558 case Intrinsic::x86_sse_ucomile_ss:
9559 case Intrinsic::x86_sse2_ucomile_sd:
9560 Opc = X86ISD::UCOMI;
9563 case Intrinsic::x86_sse_ucomigt_ss:
9564 case Intrinsic::x86_sse2_ucomigt_sd:
9565 Opc = X86ISD::UCOMI;
9568 case Intrinsic::x86_sse_ucomige_ss:
9569 case Intrinsic::x86_sse2_ucomige_sd:
9570 Opc = X86ISD::UCOMI;
9573 case Intrinsic::x86_sse_ucomineq_ss:
9574 case Intrinsic::x86_sse2_ucomineq_sd:
9575 Opc = X86ISD::UCOMI;
9580 SDValue LHS = Op.getOperand(1);
9581 SDValue RHS = Op.getOperand(2);
9582 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9583 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9584 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9585 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9586 DAG.getConstant(X86CC, MVT::i8), Cond);
9587 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9589 // Arithmetic intrinsics.
9590 case Intrinsic::x86_sse3_hadd_ps:
9591 case Intrinsic::x86_sse3_hadd_pd:
9592 case Intrinsic::x86_avx_hadd_ps_256:
9593 case Intrinsic::x86_avx_hadd_pd_256:
9594 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9595 Op.getOperand(1), Op.getOperand(2));
9596 case Intrinsic::x86_sse3_hsub_ps:
9597 case Intrinsic::x86_sse3_hsub_pd:
9598 case Intrinsic::x86_avx_hsub_ps_256:
9599 case Intrinsic::x86_avx_hsub_pd_256:
9600 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9601 Op.getOperand(1), Op.getOperand(2));
9602 case Intrinsic::x86_avx2_psllv_d:
9603 case Intrinsic::x86_avx2_psllv_q:
9604 case Intrinsic::x86_avx2_psllv_d_256:
9605 case Intrinsic::x86_avx2_psllv_q_256:
9606 return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9607 Op.getOperand(1), Op.getOperand(2));
9608 case Intrinsic::x86_avx2_psrlv_d:
9609 case Intrinsic::x86_avx2_psrlv_q:
9610 case Intrinsic::x86_avx2_psrlv_d_256:
9611 case Intrinsic::x86_avx2_psrlv_q_256:
9612 return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9613 Op.getOperand(1), Op.getOperand(2));
9614 case Intrinsic::x86_avx2_psrav_d:
9615 case Intrinsic::x86_avx2_psrav_d_256:
9616 return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9617 Op.getOperand(1), Op.getOperand(2));
9619 // ptest and testp intrinsics. The intrinsic these come from are designed to
9620 // return an integer value, not just an instruction so lower it to the ptest
9621 // or testp pattern and a setcc for the result.
9622 case Intrinsic::x86_sse41_ptestz:
9623 case Intrinsic::x86_sse41_ptestc:
9624 case Intrinsic::x86_sse41_ptestnzc:
9625 case Intrinsic::x86_avx_ptestz_256:
9626 case Intrinsic::x86_avx_ptestc_256:
9627 case Intrinsic::x86_avx_ptestnzc_256:
9628 case Intrinsic::x86_avx_vtestz_ps:
9629 case Intrinsic::x86_avx_vtestc_ps:
9630 case Intrinsic::x86_avx_vtestnzc_ps:
9631 case Intrinsic::x86_avx_vtestz_pd:
9632 case Intrinsic::x86_avx_vtestc_pd:
9633 case Intrinsic::x86_avx_vtestnzc_pd:
9634 case Intrinsic::x86_avx_vtestz_ps_256:
9635 case Intrinsic::x86_avx_vtestc_ps_256:
9636 case Intrinsic::x86_avx_vtestnzc_ps_256:
9637 case Intrinsic::x86_avx_vtestz_pd_256:
9638 case Intrinsic::x86_avx_vtestc_pd_256:
9639 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9640 bool IsTestPacked = false;
9643 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9644 case Intrinsic::x86_avx_vtestz_ps:
9645 case Intrinsic::x86_avx_vtestz_pd:
9646 case Intrinsic::x86_avx_vtestz_ps_256:
9647 case Intrinsic::x86_avx_vtestz_pd_256:
9648 IsTestPacked = true; // Fallthrough
9649 case Intrinsic::x86_sse41_ptestz:
9650 case Intrinsic::x86_avx_ptestz_256:
9652 X86CC = X86::COND_E;
9654 case Intrinsic::x86_avx_vtestc_ps:
9655 case Intrinsic::x86_avx_vtestc_pd:
9656 case Intrinsic::x86_avx_vtestc_ps_256:
9657 case Intrinsic::x86_avx_vtestc_pd_256:
9658 IsTestPacked = true; // Fallthrough
9659 case Intrinsic::x86_sse41_ptestc:
9660 case Intrinsic::x86_avx_ptestc_256:
9662 X86CC = X86::COND_B;
9664 case Intrinsic::x86_avx_vtestnzc_ps:
9665 case Intrinsic::x86_avx_vtestnzc_pd:
9666 case Intrinsic::x86_avx_vtestnzc_ps_256:
9667 case Intrinsic::x86_avx_vtestnzc_pd_256:
9668 IsTestPacked = true; // Fallthrough
9669 case Intrinsic::x86_sse41_ptestnzc:
9670 case Intrinsic::x86_avx_ptestnzc_256:
9672 X86CC = X86::COND_A;
9676 SDValue LHS = Op.getOperand(1);
9677 SDValue RHS = Op.getOperand(2);
9678 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9679 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9680 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9681 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9682 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9685 // Fix vector shift instructions where the last operand is a non-immediate
9687 case Intrinsic::x86_avx2_pslli_w:
9688 case Intrinsic::x86_avx2_pslli_d:
9689 case Intrinsic::x86_avx2_pslli_q:
9690 case Intrinsic::x86_avx2_psrli_w:
9691 case Intrinsic::x86_avx2_psrli_d:
9692 case Intrinsic::x86_avx2_psrli_q:
9693 case Intrinsic::x86_avx2_psrai_w:
9694 case Intrinsic::x86_avx2_psrai_d:
9695 case Intrinsic::x86_sse2_pslli_w:
9696 case Intrinsic::x86_sse2_pslli_d:
9697 case Intrinsic::x86_sse2_pslli_q:
9698 case Intrinsic::x86_sse2_psrli_w:
9699 case Intrinsic::x86_sse2_psrli_d:
9700 case Intrinsic::x86_sse2_psrli_q:
9701 case Intrinsic::x86_sse2_psrai_w:
9702 case Intrinsic::x86_sse2_psrai_d:
9703 case Intrinsic::x86_mmx_pslli_w:
9704 case Intrinsic::x86_mmx_pslli_d:
9705 case Intrinsic::x86_mmx_pslli_q:
9706 case Intrinsic::x86_mmx_psrli_w:
9707 case Intrinsic::x86_mmx_psrli_d:
9708 case Intrinsic::x86_mmx_psrli_q:
9709 case Intrinsic::x86_mmx_psrai_w:
9710 case Intrinsic::x86_mmx_psrai_d: {
9711 SDValue ShAmt = Op.getOperand(2);
9712 if (isa<ConstantSDNode>(ShAmt))
9715 unsigned NewIntNo = 0;
9716 EVT ShAmtVT = MVT::v4i32;
9718 case Intrinsic::x86_sse2_pslli_w:
9719 NewIntNo = Intrinsic::x86_sse2_psll_w;
9721 case Intrinsic::x86_sse2_pslli_d:
9722 NewIntNo = Intrinsic::x86_sse2_psll_d;
9724 case Intrinsic::x86_sse2_pslli_q:
9725 NewIntNo = Intrinsic::x86_sse2_psll_q;
9727 case Intrinsic::x86_sse2_psrli_w:
9728 NewIntNo = Intrinsic::x86_sse2_psrl_w;
9730 case Intrinsic::x86_sse2_psrli_d:
9731 NewIntNo = Intrinsic::x86_sse2_psrl_d;
9733 case Intrinsic::x86_sse2_psrli_q:
9734 NewIntNo = Intrinsic::x86_sse2_psrl_q;
9736 case Intrinsic::x86_sse2_psrai_w:
9737 NewIntNo = Intrinsic::x86_sse2_psra_w;
9739 case Intrinsic::x86_sse2_psrai_d:
9740 NewIntNo = Intrinsic::x86_sse2_psra_d;
9742 case Intrinsic::x86_avx2_pslli_w:
9743 NewIntNo = Intrinsic::x86_avx2_psll_w;
9745 case Intrinsic::x86_avx2_pslli_d:
9746 NewIntNo = Intrinsic::x86_avx2_psll_d;
9748 case Intrinsic::x86_avx2_pslli_q:
9749 NewIntNo = Intrinsic::x86_avx2_psll_q;
9751 case Intrinsic::x86_avx2_psrli_w:
9752 NewIntNo = Intrinsic::x86_avx2_psrl_w;
9754 case Intrinsic::x86_avx2_psrli_d:
9755 NewIntNo = Intrinsic::x86_avx2_psrl_d;
9757 case Intrinsic::x86_avx2_psrli_q:
9758 NewIntNo = Intrinsic::x86_avx2_psrl_q;
9760 case Intrinsic::x86_avx2_psrai_w:
9761 NewIntNo = Intrinsic::x86_avx2_psra_w;
9763 case Intrinsic::x86_avx2_psrai_d:
9764 NewIntNo = Intrinsic::x86_avx2_psra_d;
9767 ShAmtVT = MVT::v2i32;
9769 case Intrinsic::x86_mmx_pslli_w:
9770 NewIntNo = Intrinsic::x86_mmx_psll_w;
9772 case Intrinsic::x86_mmx_pslli_d:
9773 NewIntNo = Intrinsic::x86_mmx_psll_d;
9775 case Intrinsic::x86_mmx_pslli_q:
9776 NewIntNo = Intrinsic::x86_mmx_psll_q;
9778 case Intrinsic::x86_mmx_psrli_w:
9779 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9781 case Intrinsic::x86_mmx_psrli_d:
9782 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9784 case Intrinsic::x86_mmx_psrli_q:
9785 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9787 case Intrinsic::x86_mmx_psrai_w:
9788 NewIntNo = Intrinsic::x86_mmx_psra_w;
9790 case Intrinsic::x86_mmx_psrai_d:
9791 NewIntNo = Intrinsic::x86_mmx_psra_d;
9793 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9799 // The vector shift intrinsics with scalars uses 32b shift amounts but
9800 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9804 ShOps[1] = DAG.getConstant(0, MVT::i32);
9805 if (ShAmtVT == MVT::v4i32) {
9806 ShOps[2] = DAG.getUNDEF(MVT::i32);
9807 ShOps[3] = DAG.getUNDEF(MVT::i32);
9808 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9810 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9811 // FIXME this must be lowered to get rid of the invalid type.
9814 EVT VT = Op.getValueType();
9815 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9816 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9817 DAG.getConstant(NewIntNo, MVT::i32),
9818 Op.getOperand(1), ShAmt);
9823 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9824 SelectionDAG &DAG) const {
9825 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9826 MFI->setReturnAddressIsTaken(true);
9828 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9829 DebugLoc dl = Op.getDebugLoc();
9832 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9834 DAG.getConstant(TD->getPointerSize(),
9835 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9836 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9837 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9839 MachinePointerInfo(), false, false, false, 0);
9842 // Just load the return address.
9843 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9844 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9845 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9848 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9849 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9850 MFI->setFrameAddressIsTaken(true);
9852 EVT VT = Op.getValueType();
9853 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9854 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9855 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9856 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9858 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9859 MachinePointerInfo(),
9860 false, false, false, 0);
9864 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9865 SelectionDAG &DAG) const {
9866 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9869 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9870 MachineFunction &MF = DAG.getMachineFunction();
9871 SDValue Chain = Op.getOperand(0);
9872 SDValue Offset = Op.getOperand(1);
9873 SDValue Handler = Op.getOperand(2);
9874 DebugLoc dl = Op.getDebugLoc();
9876 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9877 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9879 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9881 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9882 DAG.getIntPtrConstant(TD->getPointerSize()));
9883 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9884 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9886 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9887 MF.getRegInfo().addLiveOut(StoreAddrReg);
9889 return DAG.getNode(X86ISD::EH_RETURN, dl,
9891 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9894 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9895 SelectionDAG &DAG) const {
9896 return Op.getOperand(0);
9899 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9900 SelectionDAG &DAG) const {
9901 SDValue Root = Op.getOperand(0);
9902 SDValue Trmp = Op.getOperand(1); // trampoline
9903 SDValue FPtr = Op.getOperand(2); // nested function
9904 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9905 DebugLoc dl = Op.getDebugLoc();
9907 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9909 if (Subtarget->is64Bit()) {
9910 SDValue OutChains[6];
9912 // Large code-model.
9913 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
9914 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9916 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9917 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9919 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9921 // Load the pointer to the nested function into R11.
9922 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9923 SDValue Addr = Trmp;
9924 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9925 Addr, MachinePointerInfo(TrmpAddr),
9928 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9929 DAG.getConstant(2, MVT::i64));
9930 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9931 MachinePointerInfo(TrmpAddr, 2),
9934 // Load the 'nest' parameter value into R10.
9935 // R10 is specified in X86CallingConv.td
9936 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9937 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9938 DAG.getConstant(10, MVT::i64));
9939 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9940 Addr, MachinePointerInfo(TrmpAddr, 10),
9943 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9944 DAG.getConstant(12, MVT::i64));
9945 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9946 MachinePointerInfo(TrmpAddr, 12),
9949 // Jump to the nested function.
9950 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9951 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9952 DAG.getConstant(20, MVT::i64));
9953 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9954 Addr, MachinePointerInfo(TrmpAddr, 20),
9957 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9958 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9959 DAG.getConstant(22, MVT::i64));
9960 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9961 MachinePointerInfo(TrmpAddr, 22),
9964 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9966 const Function *Func =
9967 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9968 CallingConv::ID CC = Func->getCallingConv();
9973 llvm_unreachable("Unsupported calling convention");
9974 case CallingConv::C:
9975 case CallingConv::X86_StdCall: {
9976 // Pass 'nest' parameter in ECX.
9977 // Must be kept in sync with X86CallingConv.td
9980 // Check that ECX wasn't needed by an 'inreg' parameter.
9981 FunctionType *FTy = Func->getFunctionType();
9982 const AttrListPtr &Attrs = Func->getAttributes();
9984 if (!Attrs.isEmpty() && !Func->isVarArg()) {
9985 unsigned InRegCount = 0;
9988 for (FunctionType::param_iterator I = FTy->param_begin(),
9989 E = FTy->param_end(); I != E; ++I, ++Idx)
9990 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9991 // FIXME: should only count parameters that are lowered to integers.
9992 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9994 if (InRegCount > 2) {
9995 report_fatal_error("Nest register in use - reduce number of inreg"
10001 case CallingConv::X86_FastCall:
10002 case CallingConv::X86_ThisCall:
10003 case CallingConv::Fast:
10004 // Pass 'nest' parameter in EAX.
10005 // Must be kept in sync with X86CallingConv.td
10006 NestReg = X86::EAX;
10010 SDValue OutChains[4];
10011 SDValue Addr, Disp;
10013 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10014 DAG.getConstant(10, MVT::i32));
10015 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10017 // This is storing the opcode for MOV32ri.
10018 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10019 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10020 OutChains[0] = DAG.getStore(Root, dl,
10021 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10022 Trmp, MachinePointerInfo(TrmpAddr),
10025 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10026 DAG.getConstant(1, MVT::i32));
10027 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10028 MachinePointerInfo(TrmpAddr, 1),
10031 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10032 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10033 DAG.getConstant(5, MVT::i32));
10034 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10035 MachinePointerInfo(TrmpAddr, 5),
10038 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10039 DAG.getConstant(6, MVT::i32));
10040 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10041 MachinePointerInfo(TrmpAddr, 6),
10044 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10048 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10049 SelectionDAG &DAG) const {
10051 The rounding mode is in bits 11:10 of FPSR, and has the following
10053 00 Round to nearest
10058 FLT_ROUNDS, on the other hand, expects the following:
10065 To perform the conversion, we do:
10066 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10069 MachineFunction &MF = DAG.getMachineFunction();
10070 const TargetMachine &TM = MF.getTarget();
10071 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10072 unsigned StackAlignment = TFI.getStackAlignment();
10073 EVT VT = Op.getValueType();
10074 DebugLoc DL = Op.getDebugLoc();
10076 // Save FP Control Word to stack slot
10077 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10078 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10081 MachineMemOperand *MMO =
10082 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10083 MachineMemOperand::MOStore, 2, 2);
10085 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10086 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10087 DAG.getVTList(MVT::Other),
10088 Ops, 2, MVT::i16, MMO);
10090 // Load FP Control Word from stack slot
10091 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10092 MachinePointerInfo(), false, false, false, 0);
10094 // Transform as necessary
10096 DAG.getNode(ISD::SRL, DL, MVT::i16,
10097 DAG.getNode(ISD::AND, DL, MVT::i16,
10098 CWD, DAG.getConstant(0x800, MVT::i16)),
10099 DAG.getConstant(11, MVT::i8));
10101 DAG.getNode(ISD::SRL, DL, MVT::i16,
10102 DAG.getNode(ISD::AND, DL, MVT::i16,
10103 CWD, DAG.getConstant(0x400, MVT::i16)),
10104 DAG.getConstant(9, MVT::i8));
10107 DAG.getNode(ISD::AND, DL, MVT::i16,
10108 DAG.getNode(ISD::ADD, DL, MVT::i16,
10109 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10110 DAG.getConstant(1, MVT::i16)),
10111 DAG.getConstant(3, MVT::i16));
10114 return DAG.getNode((VT.getSizeInBits() < 16 ?
10115 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10118 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10119 EVT VT = Op.getValueType();
10121 unsigned NumBits = VT.getSizeInBits();
10122 DebugLoc dl = Op.getDebugLoc();
10124 Op = Op.getOperand(0);
10125 if (VT == MVT::i8) {
10126 // Zero extend to i32 since there is not an i8 bsr.
10128 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10131 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10132 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10133 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10135 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10138 DAG.getConstant(NumBits+NumBits-1, OpVT),
10139 DAG.getConstant(X86::COND_E, MVT::i8),
10142 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10144 // Finally xor with NumBits-1.
10145 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10148 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10152 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10153 EVT VT = Op.getValueType();
10155 unsigned NumBits = VT.getSizeInBits();
10156 DebugLoc dl = Op.getDebugLoc();
10158 Op = Op.getOperand(0);
10159 if (VT == MVT::i8) {
10161 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10164 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10165 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10166 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10168 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10171 DAG.getConstant(NumBits, OpVT),
10172 DAG.getConstant(X86::COND_E, MVT::i8),
10175 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10178 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10182 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10183 // ones, and then concatenate the result back.
10184 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10185 EVT VT = Op.getValueType();
10187 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10188 "Unsupported value type for operation");
10190 int NumElems = VT.getVectorNumElements();
10191 DebugLoc dl = Op.getDebugLoc();
10192 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10193 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10195 // Extract the LHS vectors
10196 SDValue LHS = Op.getOperand(0);
10197 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10198 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10200 // Extract the RHS vectors
10201 SDValue RHS = Op.getOperand(1);
10202 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
10203 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
10205 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10206 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10208 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10209 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10210 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10213 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10214 assert(Op.getValueType().getSizeInBits() == 256 &&
10215 Op.getValueType().isInteger() &&
10216 "Only handle AVX 256-bit vector integer operation");
10217 return Lower256IntArith(Op, DAG);
10220 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10221 assert(Op.getValueType().getSizeInBits() == 256 &&
10222 Op.getValueType().isInteger() &&
10223 "Only handle AVX 256-bit vector integer operation");
10224 return Lower256IntArith(Op, DAG);
10227 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10228 EVT VT = Op.getValueType();
10230 // Decompose 256-bit ops into smaller 128-bit ops.
10231 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10232 return Lower256IntArith(Op, DAG);
10234 DebugLoc dl = Op.getDebugLoc();
10236 SDValue A = Op.getOperand(0);
10237 SDValue B = Op.getOperand(1);
10239 if (VT == MVT::v4i64) {
10240 assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
10242 // ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
10243 // ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
10244 // ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
10245 // ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
10246 // ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
10248 // AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
10249 // AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
10250 // return AloBlo + AloBhi + AhiBlo;
10252 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10253 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10254 A, DAG.getConstant(32, MVT::i32));
10255 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10256 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10257 B, DAG.getConstant(32, MVT::i32));
10258 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10259 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10261 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10262 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10264 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10265 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10267 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10268 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10269 AloBhi, DAG.getConstant(32, MVT::i32));
10270 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10271 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10272 AhiBlo, DAG.getConstant(32, MVT::i32));
10273 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10274 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10278 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
10280 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
10281 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
10282 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
10283 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
10284 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
10286 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
10287 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
10288 // return AloBlo + AloBhi + AhiBlo;
10290 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10291 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10292 A, DAG.getConstant(32, MVT::i32));
10293 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10294 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10295 B, DAG.getConstant(32, MVT::i32));
10296 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10297 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10299 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10300 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10302 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10303 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10305 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10306 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10307 AloBhi, DAG.getConstant(32, MVT::i32));
10308 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10309 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10310 AhiBlo, DAG.getConstant(32, MVT::i32));
10311 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10312 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10316 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10318 EVT VT = Op.getValueType();
10319 DebugLoc dl = Op.getDebugLoc();
10320 SDValue R = Op.getOperand(0);
10321 SDValue Amt = Op.getOperand(1);
10322 LLVMContext *Context = DAG.getContext();
10324 if (!Subtarget->hasXMMInt())
10327 // Optimize shl/srl/sra with constant shift amount.
10328 if (isSplatVector(Amt.getNode())) {
10329 SDValue SclrAmt = Amt->getOperand(0);
10330 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10331 uint64_t ShiftAmt = C->getZExtValue();
10333 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10334 // Make a large shift.
10336 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10337 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10338 R, DAG.getConstant(ShiftAmt, MVT::i32));
10339 // Zero out the rightmost bits.
10340 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10342 return DAG.getNode(ISD::AND, dl, VT, SHL,
10343 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10346 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10347 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10348 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10349 R, DAG.getConstant(ShiftAmt, MVT::i32));
10351 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10352 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10353 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10354 R, DAG.getConstant(ShiftAmt, MVT::i32));
10356 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10357 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10358 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10359 R, DAG.getConstant(ShiftAmt, MVT::i32));
10361 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10362 // Make a large shift.
10364 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10365 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10366 R, DAG.getConstant(ShiftAmt, MVT::i32));
10367 // Zero out the leftmost bits.
10368 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10370 return DAG.getNode(ISD::AND, dl, VT, SRL,
10371 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10374 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10375 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10376 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10377 R, DAG.getConstant(ShiftAmt, MVT::i32));
10379 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10380 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10381 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10382 R, DAG.getConstant(ShiftAmt, MVT::i32));
10384 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10385 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10386 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10387 R, DAG.getConstant(ShiftAmt, MVT::i32));
10389 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10390 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10391 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10392 R, DAG.getConstant(ShiftAmt, MVT::i32));
10394 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10395 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10396 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10397 R, DAG.getConstant(ShiftAmt, MVT::i32));
10399 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10400 if (ShiftAmt == 7) {
10401 // R s>> 7 === R s< 0
10402 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10403 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10406 // R s>> a === ((R u>> a) ^ m) - m
10407 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10408 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10410 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10411 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10412 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10416 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10417 if (Op.getOpcode() == ISD::SHL) {
10418 // Make a large shift.
10420 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10421 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
10422 R, DAG.getConstant(ShiftAmt, MVT::i32));
10423 // Zero out the rightmost bits.
10424 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10426 return DAG.getNode(ISD::AND, dl, VT, SHL,
10427 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10429 if (Op.getOpcode() == ISD::SRL) {
10430 // Make a large shift.
10432 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10433 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
10434 R, DAG.getConstant(ShiftAmt, MVT::i32));
10435 // Zero out the leftmost bits.
10436 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10438 return DAG.getNode(ISD::AND, dl, VT, SRL,
10439 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10441 if (Op.getOpcode() == ISD::SRA) {
10442 if (ShiftAmt == 7) {
10443 // R s>> 7 === R s< 0
10444 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10445 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10448 // R s>> a === ((R u>> a) ^ m) - m
10449 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10450 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10452 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10453 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10454 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10461 // Lower SHL with variable shift amount.
10462 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10463 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10464 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10465 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10467 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10469 std::vector<Constant*> CV(4, CI);
10470 Constant *C = ConstantVector::get(CV);
10471 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10472 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10473 MachinePointerInfo::getConstantPool(),
10474 false, false, false, 16);
10476 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10477 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10478 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10479 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10481 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10483 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10484 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10485 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10487 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
10488 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
10490 std::vector<Constant*> CVM1(16, CM1);
10491 std::vector<Constant*> CVM2(16, CM2);
10492 Constant *C = ConstantVector::get(CVM1);
10493 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10494 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10495 MachinePointerInfo::getConstantPool(),
10496 false, false, false, 16);
10498 // r = pblendv(r, psllw(r & (char16)15, 4), a);
10499 M = DAG.getNode(ISD::AND, dl, VT, R, M);
10500 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10501 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10502 DAG.getConstant(4, MVT::i32));
10503 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10505 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10507 C = ConstantVector::get(CVM2);
10508 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10509 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10510 MachinePointerInfo::getConstantPool(),
10511 false, false, false, 16);
10513 // r = pblendv(r, psllw(r & (char16)63, 2), a);
10514 M = DAG.getNode(ISD::AND, dl, VT, R, M);
10515 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10516 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10517 DAG.getConstant(2, MVT::i32));
10518 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10520 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10522 // return pblendv(r, r+r, a);
10523 R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10524 R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10528 // Decompose 256-bit shifts into smaller 128-bit shifts.
10529 if (VT.getSizeInBits() == 256) {
10530 int NumElems = VT.getVectorNumElements();
10531 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10532 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10534 // Extract the two vectors
10535 SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10536 SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10539 // Recreate the shift amount vectors
10540 SDValue Amt1, Amt2;
10541 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10542 // Constant shift amount
10543 SmallVector<SDValue, 4> Amt1Csts;
10544 SmallVector<SDValue, 4> Amt2Csts;
10545 for (int i = 0; i < NumElems/2; ++i)
10546 Amt1Csts.push_back(Amt->getOperand(i));
10547 for (int i = NumElems/2; i < NumElems; ++i)
10548 Amt2Csts.push_back(Amt->getOperand(i));
10550 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10551 &Amt1Csts[0], NumElems/2);
10552 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10553 &Amt2Csts[0], NumElems/2);
10555 // Variable shift amount
10556 Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10557 Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10561 // Issue new vector shifts for the smaller types
10562 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10563 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10565 // Concatenate the result back
10566 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10572 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10573 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10574 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10575 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10576 // has only one use.
10577 SDNode *N = Op.getNode();
10578 SDValue LHS = N->getOperand(0);
10579 SDValue RHS = N->getOperand(1);
10580 unsigned BaseOp = 0;
10582 DebugLoc DL = Op.getDebugLoc();
10583 switch (Op.getOpcode()) {
10584 default: llvm_unreachable("Unknown ovf instruction!");
10586 // A subtract of one will be selected as a INC. Note that INC doesn't
10587 // set CF, so we can't do this for UADDO.
10588 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10590 BaseOp = X86ISD::INC;
10591 Cond = X86::COND_O;
10594 BaseOp = X86ISD::ADD;
10595 Cond = X86::COND_O;
10598 BaseOp = X86ISD::ADD;
10599 Cond = X86::COND_B;
10602 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10603 // set CF, so we can't do this for USUBO.
10604 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10606 BaseOp = X86ISD::DEC;
10607 Cond = X86::COND_O;
10610 BaseOp = X86ISD::SUB;
10611 Cond = X86::COND_O;
10614 BaseOp = X86ISD::SUB;
10615 Cond = X86::COND_B;
10618 BaseOp = X86ISD::SMUL;
10619 Cond = X86::COND_O;
10621 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10622 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10624 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10627 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10628 DAG.getConstant(X86::COND_O, MVT::i32),
10629 SDValue(Sum.getNode(), 2));
10631 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10635 // Also sets EFLAGS.
10636 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10637 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10640 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10641 DAG.getConstant(Cond, MVT::i32),
10642 SDValue(Sum.getNode(), 1));
10644 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10647 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10648 DebugLoc dl = Op.getDebugLoc();
10649 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10650 EVT VT = Op.getValueType();
10652 if (Subtarget->hasXMMInt() && VT.isVector()) {
10653 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10654 ExtraVT.getScalarType().getSizeInBits();
10655 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10657 unsigned SHLIntrinsicsID = 0;
10658 unsigned SRAIntrinsicsID = 0;
10659 switch (VT.getSimpleVT().SimpleTy) {
10663 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10664 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10667 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10668 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10672 if (!Subtarget->hasAVX())
10674 if (!Subtarget->hasAVX2()) {
10675 // needs to be split
10676 int NumElems = VT.getVectorNumElements();
10677 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10678 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10680 // Extract the LHS vectors
10681 SDValue LHS = Op.getOperand(0);
10682 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10683 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10685 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10686 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10688 EVT ExtraEltVT = ExtraVT.getVectorElementType();
10689 int ExtraNumElems = ExtraVT.getVectorNumElements();
10690 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10692 SDValue Extra = DAG.getValueType(ExtraVT);
10694 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10695 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10697 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10699 if (VT == MVT::v8i32) {
10700 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_d;
10701 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_d;
10703 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_w;
10704 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_w;
10708 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10709 DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10710 Op.getOperand(0), ShAmt);
10712 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10713 DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10721 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10722 DebugLoc dl = Op.getDebugLoc();
10724 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10725 // There isn't any reason to disable it if the target processor supports it.
10726 if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10727 SDValue Chain = Op.getOperand(0);
10728 SDValue Zero = DAG.getConstant(0, MVT::i32);
10730 DAG.getRegister(X86::ESP, MVT::i32), // Base
10731 DAG.getTargetConstant(1, MVT::i8), // Scale
10732 DAG.getRegister(0, MVT::i32), // Index
10733 DAG.getTargetConstant(0, MVT::i32), // Disp
10734 DAG.getRegister(0, MVT::i32), // Segment.
10739 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10740 array_lengthof(Ops));
10741 return SDValue(Res, 0);
10744 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10746 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10748 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10749 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10750 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10751 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10753 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10754 if (!Op1 && !Op2 && !Op3 && Op4)
10755 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10757 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10758 if (Op1 && !Op2 && !Op3 && !Op4)
10759 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10761 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10763 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10766 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10767 SelectionDAG &DAG) const {
10768 DebugLoc dl = Op.getDebugLoc();
10769 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10770 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10771 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10772 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10774 // The only fence that needs an instruction is a sequentially-consistent
10775 // cross-thread fence.
10776 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10777 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10778 // no-sse2). There isn't any reason to disable it if the target processor
10780 if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10781 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10783 SDValue Chain = Op.getOperand(0);
10784 SDValue Zero = DAG.getConstant(0, MVT::i32);
10786 DAG.getRegister(X86::ESP, MVT::i32), // Base
10787 DAG.getTargetConstant(1, MVT::i8), // Scale
10788 DAG.getRegister(0, MVT::i32), // Index
10789 DAG.getTargetConstant(0, MVT::i32), // Disp
10790 DAG.getRegister(0, MVT::i32), // Segment.
10795 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10796 array_lengthof(Ops));
10797 return SDValue(Res, 0);
10800 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10801 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10805 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10806 EVT T = Op.getValueType();
10807 DebugLoc DL = Op.getDebugLoc();
10810 switch(T.getSimpleVT().SimpleTy) {
10812 assert(false && "Invalid value type!");
10813 case MVT::i8: Reg = X86::AL; size = 1; break;
10814 case MVT::i16: Reg = X86::AX; size = 2; break;
10815 case MVT::i32: Reg = X86::EAX; size = 4; break;
10817 assert(Subtarget->is64Bit() && "Node not type legal!");
10818 Reg = X86::RAX; size = 8;
10821 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10822 Op.getOperand(2), SDValue());
10823 SDValue Ops[] = { cpIn.getValue(0),
10826 DAG.getTargetConstant(size, MVT::i8),
10827 cpIn.getValue(1) };
10828 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10829 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10830 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10833 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10837 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10838 SelectionDAG &DAG) const {
10839 assert(Subtarget->is64Bit() && "Result not type legalized?");
10840 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10841 SDValue TheChain = Op.getOperand(0);
10842 DebugLoc dl = Op.getDebugLoc();
10843 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10844 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10845 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10847 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10848 DAG.getConstant(32, MVT::i8));
10850 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10853 return DAG.getMergeValues(Ops, 2, dl);
10856 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10857 SelectionDAG &DAG) const {
10858 EVT SrcVT = Op.getOperand(0).getValueType();
10859 EVT DstVT = Op.getValueType();
10860 assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10861 Subtarget->hasMMX() && "Unexpected custom BITCAST");
10862 assert((DstVT == MVT::i64 ||
10863 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10864 "Unexpected custom BITCAST");
10865 // i64 <=> MMX conversions are Legal.
10866 if (SrcVT==MVT::i64 && DstVT.isVector())
10868 if (DstVT==MVT::i64 && SrcVT.isVector())
10870 // MMX <=> MMX conversions are Legal.
10871 if (SrcVT.isVector() && DstVT.isVector())
10873 // All other conversions need to be expanded.
10877 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10878 SDNode *Node = Op.getNode();
10879 DebugLoc dl = Node->getDebugLoc();
10880 EVT T = Node->getValueType(0);
10881 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10882 DAG.getConstant(0, T), Node->getOperand(2));
10883 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10884 cast<AtomicSDNode>(Node)->getMemoryVT(),
10885 Node->getOperand(0),
10886 Node->getOperand(1), negOp,
10887 cast<AtomicSDNode>(Node)->getSrcValue(),
10888 cast<AtomicSDNode>(Node)->getAlignment(),
10889 cast<AtomicSDNode>(Node)->getOrdering(),
10890 cast<AtomicSDNode>(Node)->getSynchScope());
10893 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10894 SDNode *Node = Op.getNode();
10895 DebugLoc dl = Node->getDebugLoc();
10896 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10898 // Convert seq_cst store -> xchg
10899 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10900 // FIXME: On 32-bit, store -> fist or movq would be more efficient
10901 // (The only way to get a 16-byte store is cmpxchg16b)
10902 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10903 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10904 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10905 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10906 cast<AtomicSDNode>(Node)->getMemoryVT(),
10907 Node->getOperand(0),
10908 Node->getOperand(1), Node->getOperand(2),
10909 cast<AtomicSDNode>(Node)->getMemOperand(),
10910 cast<AtomicSDNode>(Node)->getOrdering(),
10911 cast<AtomicSDNode>(Node)->getSynchScope());
10912 return Swap.getValue(1);
10914 // Other atomic stores have a simple pattern.
10918 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10919 EVT VT = Op.getNode()->getValueType(0);
10921 // Let legalize expand this if it isn't a legal type yet.
10922 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10925 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10928 bool ExtraOp = false;
10929 switch (Op.getOpcode()) {
10930 default: assert(0 && "Invalid code");
10931 case ISD::ADDC: Opc = X86ISD::ADD; break;
10932 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10933 case ISD::SUBC: Opc = X86ISD::SUB; break;
10934 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10938 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10940 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10941 Op.getOperand(1), Op.getOperand(2));
10944 /// LowerOperation - Provide custom lowering hooks for some operations.
10946 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10947 switch (Op.getOpcode()) {
10948 default: llvm_unreachable("Should not custom lower this!");
10949 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10950 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10951 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10952 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10953 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10954 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
10955 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10956 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10957 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10958 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10959 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10960 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10961 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10962 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10963 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10964 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10965 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10966 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10967 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10968 case ISD::SHL_PARTS:
10969 case ISD::SRA_PARTS:
10970 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
10971 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
10972 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
10973 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
10974 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
10975 case ISD::FABS: return LowerFABS(Op, DAG);
10976 case ISD::FNEG: return LowerFNEG(Op, DAG);
10977 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10978 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
10979 case ISD::SETCC: return LowerSETCC(Op, DAG);
10980 case ISD::SELECT: return LowerSELECT(Op, DAG);
10981 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10982 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
10983 case ISD::VASTART: return LowerVASTART(Op, DAG);
10984 case ISD::VAARG: return LowerVAARG(Op, DAG);
10985 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
10986 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10987 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10988 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10989 case ISD::FRAME_TO_ARGS_OFFSET:
10990 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10991 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10992 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
10993 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
10994 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
10995 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10996 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
10997 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
10998 case ISD::MUL: return LowerMUL(Op, DAG);
11001 case ISD::SHL: return LowerShift(Op, DAG);
11007 case ISD::UMULO: return LowerXALUO(Op, DAG);
11008 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
11009 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11013 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11014 case ISD::ADD: return LowerADD(Op, DAG);
11015 case ISD::SUB: return LowerSUB(Op, DAG);
11019 static void ReplaceATOMIC_LOAD(SDNode *Node,
11020 SmallVectorImpl<SDValue> &Results,
11021 SelectionDAG &DAG) {
11022 DebugLoc dl = Node->getDebugLoc();
11023 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11025 // Convert wide load -> cmpxchg8b/cmpxchg16b
11026 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11027 // (The only way to get a 16-byte load is cmpxchg16b)
11028 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11029 SDValue Zero = DAG.getConstant(0, VT);
11030 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11031 Node->getOperand(0),
11032 Node->getOperand(1), Zero, Zero,
11033 cast<AtomicSDNode>(Node)->getMemOperand(),
11034 cast<AtomicSDNode>(Node)->getOrdering(),
11035 cast<AtomicSDNode>(Node)->getSynchScope());
11036 Results.push_back(Swap.getValue(0));
11037 Results.push_back(Swap.getValue(1));
11040 void X86TargetLowering::
11041 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11042 SelectionDAG &DAG, unsigned NewOp) const {
11043 DebugLoc dl = Node->getDebugLoc();
11044 assert (Node->getValueType(0) == MVT::i64 &&
11045 "Only know how to expand i64 atomics");
11047 SDValue Chain = Node->getOperand(0);
11048 SDValue In1 = Node->getOperand(1);
11049 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11050 Node->getOperand(2), DAG.getIntPtrConstant(0));
11051 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11052 Node->getOperand(2), DAG.getIntPtrConstant(1));
11053 SDValue Ops[] = { Chain, In1, In2L, In2H };
11054 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11056 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11057 cast<MemSDNode>(Node)->getMemOperand());
11058 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11059 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11060 Results.push_back(Result.getValue(2));
11063 /// ReplaceNodeResults - Replace a node with an illegal result type
11064 /// with a new node built out of custom code.
11065 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11066 SmallVectorImpl<SDValue>&Results,
11067 SelectionDAG &DAG) const {
11068 DebugLoc dl = N->getDebugLoc();
11069 switch (N->getOpcode()) {
11071 assert(false && "Do not know how to custom type legalize this operation!");
11073 case ISD::SIGN_EXTEND_INREG:
11078 // We don't want to expand or promote these.
11080 case ISD::FP_TO_SINT: {
11081 std::pair<SDValue,SDValue> Vals =
11082 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
11083 SDValue FIST = Vals.first, StackSlot = Vals.second;
11084 if (FIST.getNode() != 0) {
11085 EVT VT = N->getValueType(0);
11086 // Return a load from the stack slot.
11087 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11088 MachinePointerInfo(),
11089 false, false, false, 0));
11093 case ISD::READCYCLECOUNTER: {
11094 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11095 SDValue TheChain = N->getOperand(0);
11096 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11097 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11099 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11101 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11102 SDValue Ops[] = { eax, edx };
11103 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11104 Results.push_back(edx.getValue(1));
11107 case ISD::ATOMIC_CMP_SWAP: {
11108 EVT T = N->getValueType(0);
11109 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11110 bool Regs64bit = T == MVT::i128;
11111 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11112 SDValue cpInL, cpInH;
11113 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11114 DAG.getConstant(0, HalfT));
11115 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11116 DAG.getConstant(1, HalfT));
11117 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11118 Regs64bit ? X86::RAX : X86::EAX,
11120 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11121 Regs64bit ? X86::RDX : X86::EDX,
11122 cpInH, cpInL.getValue(1));
11123 SDValue swapInL, swapInH;
11124 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11125 DAG.getConstant(0, HalfT));
11126 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11127 DAG.getConstant(1, HalfT));
11128 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11129 Regs64bit ? X86::RBX : X86::EBX,
11130 swapInL, cpInH.getValue(1));
11131 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11132 Regs64bit ? X86::RCX : X86::ECX,
11133 swapInH, swapInL.getValue(1));
11134 SDValue Ops[] = { swapInH.getValue(0),
11136 swapInH.getValue(1) };
11137 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11138 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11139 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11140 X86ISD::LCMPXCHG8_DAG;
11141 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11143 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11144 Regs64bit ? X86::RAX : X86::EAX,
11145 HalfT, Result.getValue(1));
11146 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11147 Regs64bit ? X86::RDX : X86::EDX,
11148 HalfT, cpOutL.getValue(2));
11149 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11150 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11151 Results.push_back(cpOutH.getValue(1));
11154 case ISD::ATOMIC_LOAD_ADD:
11155 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11157 case ISD::ATOMIC_LOAD_AND:
11158 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11160 case ISD::ATOMIC_LOAD_NAND:
11161 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11163 case ISD::ATOMIC_LOAD_OR:
11164 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11166 case ISD::ATOMIC_LOAD_SUB:
11167 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11169 case ISD::ATOMIC_LOAD_XOR:
11170 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11172 case ISD::ATOMIC_SWAP:
11173 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11175 case ISD::ATOMIC_LOAD:
11176 ReplaceATOMIC_LOAD(N, Results, DAG);
11180 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11182 default: return NULL;
11183 case X86ISD::BSF: return "X86ISD::BSF";
11184 case X86ISD::BSR: return "X86ISD::BSR";
11185 case X86ISD::SHLD: return "X86ISD::SHLD";
11186 case X86ISD::SHRD: return "X86ISD::SHRD";
11187 case X86ISD::FAND: return "X86ISD::FAND";
11188 case X86ISD::FOR: return "X86ISD::FOR";
11189 case X86ISD::FXOR: return "X86ISD::FXOR";
11190 case X86ISD::FSRL: return "X86ISD::FSRL";
11191 case X86ISD::FILD: return "X86ISD::FILD";
11192 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11193 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11194 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11195 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11196 case X86ISD::FLD: return "X86ISD::FLD";
11197 case X86ISD::FST: return "X86ISD::FST";
11198 case X86ISD::CALL: return "X86ISD::CALL";
11199 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11200 case X86ISD::BT: return "X86ISD::BT";
11201 case X86ISD::CMP: return "X86ISD::CMP";
11202 case X86ISD::COMI: return "X86ISD::COMI";
11203 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11204 case X86ISD::SETCC: return "X86ISD::SETCC";
11205 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11206 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11207 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11208 case X86ISD::CMOV: return "X86ISD::CMOV";
11209 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11210 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11211 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11212 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11213 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11214 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11215 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11216 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11217 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11218 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11219 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11220 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11221 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11222 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11223 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11224 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11225 case X86ISD::FHADD: return "X86ISD::FHADD";
11226 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11227 case X86ISD::FMAX: return "X86ISD::FMAX";
11228 case X86ISD::FMIN: return "X86ISD::FMIN";
11229 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11230 case X86ISD::FRCP: return "X86ISD::FRCP";
11231 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11232 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11233 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11234 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11235 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11236 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11237 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11238 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11239 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11240 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11241 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11242 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11243 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11244 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11245 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11246 case X86ISD::VSHL: return "X86ISD::VSHL";
11247 case X86ISD::VSRL: return "X86ISD::VSRL";
11248 case X86ISD::CMPPD: return "X86ISD::CMPPD";
11249 case X86ISD::CMPPS: return "X86ISD::CMPPS";
11250 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
11251 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
11252 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
11253 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
11254 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
11255 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
11256 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
11257 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
11258 case X86ISD::ADD: return "X86ISD::ADD";
11259 case X86ISD::SUB: return "X86ISD::SUB";
11260 case X86ISD::ADC: return "X86ISD::ADC";
11261 case X86ISD::SBB: return "X86ISD::SBB";
11262 case X86ISD::SMUL: return "X86ISD::SMUL";
11263 case X86ISD::UMUL: return "X86ISD::UMUL";
11264 case X86ISD::INC: return "X86ISD::INC";
11265 case X86ISD::DEC: return "X86ISD::DEC";
11266 case X86ISD::OR: return "X86ISD::OR";
11267 case X86ISD::XOR: return "X86ISD::XOR";
11268 case X86ISD::AND: return "X86ISD::AND";
11269 case X86ISD::ANDN: return "X86ISD::ANDN";
11270 case X86ISD::BLSI: return "X86ISD::BLSI";
11271 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11272 case X86ISD::BLSR: return "X86ISD::BLSR";
11273 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11274 case X86ISD::PTEST: return "X86ISD::PTEST";
11275 case X86ISD::TESTP: return "X86ISD::TESTP";
11276 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11277 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11278 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11279 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
11280 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11281 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
11282 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
11283 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
11284 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11285 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11286 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11287 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
11288 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11289 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11290 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11291 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11292 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11293 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
11294 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
11295 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11296 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11297 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
11298 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
11299 case X86ISD::VUNPCKLPSY: return "X86ISD::VUNPCKLPSY";
11300 case X86ISD::VUNPCKLPDY: return "X86ISD::VUNPCKLPDY";
11301 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
11302 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
11303 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
11304 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
11305 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
11306 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
11307 case X86ISD::VPUNPCKLBWY: return "X86ISD::VPUNPCKLBWY";
11308 case X86ISD::VPUNPCKLWDY: return "X86ISD::VPUNPCKLWDY";
11309 case X86ISD::VPUNPCKLDQY: return "X86ISD::VPUNPCKLDQY";
11310 case X86ISD::VPUNPCKLQDQY: return "X86ISD::VPUNPCKLQDQY";
11311 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
11312 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
11313 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
11314 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
11315 case X86ISD::VPUNPCKHBWY: return "X86ISD::VPUNPCKHBWY";
11316 case X86ISD::VPUNPCKHWDY: return "X86ISD::VPUNPCKHWDY";
11317 case X86ISD::VPUNPCKHDQY: return "X86ISD::VPUNPCKHDQY";
11318 case X86ISD::VPUNPCKHQDQY: return "X86ISD::VPUNPCKHQDQY";
11319 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11320 case X86ISD::VPERMILPS: return "X86ISD::VPERMILPS";
11321 case X86ISD::VPERMILPSY: return "X86ISD::VPERMILPSY";
11322 case X86ISD::VPERMILPD: return "X86ISD::VPERMILPD";
11323 case X86ISD::VPERMILPDY: return "X86ISD::VPERMILPDY";
11324 case X86ISD::VPERM2F128: return "X86ISD::VPERM2F128";
11325 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11326 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11327 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11328 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11329 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11333 // isLegalAddressingMode - Return true if the addressing mode represented
11334 // by AM is legal for this target, for a load/store of the specified type.
11335 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11337 // X86 supports extremely general addressing modes.
11338 CodeModel::Model M = getTargetMachine().getCodeModel();
11339 Reloc::Model R = getTargetMachine().getRelocationModel();
11341 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11342 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11347 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11349 // If a reference to this global requires an extra load, we can't fold it.
11350 if (isGlobalStubReference(GVFlags))
11353 // If BaseGV requires a register for the PIC base, we cannot also have a
11354 // BaseReg specified.
11355 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11358 // If lower 4G is not available, then we must use rip-relative addressing.
11359 if ((M != CodeModel::Small || R != Reloc::Static) &&
11360 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11364 switch (AM.Scale) {
11370 // These scales always work.
11375 // These scales are formed with basereg+scalereg. Only accept if there is
11380 default: // Other stuff never works.
11388 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11389 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11391 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11392 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11393 if (NumBits1 <= NumBits2)
11398 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11399 if (!VT1.isInteger() || !VT2.isInteger())
11401 unsigned NumBits1 = VT1.getSizeInBits();
11402 unsigned NumBits2 = VT2.getSizeInBits();
11403 if (NumBits1 <= NumBits2)
11408 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11409 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11410 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11413 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11414 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11415 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11418 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11419 // i16 instructions are longer (0x66 prefix) and potentially slower.
11420 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11423 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11424 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11425 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11426 /// are assumed to be legal.
11428 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11430 // Very little shuffling can be done for 64-bit vectors right now.
11431 if (VT.getSizeInBits() == 64)
11432 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX());
11434 // FIXME: pshufb, blends, shifts.
11435 return (VT.getVectorNumElements() == 2 ||
11436 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11437 isMOVLMask(M, VT) ||
11438 isSHUFPMask(M, VT) ||
11439 isPSHUFDMask(M, VT) ||
11440 isPSHUFHWMask(M, VT) ||
11441 isPSHUFLWMask(M, VT) ||
11442 isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()) ||
11443 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11444 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11445 isUNPCKL_v_undef_Mask(M, VT) ||
11446 isUNPCKH_v_undef_Mask(M, VT));
11450 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11452 unsigned NumElts = VT.getVectorNumElements();
11453 // FIXME: This collection of masks seems suspect.
11456 if (NumElts == 4 && VT.getSizeInBits() == 128) {
11457 return (isMOVLMask(Mask, VT) ||
11458 isCommutedMOVLMask(Mask, VT, true) ||
11459 isSHUFPMask(Mask, VT) ||
11460 isCommutedSHUFPMask(Mask, VT));
11465 //===----------------------------------------------------------------------===//
11466 // X86 Scheduler Hooks
11467 //===----------------------------------------------------------------------===//
11469 // private utility function
11470 MachineBasicBlock *
11471 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11472 MachineBasicBlock *MBB,
11479 TargetRegisterClass *RC,
11480 bool invSrc) const {
11481 // For the atomic bitwise operator, we generate
11484 // ld t1 = [bitinstr.addr]
11485 // op t2 = t1, [bitinstr.val]
11487 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11489 // fallthrough -->nextMBB
11490 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11491 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11492 MachineFunction::iterator MBBIter = MBB;
11495 /// First build the CFG
11496 MachineFunction *F = MBB->getParent();
11497 MachineBasicBlock *thisMBB = MBB;
11498 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11499 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11500 F->insert(MBBIter, newMBB);
11501 F->insert(MBBIter, nextMBB);
11503 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11504 nextMBB->splice(nextMBB->begin(), thisMBB,
11505 llvm::next(MachineBasicBlock::iterator(bInstr)),
11507 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11509 // Update thisMBB to fall through to newMBB
11510 thisMBB->addSuccessor(newMBB);
11512 // newMBB jumps to itself and fall through to nextMBB
11513 newMBB->addSuccessor(nextMBB);
11514 newMBB->addSuccessor(newMBB);
11516 // Insert instructions into newMBB based on incoming instruction
11517 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11518 "unexpected number of operands");
11519 DebugLoc dl = bInstr->getDebugLoc();
11520 MachineOperand& destOper = bInstr->getOperand(0);
11521 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11522 int numArgs = bInstr->getNumOperands() - 1;
11523 for (int i=0; i < numArgs; ++i)
11524 argOpers[i] = &bInstr->getOperand(i+1);
11526 // x86 address has 4 operands: base, index, scale, and displacement
11527 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11528 int valArgIndx = lastAddrIndx + 1;
11530 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11531 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11532 for (int i=0; i <= lastAddrIndx; ++i)
11533 (*MIB).addOperand(*argOpers[i]);
11535 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11537 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11542 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11543 assert((argOpers[valArgIndx]->isReg() ||
11544 argOpers[valArgIndx]->isImm()) &&
11545 "invalid operand");
11546 if (argOpers[valArgIndx]->isReg())
11547 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11549 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11551 (*MIB).addOperand(*argOpers[valArgIndx]);
11553 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11556 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11557 for (int i=0; i <= lastAddrIndx; ++i)
11558 (*MIB).addOperand(*argOpers[i]);
11560 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11561 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11562 bInstr->memoperands_end());
11564 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11565 MIB.addReg(EAXreg);
11568 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11570 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11574 // private utility function: 64 bit atomics on 32 bit host.
11575 MachineBasicBlock *
11576 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11577 MachineBasicBlock *MBB,
11582 bool invSrc) const {
11583 // For the atomic bitwise operator, we generate
11584 // thisMBB (instructions are in pairs, except cmpxchg8b)
11585 // ld t1,t2 = [bitinstr.addr]
11587 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11588 // op t5, t6 <- out1, out2, [bitinstr.val]
11589 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11590 // mov ECX, EBX <- t5, t6
11591 // mov EAX, EDX <- t1, t2
11592 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11593 // mov t3, t4 <- EAX, EDX
11595 // result in out1, out2
11596 // fallthrough -->nextMBB
11598 const TargetRegisterClass *RC = X86::GR32RegisterClass;
11599 const unsigned LoadOpc = X86::MOV32rm;
11600 const unsigned NotOpc = X86::NOT32r;
11601 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11602 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11603 MachineFunction::iterator MBBIter = MBB;
11606 /// First build the CFG
11607 MachineFunction *F = MBB->getParent();
11608 MachineBasicBlock *thisMBB = MBB;
11609 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11610 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11611 F->insert(MBBIter, newMBB);
11612 F->insert(MBBIter, nextMBB);
11614 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11615 nextMBB->splice(nextMBB->begin(), thisMBB,
11616 llvm::next(MachineBasicBlock::iterator(bInstr)),
11618 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11620 // Update thisMBB to fall through to newMBB
11621 thisMBB->addSuccessor(newMBB);
11623 // newMBB jumps to itself and fall through to nextMBB
11624 newMBB->addSuccessor(nextMBB);
11625 newMBB->addSuccessor(newMBB);
11627 DebugLoc dl = bInstr->getDebugLoc();
11628 // Insert instructions into newMBB based on incoming instruction
11629 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11630 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11631 "unexpected number of operands");
11632 MachineOperand& dest1Oper = bInstr->getOperand(0);
11633 MachineOperand& dest2Oper = bInstr->getOperand(1);
11634 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11635 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11636 argOpers[i] = &bInstr->getOperand(i+2);
11638 // We use some of the operands multiple times, so conservatively just
11639 // clear any kill flags that might be present.
11640 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11641 argOpers[i]->setIsKill(false);
11644 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11645 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11647 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11648 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11649 for (int i=0; i <= lastAddrIndx; ++i)
11650 (*MIB).addOperand(*argOpers[i]);
11651 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11652 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11653 // add 4 to displacement.
11654 for (int i=0; i <= lastAddrIndx-2; ++i)
11655 (*MIB).addOperand(*argOpers[i]);
11656 MachineOperand newOp3 = *(argOpers[3]);
11657 if (newOp3.isImm())
11658 newOp3.setImm(newOp3.getImm()+4);
11660 newOp3.setOffset(newOp3.getOffset()+4);
11661 (*MIB).addOperand(newOp3);
11662 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11664 // t3/4 are defined later, at the bottom of the loop
11665 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11666 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11667 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11668 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11669 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11670 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11672 // The subsequent operations should be using the destination registers of
11673 //the PHI instructions.
11675 t1 = F->getRegInfo().createVirtualRegister(RC);
11676 t2 = F->getRegInfo().createVirtualRegister(RC);
11677 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11678 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11680 t1 = dest1Oper.getReg();
11681 t2 = dest2Oper.getReg();
11684 int valArgIndx = lastAddrIndx + 1;
11685 assert((argOpers[valArgIndx]->isReg() ||
11686 argOpers[valArgIndx]->isImm()) &&
11687 "invalid operand");
11688 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11689 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11690 if (argOpers[valArgIndx]->isReg())
11691 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11693 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11694 if (regOpcL != X86::MOV32rr)
11696 (*MIB).addOperand(*argOpers[valArgIndx]);
11697 assert(argOpers[valArgIndx + 1]->isReg() ==
11698 argOpers[valArgIndx]->isReg());
11699 assert(argOpers[valArgIndx + 1]->isImm() ==
11700 argOpers[valArgIndx]->isImm());
11701 if (argOpers[valArgIndx + 1]->isReg())
11702 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11704 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11705 if (regOpcH != X86::MOV32rr)
11707 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11709 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11711 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11714 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11716 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11719 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11720 for (int i=0; i <= lastAddrIndx; ++i)
11721 (*MIB).addOperand(*argOpers[i]);
11723 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11724 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11725 bInstr->memoperands_end());
11727 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11728 MIB.addReg(X86::EAX);
11729 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11730 MIB.addReg(X86::EDX);
11733 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11735 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11739 // private utility function
11740 MachineBasicBlock *
11741 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11742 MachineBasicBlock *MBB,
11743 unsigned cmovOpc) const {
11744 // For the atomic min/max operator, we generate
11747 // ld t1 = [min/max.addr]
11748 // mov t2 = [min/max.val]
11750 // cmov[cond] t2 = t1
11752 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11754 // fallthrough -->nextMBB
11756 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11757 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11758 MachineFunction::iterator MBBIter = MBB;
11761 /// First build the CFG
11762 MachineFunction *F = MBB->getParent();
11763 MachineBasicBlock *thisMBB = MBB;
11764 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11765 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11766 F->insert(MBBIter, newMBB);
11767 F->insert(MBBIter, nextMBB);
11769 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11770 nextMBB->splice(nextMBB->begin(), thisMBB,
11771 llvm::next(MachineBasicBlock::iterator(mInstr)),
11773 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11775 // Update thisMBB to fall through to newMBB
11776 thisMBB->addSuccessor(newMBB);
11778 // newMBB jumps to newMBB and fall through to nextMBB
11779 newMBB->addSuccessor(nextMBB);
11780 newMBB->addSuccessor(newMBB);
11782 DebugLoc dl = mInstr->getDebugLoc();
11783 // Insert instructions into newMBB based on incoming instruction
11784 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11785 "unexpected number of operands");
11786 MachineOperand& destOper = mInstr->getOperand(0);
11787 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11788 int numArgs = mInstr->getNumOperands() - 1;
11789 for (int i=0; i < numArgs; ++i)
11790 argOpers[i] = &mInstr->getOperand(i+1);
11792 // x86 address has 4 operands: base, index, scale, and displacement
11793 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11794 int valArgIndx = lastAddrIndx + 1;
11796 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11797 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11798 for (int i=0; i <= lastAddrIndx; ++i)
11799 (*MIB).addOperand(*argOpers[i]);
11801 // We only support register and immediate values
11802 assert((argOpers[valArgIndx]->isReg() ||
11803 argOpers[valArgIndx]->isImm()) &&
11804 "invalid operand");
11806 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11807 if (argOpers[valArgIndx]->isReg())
11808 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11810 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11811 (*MIB).addOperand(*argOpers[valArgIndx]);
11813 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11816 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11821 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11822 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11826 // Cmp and exchange if none has modified the memory location
11827 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11828 for (int i=0; i <= lastAddrIndx; ++i)
11829 (*MIB).addOperand(*argOpers[i]);
11831 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11832 (*MIB).setMemRefs(mInstr->memoperands_begin(),
11833 mInstr->memoperands_end());
11835 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11836 MIB.addReg(X86::EAX);
11839 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11841 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
11845 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11846 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11847 // in the .td file.
11848 MachineBasicBlock *
11849 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11850 unsigned numArgs, bool memArg) const {
11851 assert(Subtarget->hasSSE42orAVX() &&
11852 "Target must have SSE4.2 or AVX features enabled");
11854 DebugLoc dl = MI->getDebugLoc();
11855 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11857 if (!Subtarget->hasAVX()) {
11859 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11861 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11864 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11866 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11869 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11870 for (unsigned i = 0; i < numArgs; ++i) {
11871 MachineOperand &Op = MI->getOperand(i+1);
11872 if (!(Op.isReg() && Op.isImplicit()))
11873 MIB.addOperand(Op);
11875 BuildMI(*BB, MI, dl,
11876 TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11877 MI->getOperand(0).getReg())
11878 .addReg(X86::XMM0);
11880 MI->eraseFromParent();
11884 MachineBasicBlock *
11885 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11886 DebugLoc dl = MI->getDebugLoc();
11887 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11889 // Address into RAX/EAX, other two args into ECX, EDX.
11890 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11891 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11892 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11893 for (int i = 0; i < X86::AddrNumOperands; ++i)
11894 MIB.addOperand(MI->getOperand(i));
11896 unsigned ValOps = X86::AddrNumOperands;
11897 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11898 .addReg(MI->getOperand(ValOps).getReg());
11899 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11900 .addReg(MI->getOperand(ValOps+1).getReg());
11902 // The instruction doesn't actually take any operands though.
11903 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11905 MI->eraseFromParent(); // The pseudo is gone now.
11909 MachineBasicBlock *
11910 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11911 DebugLoc dl = MI->getDebugLoc();
11912 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11914 // First arg in ECX, the second in EAX.
11915 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11916 .addReg(MI->getOperand(0).getReg());
11917 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11918 .addReg(MI->getOperand(1).getReg());
11920 // The instruction doesn't actually take any operands though.
11921 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11923 MI->eraseFromParent(); // The pseudo is gone now.
11927 MachineBasicBlock *
11928 X86TargetLowering::EmitVAARG64WithCustomInserter(
11930 MachineBasicBlock *MBB) const {
11931 // Emit va_arg instruction on X86-64.
11933 // Operands to this pseudo-instruction:
11934 // 0 ) Output : destination address (reg)
11935 // 1-5) Input : va_list address (addr, i64mem)
11936 // 6 ) ArgSize : Size (in bytes) of vararg type
11937 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11938 // 8 ) Align : Alignment of type
11939 // 9 ) EFLAGS (implicit-def)
11941 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11942 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11944 unsigned DestReg = MI->getOperand(0).getReg();
11945 MachineOperand &Base = MI->getOperand(1);
11946 MachineOperand &Scale = MI->getOperand(2);
11947 MachineOperand &Index = MI->getOperand(3);
11948 MachineOperand &Disp = MI->getOperand(4);
11949 MachineOperand &Segment = MI->getOperand(5);
11950 unsigned ArgSize = MI->getOperand(6).getImm();
11951 unsigned ArgMode = MI->getOperand(7).getImm();
11952 unsigned Align = MI->getOperand(8).getImm();
11954 // Memory Reference
11955 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11956 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11957 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11959 // Machine Information
11960 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11961 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11962 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11963 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11964 DebugLoc DL = MI->getDebugLoc();
11966 // struct va_list {
11969 // i64 overflow_area (address)
11970 // i64 reg_save_area (address)
11972 // sizeof(va_list) = 24
11973 // alignment(va_list) = 8
11975 unsigned TotalNumIntRegs = 6;
11976 unsigned TotalNumXMMRegs = 8;
11977 bool UseGPOffset = (ArgMode == 1);
11978 bool UseFPOffset = (ArgMode == 2);
11979 unsigned MaxOffset = TotalNumIntRegs * 8 +
11980 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11982 /* Align ArgSize to a multiple of 8 */
11983 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11984 bool NeedsAlign = (Align > 8);
11986 MachineBasicBlock *thisMBB = MBB;
11987 MachineBasicBlock *overflowMBB;
11988 MachineBasicBlock *offsetMBB;
11989 MachineBasicBlock *endMBB;
11991 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
11992 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
11993 unsigned OffsetReg = 0;
11995 if (!UseGPOffset && !UseFPOffset) {
11996 // If we only pull from the overflow region, we don't create a branch.
11997 // We don't need to alter control flow.
11998 OffsetDestReg = 0; // unused
11999 OverflowDestReg = DestReg;
12002 overflowMBB = thisMBB;
12005 // First emit code to check if gp_offset (or fp_offset) is below the bound.
12006 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12007 // If not, pull from overflow_area. (branch to overflowMBB)
12012 // offsetMBB overflowMBB
12017 // Registers for the PHI in endMBB
12018 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12019 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12021 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12022 MachineFunction *MF = MBB->getParent();
12023 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12024 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12025 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12027 MachineFunction::iterator MBBIter = MBB;
12030 // Insert the new basic blocks
12031 MF->insert(MBBIter, offsetMBB);
12032 MF->insert(MBBIter, overflowMBB);
12033 MF->insert(MBBIter, endMBB);
12035 // Transfer the remainder of MBB and its successor edges to endMBB.
12036 endMBB->splice(endMBB->begin(), thisMBB,
12037 llvm::next(MachineBasicBlock::iterator(MI)),
12039 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12041 // Make offsetMBB and overflowMBB successors of thisMBB
12042 thisMBB->addSuccessor(offsetMBB);
12043 thisMBB->addSuccessor(overflowMBB);
12045 // endMBB is a successor of both offsetMBB and overflowMBB
12046 offsetMBB->addSuccessor(endMBB);
12047 overflowMBB->addSuccessor(endMBB);
12049 // Load the offset value into a register
12050 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12051 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12055 .addDisp(Disp, UseFPOffset ? 4 : 0)
12056 .addOperand(Segment)
12057 .setMemRefs(MMOBegin, MMOEnd);
12059 // Check if there is enough room left to pull this argument.
12060 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12062 .addImm(MaxOffset + 8 - ArgSizeA8);
12064 // Branch to "overflowMBB" if offset >= max
12065 // Fall through to "offsetMBB" otherwise
12066 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12067 .addMBB(overflowMBB);
12070 // In offsetMBB, emit code to use the reg_save_area.
12072 assert(OffsetReg != 0);
12074 // Read the reg_save_area address.
12075 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12076 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12081 .addOperand(Segment)
12082 .setMemRefs(MMOBegin, MMOEnd);
12084 // Zero-extend the offset
12085 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12086 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12089 .addImm(X86::sub_32bit);
12091 // Add the offset to the reg_save_area to get the final address.
12092 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12093 .addReg(OffsetReg64)
12094 .addReg(RegSaveReg);
12096 // Compute the offset for the next argument
12097 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12098 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12100 .addImm(UseFPOffset ? 16 : 8);
12102 // Store it back into the va_list.
12103 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12107 .addDisp(Disp, UseFPOffset ? 4 : 0)
12108 .addOperand(Segment)
12109 .addReg(NextOffsetReg)
12110 .setMemRefs(MMOBegin, MMOEnd);
12113 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12118 // Emit code to use overflow area
12121 // Load the overflow_area address into a register.
12122 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12123 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12128 .addOperand(Segment)
12129 .setMemRefs(MMOBegin, MMOEnd);
12131 // If we need to align it, do so. Otherwise, just copy the address
12132 // to OverflowDestReg.
12134 // Align the overflow address
12135 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12136 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12138 // aligned_addr = (addr + (align-1)) & ~(align-1)
12139 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12140 .addReg(OverflowAddrReg)
12143 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12145 .addImm(~(uint64_t)(Align-1));
12147 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12148 .addReg(OverflowAddrReg);
12151 // Compute the next overflow address after this argument.
12152 // (the overflow address should be kept 8-byte aligned)
12153 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12154 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12155 .addReg(OverflowDestReg)
12156 .addImm(ArgSizeA8);
12158 // Store the new overflow address.
12159 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12164 .addOperand(Segment)
12165 .addReg(NextAddrReg)
12166 .setMemRefs(MMOBegin, MMOEnd);
12168 // If we branched, emit the PHI to the front of endMBB.
12170 BuildMI(*endMBB, endMBB->begin(), DL,
12171 TII->get(X86::PHI), DestReg)
12172 .addReg(OffsetDestReg).addMBB(offsetMBB)
12173 .addReg(OverflowDestReg).addMBB(overflowMBB);
12176 // Erase the pseudo instruction
12177 MI->eraseFromParent();
12182 MachineBasicBlock *
12183 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12185 MachineBasicBlock *MBB) const {
12186 // Emit code to save XMM registers to the stack. The ABI says that the
12187 // number of registers to save is given in %al, so it's theoretically
12188 // possible to do an indirect jump trick to avoid saving all of them,
12189 // however this code takes a simpler approach and just executes all
12190 // of the stores if %al is non-zero. It's less code, and it's probably
12191 // easier on the hardware branch predictor, and stores aren't all that
12192 // expensive anyway.
12194 // Create the new basic blocks. One block contains all the XMM stores,
12195 // and one block is the final destination regardless of whether any
12196 // stores were performed.
12197 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12198 MachineFunction *F = MBB->getParent();
12199 MachineFunction::iterator MBBIter = MBB;
12201 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12202 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12203 F->insert(MBBIter, XMMSaveMBB);
12204 F->insert(MBBIter, EndMBB);
12206 // Transfer the remainder of MBB and its successor edges to EndMBB.
12207 EndMBB->splice(EndMBB->begin(), MBB,
12208 llvm::next(MachineBasicBlock::iterator(MI)),
12210 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12212 // The original block will now fall through to the XMM save block.
12213 MBB->addSuccessor(XMMSaveMBB);
12214 // The XMMSaveMBB will fall through to the end block.
12215 XMMSaveMBB->addSuccessor(EndMBB);
12217 // Now add the instructions.
12218 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12219 DebugLoc DL = MI->getDebugLoc();
12221 unsigned CountReg = MI->getOperand(0).getReg();
12222 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12223 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12225 if (!Subtarget->isTargetWin64()) {
12226 // If %al is 0, branch around the XMM save block.
12227 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12228 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12229 MBB->addSuccessor(EndMBB);
12232 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12233 // In the XMM save block, save all the XMM argument registers.
12234 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12235 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12236 MachineMemOperand *MMO =
12237 F->getMachineMemOperand(
12238 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12239 MachineMemOperand::MOStore,
12240 /*Size=*/16, /*Align=*/16);
12241 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12242 .addFrameIndex(RegSaveFrameIndex)
12243 .addImm(/*Scale=*/1)
12244 .addReg(/*IndexReg=*/0)
12245 .addImm(/*Disp=*/Offset)
12246 .addReg(/*Segment=*/0)
12247 .addReg(MI->getOperand(i).getReg())
12248 .addMemOperand(MMO);
12251 MI->eraseFromParent(); // The pseudo instruction is gone now.
12256 MachineBasicBlock *
12257 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12258 MachineBasicBlock *BB) const {
12259 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12260 DebugLoc DL = MI->getDebugLoc();
12262 // To "insert" a SELECT_CC instruction, we actually have to insert the
12263 // diamond control-flow pattern. The incoming instruction knows the
12264 // destination vreg to set, the condition code register to branch on, the
12265 // true/false values to select between, and a branch opcode to use.
12266 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12267 MachineFunction::iterator It = BB;
12273 // cmpTY ccX, r1, r2
12275 // fallthrough --> copy0MBB
12276 MachineBasicBlock *thisMBB = BB;
12277 MachineFunction *F = BB->getParent();
12278 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12279 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12280 F->insert(It, copy0MBB);
12281 F->insert(It, sinkMBB);
12283 // If the EFLAGS register isn't dead in the terminator, then claim that it's
12284 // live into the sink and copy blocks.
12285 if (!MI->killsRegister(X86::EFLAGS)) {
12286 copy0MBB->addLiveIn(X86::EFLAGS);
12287 sinkMBB->addLiveIn(X86::EFLAGS);
12290 // Transfer the remainder of BB and its successor edges to sinkMBB.
12291 sinkMBB->splice(sinkMBB->begin(), BB,
12292 llvm::next(MachineBasicBlock::iterator(MI)),
12294 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12296 // Add the true and fallthrough blocks as its successors.
12297 BB->addSuccessor(copy0MBB);
12298 BB->addSuccessor(sinkMBB);
12300 // Create the conditional branch instruction.
12302 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12303 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12306 // %FalseValue = ...
12307 // # fallthrough to sinkMBB
12308 copy0MBB->addSuccessor(sinkMBB);
12311 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12313 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12314 TII->get(X86::PHI), MI->getOperand(0).getReg())
12315 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12316 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12318 MI->eraseFromParent(); // The pseudo instruction is gone now.
12322 MachineBasicBlock *
12323 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12324 bool Is64Bit) const {
12325 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12326 DebugLoc DL = MI->getDebugLoc();
12327 MachineFunction *MF = BB->getParent();
12328 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12330 assert(EnableSegmentedStacks);
12332 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12333 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12336 // ... [Till the alloca]
12337 // If stacklet is not large enough, jump to mallocMBB
12340 // Allocate by subtracting from RSP
12341 // Jump to continueMBB
12344 // Allocate by call to runtime
12348 // [rest of original BB]
12351 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12352 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12353 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12355 MachineRegisterInfo &MRI = MF->getRegInfo();
12356 const TargetRegisterClass *AddrRegClass =
12357 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12359 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12360 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12361 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12362 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12363 sizeVReg = MI->getOperand(1).getReg(),
12364 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12366 MachineFunction::iterator MBBIter = BB;
12369 MF->insert(MBBIter, bumpMBB);
12370 MF->insert(MBBIter, mallocMBB);
12371 MF->insert(MBBIter, continueMBB);
12373 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12374 (MachineBasicBlock::iterator(MI)), BB->end());
12375 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12377 // Add code to the main basic block to check if the stack limit has been hit,
12378 // and if so, jump to mallocMBB otherwise to bumpMBB.
12379 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12380 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12381 .addReg(tmpSPVReg).addReg(sizeVReg);
12382 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12383 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12384 .addReg(SPLimitVReg);
12385 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12387 // bumpMBB simply decreases the stack pointer, since we know the current
12388 // stacklet has enough space.
12389 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12390 .addReg(SPLimitVReg);
12391 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12392 .addReg(SPLimitVReg);
12393 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12395 // Calls into a routine in libgcc to allocate more space from the heap.
12397 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12399 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12400 .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12402 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12404 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12405 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12406 .addExternalSymbol("__morestack_allocate_stack_space");
12410 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12413 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12414 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12415 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12417 // Set up the CFG correctly.
12418 BB->addSuccessor(bumpMBB);
12419 BB->addSuccessor(mallocMBB);
12420 mallocMBB->addSuccessor(continueMBB);
12421 bumpMBB->addSuccessor(continueMBB);
12423 // Take care of the PHI nodes.
12424 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12425 MI->getOperand(0).getReg())
12426 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12427 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12429 // Delete the original pseudo instruction.
12430 MI->eraseFromParent();
12433 return continueMBB;
12436 MachineBasicBlock *
12437 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12438 MachineBasicBlock *BB) const {
12439 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12440 DebugLoc DL = MI->getDebugLoc();
12442 assert(!Subtarget->isTargetEnvMacho());
12444 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12445 // non-trivial part is impdef of ESP.
12447 if (Subtarget->isTargetWin64()) {
12448 if (Subtarget->isTargetCygMing()) {
12449 // ___chkstk(Mingw64):
12450 // Clobbers R10, R11, RAX and EFLAGS.
12452 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12453 .addExternalSymbol("___chkstk")
12454 .addReg(X86::RAX, RegState::Implicit)
12455 .addReg(X86::RSP, RegState::Implicit)
12456 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12457 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12458 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12460 // __chkstk(MSVCRT): does not update stack pointer.
12461 // Clobbers R10, R11 and EFLAGS.
12462 // FIXME: RAX(allocated size) might be reused and not killed.
12463 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12464 .addExternalSymbol("__chkstk")
12465 .addReg(X86::RAX, RegState::Implicit)
12466 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12467 // RAX has the offset to subtracted from RSP.
12468 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12473 const char *StackProbeSymbol =
12474 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12476 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12477 .addExternalSymbol(StackProbeSymbol)
12478 .addReg(X86::EAX, RegState::Implicit)
12479 .addReg(X86::ESP, RegState::Implicit)
12480 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12481 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12482 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12485 MI->eraseFromParent(); // The pseudo instruction is gone now.
12489 MachineBasicBlock *
12490 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12491 MachineBasicBlock *BB) const {
12492 // This is pretty easy. We're taking the value that we received from
12493 // our load from the relocation, sticking it in either RDI (x86-64)
12494 // or EAX and doing an indirect call. The return value will then
12495 // be in the normal return register.
12496 const X86InstrInfo *TII
12497 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12498 DebugLoc DL = MI->getDebugLoc();
12499 MachineFunction *F = BB->getParent();
12501 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12502 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12504 if (Subtarget->is64Bit()) {
12505 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12506 TII->get(X86::MOV64rm), X86::RDI)
12508 .addImm(0).addReg(0)
12509 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12510 MI->getOperand(3).getTargetFlags())
12512 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12513 addDirectMem(MIB, X86::RDI);
12514 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12515 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12516 TII->get(X86::MOV32rm), X86::EAX)
12518 .addImm(0).addReg(0)
12519 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12520 MI->getOperand(3).getTargetFlags())
12522 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12523 addDirectMem(MIB, X86::EAX);
12525 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12526 TII->get(X86::MOV32rm), X86::EAX)
12527 .addReg(TII->getGlobalBaseReg(F))
12528 .addImm(0).addReg(0)
12529 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12530 MI->getOperand(3).getTargetFlags())
12532 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12533 addDirectMem(MIB, X86::EAX);
12536 MI->eraseFromParent(); // The pseudo instruction is gone now.
12540 MachineBasicBlock *
12541 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12542 MachineBasicBlock *BB) const {
12543 switch (MI->getOpcode()) {
12544 default: assert(0 && "Unexpected instr type to insert");
12545 case X86::TAILJMPd64:
12546 case X86::TAILJMPr64:
12547 case X86::TAILJMPm64:
12548 assert(0 && "TAILJMP64 would not be touched here.");
12549 case X86::TCRETURNdi64:
12550 case X86::TCRETURNri64:
12551 case X86::TCRETURNmi64:
12552 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12553 // On AMD64, additional defs should be added before register allocation.
12554 if (!Subtarget->isTargetWin64()) {
12555 MI->addRegisterDefined(X86::RSI);
12556 MI->addRegisterDefined(X86::RDI);
12557 MI->addRegisterDefined(X86::XMM6);
12558 MI->addRegisterDefined(X86::XMM7);
12559 MI->addRegisterDefined(X86::XMM8);
12560 MI->addRegisterDefined(X86::XMM9);
12561 MI->addRegisterDefined(X86::XMM10);
12562 MI->addRegisterDefined(X86::XMM11);
12563 MI->addRegisterDefined(X86::XMM12);
12564 MI->addRegisterDefined(X86::XMM13);
12565 MI->addRegisterDefined(X86::XMM14);
12566 MI->addRegisterDefined(X86::XMM15);
12569 case X86::WIN_ALLOCA:
12570 return EmitLoweredWinAlloca(MI, BB);
12571 case X86::SEG_ALLOCA_32:
12572 return EmitLoweredSegAlloca(MI, BB, false);
12573 case X86::SEG_ALLOCA_64:
12574 return EmitLoweredSegAlloca(MI, BB, true);
12575 case X86::TLSCall_32:
12576 case X86::TLSCall_64:
12577 return EmitLoweredTLSCall(MI, BB);
12578 case X86::CMOV_GR8:
12579 case X86::CMOV_FR32:
12580 case X86::CMOV_FR64:
12581 case X86::CMOV_V4F32:
12582 case X86::CMOV_V2F64:
12583 case X86::CMOV_V2I64:
12584 case X86::CMOV_V8F32:
12585 case X86::CMOV_V4F64:
12586 case X86::CMOV_V4I64:
12587 case X86::CMOV_GR16:
12588 case X86::CMOV_GR32:
12589 case X86::CMOV_RFP32:
12590 case X86::CMOV_RFP64:
12591 case X86::CMOV_RFP80:
12592 return EmitLoweredSelect(MI, BB);
12594 case X86::FP32_TO_INT16_IN_MEM:
12595 case X86::FP32_TO_INT32_IN_MEM:
12596 case X86::FP32_TO_INT64_IN_MEM:
12597 case X86::FP64_TO_INT16_IN_MEM:
12598 case X86::FP64_TO_INT32_IN_MEM:
12599 case X86::FP64_TO_INT64_IN_MEM:
12600 case X86::FP80_TO_INT16_IN_MEM:
12601 case X86::FP80_TO_INT32_IN_MEM:
12602 case X86::FP80_TO_INT64_IN_MEM: {
12603 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12604 DebugLoc DL = MI->getDebugLoc();
12606 // Change the floating point control register to use "round towards zero"
12607 // mode when truncating to an integer value.
12608 MachineFunction *F = BB->getParent();
12609 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12610 addFrameReference(BuildMI(*BB, MI, DL,
12611 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12613 // Load the old value of the high byte of the control word...
12615 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12616 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12619 // Set the high part to be round to zero...
12620 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12623 // Reload the modified control word now...
12624 addFrameReference(BuildMI(*BB, MI, DL,
12625 TII->get(X86::FLDCW16m)), CWFrameIdx);
12627 // Restore the memory image of control word to original value
12628 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12631 // Get the X86 opcode to use.
12633 switch (MI->getOpcode()) {
12634 default: llvm_unreachable("illegal opcode!");
12635 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12636 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12637 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12638 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12639 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12640 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12641 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12642 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12643 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12647 MachineOperand &Op = MI->getOperand(0);
12649 AM.BaseType = X86AddressMode::RegBase;
12650 AM.Base.Reg = Op.getReg();
12652 AM.BaseType = X86AddressMode::FrameIndexBase;
12653 AM.Base.FrameIndex = Op.getIndex();
12655 Op = MI->getOperand(1);
12657 AM.Scale = Op.getImm();
12658 Op = MI->getOperand(2);
12660 AM.IndexReg = Op.getImm();
12661 Op = MI->getOperand(3);
12662 if (Op.isGlobal()) {
12663 AM.GV = Op.getGlobal();
12665 AM.Disp = Op.getImm();
12667 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12668 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12670 // Reload the original control word now.
12671 addFrameReference(BuildMI(*BB, MI, DL,
12672 TII->get(X86::FLDCW16m)), CWFrameIdx);
12674 MI->eraseFromParent(); // The pseudo instruction is gone now.
12677 // String/text processing lowering.
12678 case X86::PCMPISTRM128REG:
12679 case X86::VPCMPISTRM128REG:
12680 return EmitPCMP(MI, BB, 3, false /* in-mem */);
12681 case X86::PCMPISTRM128MEM:
12682 case X86::VPCMPISTRM128MEM:
12683 return EmitPCMP(MI, BB, 3, true /* in-mem */);
12684 case X86::PCMPESTRM128REG:
12685 case X86::VPCMPESTRM128REG:
12686 return EmitPCMP(MI, BB, 5, false /* in mem */);
12687 case X86::PCMPESTRM128MEM:
12688 case X86::VPCMPESTRM128MEM:
12689 return EmitPCMP(MI, BB, 5, true /* in mem */);
12691 // Thread synchronization.
12693 return EmitMonitor(MI, BB);
12695 return EmitMwait(MI, BB);
12697 // Atomic Lowering.
12698 case X86::ATOMAND32:
12699 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12700 X86::AND32ri, X86::MOV32rm,
12702 X86::NOT32r, X86::EAX,
12703 X86::GR32RegisterClass);
12704 case X86::ATOMOR32:
12705 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12706 X86::OR32ri, X86::MOV32rm,
12708 X86::NOT32r, X86::EAX,
12709 X86::GR32RegisterClass);
12710 case X86::ATOMXOR32:
12711 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12712 X86::XOR32ri, X86::MOV32rm,
12714 X86::NOT32r, X86::EAX,
12715 X86::GR32RegisterClass);
12716 case X86::ATOMNAND32:
12717 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12718 X86::AND32ri, X86::MOV32rm,
12720 X86::NOT32r, X86::EAX,
12721 X86::GR32RegisterClass, true);
12722 case X86::ATOMMIN32:
12723 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12724 case X86::ATOMMAX32:
12725 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12726 case X86::ATOMUMIN32:
12727 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12728 case X86::ATOMUMAX32:
12729 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12731 case X86::ATOMAND16:
12732 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12733 X86::AND16ri, X86::MOV16rm,
12735 X86::NOT16r, X86::AX,
12736 X86::GR16RegisterClass);
12737 case X86::ATOMOR16:
12738 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12739 X86::OR16ri, X86::MOV16rm,
12741 X86::NOT16r, X86::AX,
12742 X86::GR16RegisterClass);
12743 case X86::ATOMXOR16:
12744 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12745 X86::XOR16ri, X86::MOV16rm,
12747 X86::NOT16r, X86::AX,
12748 X86::GR16RegisterClass);
12749 case X86::ATOMNAND16:
12750 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12751 X86::AND16ri, X86::MOV16rm,
12753 X86::NOT16r, X86::AX,
12754 X86::GR16RegisterClass, true);
12755 case X86::ATOMMIN16:
12756 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12757 case X86::ATOMMAX16:
12758 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12759 case X86::ATOMUMIN16:
12760 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12761 case X86::ATOMUMAX16:
12762 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12764 case X86::ATOMAND8:
12765 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12766 X86::AND8ri, X86::MOV8rm,
12768 X86::NOT8r, X86::AL,
12769 X86::GR8RegisterClass);
12771 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12772 X86::OR8ri, X86::MOV8rm,
12774 X86::NOT8r, X86::AL,
12775 X86::GR8RegisterClass);
12776 case X86::ATOMXOR8:
12777 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12778 X86::XOR8ri, X86::MOV8rm,
12780 X86::NOT8r, X86::AL,
12781 X86::GR8RegisterClass);
12782 case X86::ATOMNAND8:
12783 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12784 X86::AND8ri, X86::MOV8rm,
12786 X86::NOT8r, X86::AL,
12787 X86::GR8RegisterClass, true);
12788 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12789 // This group is for 64-bit host.
12790 case X86::ATOMAND64:
12791 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12792 X86::AND64ri32, X86::MOV64rm,
12794 X86::NOT64r, X86::RAX,
12795 X86::GR64RegisterClass);
12796 case X86::ATOMOR64:
12797 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12798 X86::OR64ri32, X86::MOV64rm,
12800 X86::NOT64r, X86::RAX,
12801 X86::GR64RegisterClass);
12802 case X86::ATOMXOR64:
12803 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12804 X86::XOR64ri32, X86::MOV64rm,
12806 X86::NOT64r, X86::RAX,
12807 X86::GR64RegisterClass);
12808 case X86::ATOMNAND64:
12809 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12810 X86::AND64ri32, X86::MOV64rm,
12812 X86::NOT64r, X86::RAX,
12813 X86::GR64RegisterClass, true);
12814 case X86::ATOMMIN64:
12815 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12816 case X86::ATOMMAX64:
12817 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12818 case X86::ATOMUMIN64:
12819 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12820 case X86::ATOMUMAX64:
12821 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12823 // This group does 64-bit operations on a 32-bit host.
12824 case X86::ATOMAND6432:
12825 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12826 X86::AND32rr, X86::AND32rr,
12827 X86::AND32ri, X86::AND32ri,
12829 case X86::ATOMOR6432:
12830 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12831 X86::OR32rr, X86::OR32rr,
12832 X86::OR32ri, X86::OR32ri,
12834 case X86::ATOMXOR6432:
12835 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12836 X86::XOR32rr, X86::XOR32rr,
12837 X86::XOR32ri, X86::XOR32ri,
12839 case X86::ATOMNAND6432:
12840 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12841 X86::AND32rr, X86::AND32rr,
12842 X86::AND32ri, X86::AND32ri,
12844 case X86::ATOMADD6432:
12845 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12846 X86::ADD32rr, X86::ADC32rr,
12847 X86::ADD32ri, X86::ADC32ri,
12849 case X86::ATOMSUB6432:
12850 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12851 X86::SUB32rr, X86::SBB32rr,
12852 X86::SUB32ri, X86::SBB32ri,
12854 case X86::ATOMSWAP6432:
12855 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12856 X86::MOV32rr, X86::MOV32rr,
12857 X86::MOV32ri, X86::MOV32ri,
12859 case X86::VASTART_SAVE_XMM_REGS:
12860 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12862 case X86::VAARG_64:
12863 return EmitVAARG64WithCustomInserter(MI, BB);
12867 //===----------------------------------------------------------------------===//
12868 // X86 Optimization Hooks
12869 //===----------------------------------------------------------------------===//
12871 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12875 const SelectionDAG &DAG,
12876 unsigned Depth) const {
12877 unsigned Opc = Op.getOpcode();
12878 assert((Opc >= ISD::BUILTIN_OP_END ||
12879 Opc == ISD::INTRINSIC_WO_CHAIN ||
12880 Opc == ISD::INTRINSIC_W_CHAIN ||
12881 Opc == ISD::INTRINSIC_VOID) &&
12882 "Should use MaskedValueIsZero if you don't know whether Op"
12883 " is a target node!");
12885 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
12899 // These nodes' second result is a boolean.
12900 if (Op.getResNo() == 0)
12903 case X86ISD::SETCC:
12904 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12905 Mask.getBitWidth() - 1);
12907 case ISD::INTRINSIC_WO_CHAIN: {
12908 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12909 unsigned NumLoBits = 0;
12912 case Intrinsic::x86_sse_movmsk_ps:
12913 case Intrinsic::x86_avx_movmsk_ps_256:
12914 case Intrinsic::x86_sse2_movmsk_pd:
12915 case Intrinsic::x86_avx_movmsk_pd_256:
12916 case Intrinsic::x86_mmx_pmovmskb:
12917 case Intrinsic::x86_sse2_pmovmskb_128: {
12918 // High bits of movmskp{s|d}, pmovmskb are known zero.
12920 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
12921 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
12922 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
12923 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
12924 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
12925 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
12927 KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12928 Mask.getBitWidth() - NumLoBits);
12937 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12938 unsigned Depth) const {
12939 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12940 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12941 return Op.getValueType().getScalarType().getSizeInBits();
12947 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12948 /// node is a GlobalAddress + offset.
12949 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12950 const GlobalValue* &GA,
12951 int64_t &Offset) const {
12952 if (N->getOpcode() == X86ISD::Wrapper) {
12953 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12954 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12955 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12959 return TargetLowering::isGAPlusOffset(N, GA, Offset);
12962 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12963 /// same as extracting the high 128-bit part of 256-bit vector and then
12964 /// inserting the result into the low part of a new 256-bit vector
12965 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12966 EVT VT = SVOp->getValueType(0);
12967 int NumElems = VT.getVectorNumElements();
12969 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12970 for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12971 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12972 SVOp->getMaskElt(j) >= 0)
12978 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12979 /// same as extracting the low 128-bit part of 256-bit vector and then
12980 /// inserting the result into the high part of a new 256-bit vector
12981 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12982 EVT VT = SVOp->getValueType(0);
12983 int NumElems = VT.getVectorNumElements();
12985 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12986 for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12987 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12988 SVOp->getMaskElt(j) >= 0)
12994 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12995 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12996 TargetLowering::DAGCombinerInfo &DCI) {
12997 DebugLoc dl = N->getDebugLoc();
12998 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12999 SDValue V1 = SVOp->getOperand(0);
13000 SDValue V2 = SVOp->getOperand(1);
13001 EVT VT = SVOp->getValueType(0);
13002 int NumElems = VT.getVectorNumElements();
13004 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13005 V2.getOpcode() == ISD::CONCAT_VECTORS) {
13009 // V UNDEF BUILD_VECTOR UNDEF
13011 // CONCAT_VECTOR CONCAT_VECTOR
13014 // RESULT: V + zero extended
13016 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13017 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13018 V1.getOperand(1).getOpcode() != ISD::UNDEF)
13021 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13024 // To match the shuffle mask, the first half of the mask should
13025 // be exactly the first vector, and all the rest a splat with the
13026 // first element of the second one.
13027 for (int i = 0; i < NumElems/2; ++i)
13028 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13029 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13032 // Emit a zeroed vector and insert the desired subvector on its
13034 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
13035 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
13036 DAG.getConstant(0, MVT::i32), DAG, dl);
13037 return DCI.CombineTo(N, InsV);
13040 //===--------------------------------------------------------------------===//
13041 // Combine some shuffles into subvector extracts and inserts:
13044 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13045 if (isShuffleHigh128VectorInsertLow(SVOp)) {
13046 SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
13048 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
13049 V, DAG.getConstant(0, MVT::i32), DAG, dl);
13050 return DCI.CombineTo(N, InsV);
13053 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13054 if (isShuffleLow128VectorInsertHigh(SVOp)) {
13055 SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
13056 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
13057 V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
13058 return DCI.CombineTo(N, InsV);
13064 /// PerformShuffleCombine - Performs several different shuffle combines.
13065 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13066 TargetLowering::DAGCombinerInfo &DCI,
13067 const X86Subtarget *Subtarget) {
13068 DebugLoc dl = N->getDebugLoc();
13069 EVT VT = N->getValueType(0);
13071 // Don't create instructions with illegal types after legalize types has run.
13072 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13073 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13076 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13077 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
13078 N->getOpcode() == ISD::VECTOR_SHUFFLE)
13079 return PerformShuffleCombine256(N, DAG, DCI);
13081 // Only handle 128 wide vector from here on.
13082 if (VT.getSizeInBits() != 128)
13085 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13086 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13087 // consecutive, non-overlapping, and in the right order.
13088 SmallVector<SDValue, 16> Elts;
13089 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13090 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13092 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13095 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13096 /// generation and convert it from being a bunch of shuffles and extracts
13097 /// to a simple store and scalar loads to extract the elements.
13098 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13099 const TargetLowering &TLI) {
13100 SDValue InputVector = N->getOperand(0);
13102 // Only operate on vectors of 4 elements, where the alternative shuffling
13103 // gets to be more expensive.
13104 if (InputVector.getValueType() != MVT::v4i32)
13107 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13108 // single use which is a sign-extend or zero-extend, and all elements are
13110 SmallVector<SDNode *, 4> Uses;
13111 unsigned ExtractedElements = 0;
13112 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13113 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13114 if (UI.getUse().getResNo() != InputVector.getResNo())
13117 SDNode *Extract = *UI;
13118 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13121 if (Extract->getValueType(0) != MVT::i32)
13123 if (!Extract->hasOneUse())
13125 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13126 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13128 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13131 // Record which element was extracted.
13132 ExtractedElements |=
13133 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13135 Uses.push_back(Extract);
13138 // If not all the elements were used, this may not be worthwhile.
13139 if (ExtractedElements != 15)
13142 // Ok, we've now decided to do the transformation.
13143 DebugLoc dl = InputVector.getDebugLoc();
13145 // Store the value to a temporary stack slot.
13146 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13147 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13148 MachinePointerInfo(), false, false, 0);
13150 // Replace each use (extract) with a load of the appropriate element.
13151 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13152 UE = Uses.end(); UI != UE; ++UI) {
13153 SDNode *Extract = *UI;
13155 // cOMpute the element's address.
13156 SDValue Idx = Extract->getOperand(1);
13158 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13159 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13160 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13162 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13163 StackPtr, OffsetVal);
13165 // Load the scalar.
13166 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13167 ScalarAddr, MachinePointerInfo(),
13168 false, false, false, 0);
13170 // Replace the exact with the load.
13171 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13174 // The replacement was made in place; don't return anything.
13178 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13180 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13181 const X86Subtarget *Subtarget) {
13182 DebugLoc DL = N->getDebugLoc();
13183 SDValue Cond = N->getOperand(0);
13184 // Get the LHS/RHS of the select.
13185 SDValue LHS = N->getOperand(1);
13186 SDValue RHS = N->getOperand(2);
13187 EVT VT = LHS.getValueType();
13189 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13190 // instructions match the semantics of the common C idiom x<y?x:y but not
13191 // x<=y?x:y, because of how they handle negative zero (which can be
13192 // ignored in unsafe-math mode).
13193 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13194 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13195 (Subtarget->hasXMMInt() ||
13196 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13197 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13199 unsigned Opcode = 0;
13200 // Check for x CC y ? x : y.
13201 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13202 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13206 // Converting this to a min would handle NaNs incorrectly, and swapping
13207 // the operands would cause it to handle comparisons between positive
13208 // and negative zero incorrectly.
13209 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13210 if (!UnsafeFPMath &&
13211 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13213 std::swap(LHS, RHS);
13215 Opcode = X86ISD::FMIN;
13218 // Converting this to a min would handle comparisons between positive
13219 // and negative zero incorrectly.
13220 if (!UnsafeFPMath &&
13221 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13223 Opcode = X86ISD::FMIN;
13226 // Converting this to a min would handle both negative zeros and NaNs
13227 // incorrectly, but we can swap the operands to fix both.
13228 std::swap(LHS, RHS);
13232 Opcode = X86ISD::FMIN;
13236 // Converting this to a max would handle comparisons between positive
13237 // and negative zero incorrectly.
13238 if (!UnsafeFPMath &&
13239 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13241 Opcode = X86ISD::FMAX;
13244 // Converting this to a max would handle NaNs incorrectly, and swapping
13245 // the operands would cause it to handle comparisons between positive
13246 // and negative zero incorrectly.
13247 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13248 if (!UnsafeFPMath &&
13249 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13251 std::swap(LHS, RHS);
13253 Opcode = X86ISD::FMAX;
13256 // Converting this to a max would handle both negative zeros and NaNs
13257 // incorrectly, but we can swap the operands to fix both.
13258 std::swap(LHS, RHS);
13262 Opcode = X86ISD::FMAX;
13265 // Check for x CC y ? y : x -- a min/max with reversed arms.
13266 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13267 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13271 // Converting this to a min would handle comparisons between positive
13272 // and negative zero incorrectly, and swapping the operands would
13273 // cause it to handle NaNs incorrectly.
13274 if (!UnsafeFPMath &&
13275 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13276 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13278 std::swap(LHS, RHS);
13280 Opcode = X86ISD::FMIN;
13283 // Converting this to a min would handle NaNs incorrectly.
13284 if (!UnsafeFPMath &&
13285 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13287 Opcode = X86ISD::FMIN;
13290 // Converting this to a min would handle both negative zeros and NaNs
13291 // incorrectly, but we can swap the operands to fix both.
13292 std::swap(LHS, RHS);
13296 Opcode = X86ISD::FMIN;
13300 // Converting this to a max would handle NaNs incorrectly.
13301 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13303 Opcode = X86ISD::FMAX;
13306 // Converting this to a max would handle comparisons between positive
13307 // and negative zero incorrectly, and swapping the operands would
13308 // cause it to handle NaNs incorrectly.
13309 if (!UnsafeFPMath &&
13310 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13311 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13313 std::swap(LHS, RHS);
13315 Opcode = X86ISD::FMAX;
13318 // Converting this to a max would handle both negative zeros and NaNs
13319 // incorrectly, but we can swap the operands to fix both.
13320 std::swap(LHS, RHS);
13324 Opcode = X86ISD::FMAX;
13330 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13333 // If this is a select between two integer constants, try to do some
13335 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13336 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13337 // Don't do this for crazy integer types.
13338 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13339 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13340 // so that TrueC (the true value) is larger than FalseC.
13341 bool NeedsCondInvert = false;
13343 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13344 // Efficiently invertible.
13345 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
13346 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
13347 isa<ConstantSDNode>(Cond.getOperand(1))))) {
13348 NeedsCondInvert = true;
13349 std::swap(TrueC, FalseC);
13352 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
13353 if (FalseC->getAPIntValue() == 0 &&
13354 TrueC->getAPIntValue().isPowerOf2()) {
13355 if (NeedsCondInvert) // Invert the condition if needed.
13356 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13357 DAG.getConstant(1, Cond.getValueType()));
13359 // Zero extend the condition if needed.
13360 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13362 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13363 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13364 DAG.getConstant(ShAmt, MVT::i8));
13367 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13368 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13369 if (NeedsCondInvert) // Invert the condition if needed.
13370 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13371 DAG.getConstant(1, Cond.getValueType()));
13373 // Zero extend the condition if needed.
13374 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13375 FalseC->getValueType(0), Cond);
13376 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13377 SDValue(FalseC, 0));
13380 // Optimize cases that will turn into an LEA instruction. This requires
13381 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13382 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13383 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13384 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13386 bool isFastMultiplier = false;
13388 switch ((unsigned char)Diff) {
13390 case 1: // result = add base, cond
13391 case 2: // result = lea base( , cond*2)
13392 case 3: // result = lea base(cond, cond*2)
13393 case 4: // result = lea base( , cond*4)
13394 case 5: // result = lea base(cond, cond*4)
13395 case 8: // result = lea base( , cond*8)
13396 case 9: // result = lea base(cond, cond*8)
13397 isFastMultiplier = true;
13402 if (isFastMultiplier) {
13403 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13404 if (NeedsCondInvert) // Invert the condition if needed.
13405 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13406 DAG.getConstant(1, Cond.getValueType()));
13408 // Zero extend the condition if needed.
13409 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13411 // Scale the condition by the difference.
13413 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13414 DAG.getConstant(Diff, Cond.getValueType()));
13416 // Add the base if non-zero.
13417 if (FalseC->getAPIntValue() != 0)
13418 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13419 SDValue(FalseC, 0));
13429 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13430 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13431 TargetLowering::DAGCombinerInfo &DCI) {
13432 DebugLoc DL = N->getDebugLoc();
13434 // If the flag operand isn't dead, don't touch this CMOV.
13435 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13438 SDValue FalseOp = N->getOperand(0);
13439 SDValue TrueOp = N->getOperand(1);
13440 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13441 SDValue Cond = N->getOperand(3);
13442 if (CC == X86::COND_E || CC == X86::COND_NE) {
13443 switch (Cond.getOpcode()) {
13447 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13448 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13449 return (CC == X86::COND_E) ? FalseOp : TrueOp;
13453 // If this is a select between two integer constants, try to do some
13454 // optimizations. Note that the operands are ordered the opposite of SELECT
13456 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13457 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13458 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13459 // larger than FalseC (the false value).
13460 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13461 CC = X86::GetOppositeBranchCondition(CC);
13462 std::swap(TrueC, FalseC);
13465 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
13466 // This is efficient for any integer data type (including i8/i16) and
13468 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13469 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13470 DAG.getConstant(CC, MVT::i8), Cond);
13472 // Zero extend the condition if needed.
13473 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13475 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13476 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13477 DAG.getConstant(ShAmt, MVT::i8));
13478 if (N->getNumValues() == 2) // Dead flag value?
13479 return DCI.CombineTo(N, Cond, SDValue());
13483 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
13484 // for any integer data type, including i8/i16.
13485 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13486 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13487 DAG.getConstant(CC, MVT::i8), Cond);
13489 // Zero extend the condition if needed.
13490 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13491 FalseC->getValueType(0), Cond);
13492 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13493 SDValue(FalseC, 0));
13495 if (N->getNumValues() == 2) // Dead flag value?
13496 return DCI.CombineTo(N, Cond, SDValue());
13500 // Optimize cases that will turn into an LEA instruction. This requires
13501 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13502 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13503 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13504 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13506 bool isFastMultiplier = false;
13508 switch ((unsigned char)Diff) {
13510 case 1: // result = add base, cond
13511 case 2: // result = lea base( , cond*2)
13512 case 3: // result = lea base(cond, cond*2)
13513 case 4: // result = lea base( , cond*4)
13514 case 5: // result = lea base(cond, cond*4)
13515 case 8: // result = lea base( , cond*8)
13516 case 9: // result = lea base(cond, cond*8)
13517 isFastMultiplier = true;
13522 if (isFastMultiplier) {
13523 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13524 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13525 DAG.getConstant(CC, MVT::i8), Cond);
13526 // Zero extend the condition if needed.
13527 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13529 // Scale the condition by the difference.
13531 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13532 DAG.getConstant(Diff, Cond.getValueType()));
13534 // Add the base if non-zero.
13535 if (FalseC->getAPIntValue() != 0)
13536 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13537 SDValue(FalseC, 0));
13538 if (N->getNumValues() == 2) // Dead flag value?
13539 return DCI.CombineTo(N, Cond, SDValue());
13549 /// PerformMulCombine - Optimize a single multiply with constant into two
13550 /// in order to implement it with two cheaper instructions, e.g.
13551 /// LEA + SHL, LEA + LEA.
13552 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13553 TargetLowering::DAGCombinerInfo &DCI) {
13554 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13557 EVT VT = N->getValueType(0);
13558 if (VT != MVT::i64)
13561 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13564 uint64_t MulAmt = C->getZExtValue();
13565 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13568 uint64_t MulAmt1 = 0;
13569 uint64_t MulAmt2 = 0;
13570 if ((MulAmt % 9) == 0) {
13572 MulAmt2 = MulAmt / 9;
13573 } else if ((MulAmt % 5) == 0) {
13575 MulAmt2 = MulAmt / 5;
13576 } else if ((MulAmt % 3) == 0) {
13578 MulAmt2 = MulAmt / 3;
13581 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13582 DebugLoc DL = N->getDebugLoc();
13584 if (isPowerOf2_64(MulAmt2) &&
13585 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13586 // If second multiplifer is pow2, issue it first. We want the multiply by
13587 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13589 std::swap(MulAmt1, MulAmt2);
13592 if (isPowerOf2_64(MulAmt1))
13593 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13594 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13596 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13597 DAG.getConstant(MulAmt1, VT));
13599 if (isPowerOf2_64(MulAmt2))
13600 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13601 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13603 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13604 DAG.getConstant(MulAmt2, VT));
13606 // Do not add new nodes to DAG combiner worklist.
13607 DCI.CombineTo(N, NewMul, false);
13612 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13613 SDValue N0 = N->getOperand(0);
13614 SDValue N1 = N->getOperand(1);
13615 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13616 EVT VT = N0.getValueType();
13618 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13619 // since the result of setcc_c is all zero's or all ones.
13620 if (VT.isInteger() && !VT.isVector() &&
13621 N1C && N0.getOpcode() == ISD::AND &&
13622 N0.getOperand(1).getOpcode() == ISD::Constant) {
13623 SDValue N00 = N0.getOperand(0);
13624 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13625 ((N00.getOpcode() == ISD::ANY_EXTEND ||
13626 N00.getOpcode() == ISD::ZERO_EXTEND) &&
13627 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13628 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13629 APInt ShAmt = N1C->getAPIntValue();
13630 Mask = Mask.shl(ShAmt);
13632 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13633 N00, DAG.getConstant(Mask, VT));
13638 // Hardware support for vector shifts is sparse which makes us scalarize the
13639 // vector operations in many cases. Also, on sandybridge ADD is faster than
13641 // (shl V, 1) -> add V,V
13642 if (isSplatVector(N1.getNode())) {
13643 assert(N0.getValueType().isVector() && "Invalid vector shift type");
13644 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13645 // We shift all of the values by one. In many cases we do not have
13646 // hardware support for this operation. This is better expressed as an ADD
13648 if (N1C && (1 == N1C->getZExtValue())) {
13649 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13656 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13658 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13659 const X86Subtarget *Subtarget) {
13660 EVT VT = N->getValueType(0);
13661 if (N->getOpcode() == ISD::SHL) {
13662 SDValue V = PerformSHLCombine(N, DAG);
13663 if (V.getNode()) return V;
13666 // On X86 with SSE2 support, we can transform this to a vector shift if
13667 // all elements are shifted by the same amount. We can't do this in legalize
13668 // because the a constant vector is typically transformed to a constant pool
13669 // so we have no knowledge of the shift amount.
13670 if (!Subtarget->hasXMMInt())
13673 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13674 (!Subtarget->hasAVX2() ||
13675 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13678 SDValue ShAmtOp = N->getOperand(1);
13679 EVT EltVT = VT.getVectorElementType();
13680 DebugLoc DL = N->getDebugLoc();
13681 SDValue BaseShAmt = SDValue();
13682 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13683 unsigned NumElts = VT.getVectorNumElements();
13685 for (; i != NumElts; ++i) {
13686 SDValue Arg = ShAmtOp.getOperand(i);
13687 if (Arg.getOpcode() == ISD::UNDEF) continue;
13691 for (; i != NumElts; ++i) {
13692 SDValue Arg = ShAmtOp.getOperand(i);
13693 if (Arg.getOpcode() == ISD::UNDEF) continue;
13694 if (Arg != BaseShAmt) {
13698 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13699 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13700 SDValue InVec = ShAmtOp.getOperand(0);
13701 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13702 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13704 for (; i != NumElts; ++i) {
13705 SDValue Arg = InVec.getOperand(i);
13706 if (Arg.getOpcode() == ISD::UNDEF) continue;
13710 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13711 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13712 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13713 if (C->getZExtValue() == SplatIdx)
13714 BaseShAmt = InVec.getOperand(1);
13717 if (BaseShAmt.getNode() == 0)
13718 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13719 DAG.getIntPtrConstant(0));
13723 // The shift amount is an i32.
13724 if (EltVT.bitsGT(MVT::i32))
13725 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13726 else if (EltVT.bitsLT(MVT::i32))
13727 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13729 // The shift amount is identical so we can do a vector shift.
13730 SDValue ValOp = N->getOperand(0);
13731 switch (N->getOpcode()) {
13733 llvm_unreachable("Unknown shift opcode!");
13736 if (VT == MVT::v2i64)
13737 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13738 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13740 if (VT == MVT::v4i32)
13741 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13742 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13744 if (VT == MVT::v8i16)
13745 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13746 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13748 if (VT == MVT::v4i64)
13749 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13750 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
13752 if (VT == MVT::v8i32)
13753 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13754 DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
13756 if (VT == MVT::v16i16)
13757 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13758 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
13762 if (VT == MVT::v4i32)
13763 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13764 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13766 if (VT == MVT::v8i16)
13767 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13768 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13770 if (VT == MVT::v8i32)
13771 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13772 DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
13774 if (VT == MVT::v16i16)
13775 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13776 DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
13780 if (VT == MVT::v2i64)
13781 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13782 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13784 if (VT == MVT::v4i32)
13785 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13786 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13788 if (VT == MVT::v8i16)
13789 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13790 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13792 if (VT == MVT::v4i64)
13793 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13794 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
13796 if (VT == MVT::v8i32)
13797 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13798 DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
13800 if (VT == MVT::v16i16)
13801 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13802 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
13810 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
13811 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13812 // and friends. Likewise for OR -> CMPNEQSS.
13813 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13814 TargetLowering::DAGCombinerInfo &DCI,
13815 const X86Subtarget *Subtarget) {
13818 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13819 // we're requiring SSE2 for both.
13820 if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13821 SDValue N0 = N->getOperand(0);
13822 SDValue N1 = N->getOperand(1);
13823 SDValue CMP0 = N0->getOperand(1);
13824 SDValue CMP1 = N1->getOperand(1);
13825 DebugLoc DL = N->getDebugLoc();
13827 // The SETCCs should both refer to the same CMP.
13828 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13831 SDValue CMP00 = CMP0->getOperand(0);
13832 SDValue CMP01 = CMP0->getOperand(1);
13833 EVT VT = CMP00.getValueType();
13835 if (VT == MVT::f32 || VT == MVT::f64) {
13836 bool ExpectingFlags = false;
13837 // Check for any users that want flags:
13838 for (SDNode::use_iterator UI = N->use_begin(),
13840 !ExpectingFlags && UI != UE; ++UI)
13841 switch (UI->getOpcode()) {
13846 ExpectingFlags = true;
13848 case ISD::CopyToReg:
13849 case ISD::SIGN_EXTEND:
13850 case ISD::ZERO_EXTEND:
13851 case ISD::ANY_EXTEND:
13855 if (!ExpectingFlags) {
13856 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13857 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13859 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13860 X86::CondCode tmp = cc0;
13865 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
13866 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13867 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13868 X86ISD::NodeType NTOperator = is64BitFP ?
13869 X86ISD::FSETCCsd : X86ISD::FSETCCss;
13870 // FIXME: need symbolic constants for these magic numbers.
13871 // See X86ATTInstPrinter.cpp:printSSECC().
13872 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13873 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13874 DAG.getConstant(x86cc, MVT::i8));
13875 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13877 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13878 DAG.getConstant(1, MVT::i32));
13879 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13880 return OneBitOfTruth;
13888 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13889 /// so it can be folded inside ANDNP.
13890 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13891 EVT VT = N->getValueType(0);
13893 // Match direct AllOnes for 128 and 256-bit vectors
13894 if (ISD::isBuildVectorAllOnes(N))
13897 // Look through a bit convert.
13898 if (N->getOpcode() == ISD::BITCAST)
13899 N = N->getOperand(0).getNode();
13901 // Sometimes the operand may come from a insert_subvector building a 256-bit
13903 if (VT.getSizeInBits() == 256 &&
13904 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13905 SDValue V1 = N->getOperand(0);
13906 SDValue V2 = N->getOperand(1);
13908 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13909 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13910 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13911 ISD::isBuildVectorAllOnes(V2.getNode()))
13918 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13919 TargetLowering::DAGCombinerInfo &DCI,
13920 const X86Subtarget *Subtarget) {
13921 if (DCI.isBeforeLegalizeOps())
13924 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13928 EVT VT = N->getValueType(0);
13930 // Create ANDN, BLSI, and BLSR instructions
13931 // BLSI is X & (-X)
13932 // BLSR is X & (X-1)
13933 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13934 SDValue N0 = N->getOperand(0);
13935 SDValue N1 = N->getOperand(1);
13936 DebugLoc DL = N->getDebugLoc();
13938 // Check LHS for not
13939 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13940 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13941 // Check RHS for not
13942 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13943 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13945 // Check LHS for neg
13946 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13947 isZero(N0.getOperand(0)))
13948 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13950 // Check RHS for neg
13951 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13952 isZero(N1.getOperand(0)))
13953 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13955 // Check LHS for X-1
13956 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13957 isAllOnes(N0.getOperand(1)))
13958 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13960 // Check RHS for X-1
13961 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13962 isAllOnes(N1.getOperand(1)))
13963 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13968 // Want to form ANDNP nodes:
13969 // 1) In the hopes of then easily combining them with OR and AND nodes
13970 // to form PBLEND/PSIGN.
13971 // 2) To match ANDN packed intrinsics
13972 if (VT != MVT::v2i64 && VT != MVT::v4i64)
13975 SDValue N0 = N->getOperand(0);
13976 SDValue N1 = N->getOperand(1);
13977 DebugLoc DL = N->getDebugLoc();
13979 // Check LHS for vnot
13980 if (N0.getOpcode() == ISD::XOR &&
13981 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13982 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13983 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13985 // Check RHS for vnot
13986 if (N1.getOpcode() == ISD::XOR &&
13987 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13988 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13989 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13994 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13995 TargetLowering::DAGCombinerInfo &DCI,
13996 const X86Subtarget *Subtarget) {
13997 if (DCI.isBeforeLegalizeOps())
14000 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14004 EVT VT = N->getValueType(0);
14006 SDValue N0 = N->getOperand(0);
14007 SDValue N1 = N->getOperand(1);
14009 // look for psign/blend
14010 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14011 if (!Subtarget->hasSSSE3orAVX() ||
14012 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14015 // Canonicalize pandn to RHS
14016 if (N0.getOpcode() == X86ISD::ANDNP)
14018 // or (and (m, x), (pandn m, y))
14019 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14020 SDValue Mask = N1.getOperand(0);
14021 SDValue X = N1.getOperand(1);
14023 if (N0.getOperand(0) == Mask)
14024 Y = N0.getOperand(1);
14025 if (N0.getOperand(1) == Mask)
14026 Y = N0.getOperand(0);
14028 // Check to see if the mask appeared in both the AND and ANDNP and
14032 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14033 if (Mask.getOpcode() != ISD::BITCAST ||
14034 X.getOpcode() != ISD::BITCAST ||
14035 Y.getOpcode() != ISD::BITCAST)
14038 // Look through mask bitcast.
14039 Mask = Mask.getOperand(0);
14040 EVT MaskVT = Mask.getValueType();
14042 // Validate that the Mask operand is a vector sra node. The sra node
14043 // will be an intrinsic.
14044 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
14047 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14048 // there is no psrai.b
14049 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
14050 case Intrinsic::x86_sse2_psrai_w:
14051 case Intrinsic::x86_sse2_psrai_d:
14052 case Intrinsic::x86_avx2_psrai_w:
14053 case Intrinsic::x86_avx2_psrai_d:
14055 default: return SDValue();
14058 // Check that the SRA is all signbits.
14059 SDValue SraC = Mask.getOperand(2);
14060 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
14061 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14062 if ((SraAmt + 1) != EltBits)
14065 DebugLoc DL = N->getDebugLoc();
14067 // Now we know we at least have a plendvb with the mask val. See if
14068 // we can form a psignb/w/d.
14069 // psign = x.type == y.type == mask.type && y = sub(0, x);
14070 X = X.getOperand(0);
14071 Y = Y.getOperand(0);
14072 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14073 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14074 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType() &&
14075 (EltBits == 8 || EltBits == 16 || EltBits == 32)) {
14076 SDValue Sign = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X,
14077 Mask.getOperand(1));
14078 return DAG.getNode(ISD::BITCAST, DL, VT, Sign);
14080 // PBLENDVB only available on SSE 4.1
14081 if (!Subtarget->hasSSE41orAVX())
14084 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14086 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14087 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14088 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14089 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, X, Y);
14090 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14094 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14097 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14098 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14100 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14102 if (!N0.hasOneUse() || !N1.hasOneUse())
14105 SDValue ShAmt0 = N0.getOperand(1);
14106 if (ShAmt0.getValueType() != MVT::i8)
14108 SDValue ShAmt1 = N1.getOperand(1);
14109 if (ShAmt1.getValueType() != MVT::i8)
14111 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14112 ShAmt0 = ShAmt0.getOperand(0);
14113 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14114 ShAmt1 = ShAmt1.getOperand(0);
14116 DebugLoc DL = N->getDebugLoc();
14117 unsigned Opc = X86ISD::SHLD;
14118 SDValue Op0 = N0.getOperand(0);
14119 SDValue Op1 = N1.getOperand(0);
14120 if (ShAmt0.getOpcode() == ISD::SUB) {
14121 Opc = X86ISD::SHRD;
14122 std::swap(Op0, Op1);
14123 std::swap(ShAmt0, ShAmt1);
14126 unsigned Bits = VT.getSizeInBits();
14127 if (ShAmt1.getOpcode() == ISD::SUB) {
14128 SDValue Sum = ShAmt1.getOperand(0);
14129 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14130 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14131 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14132 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14133 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14134 return DAG.getNode(Opc, DL, VT,
14136 DAG.getNode(ISD::TRUNCATE, DL,
14139 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14140 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14142 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14143 return DAG.getNode(Opc, DL, VT,
14144 N0.getOperand(0), N1.getOperand(0),
14145 DAG.getNode(ISD::TRUNCATE, DL,
14152 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14153 TargetLowering::DAGCombinerInfo &DCI,
14154 const X86Subtarget *Subtarget) {
14155 if (DCI.isBeforeLegalizeOps())
14158 EVT VT = N->getValueType(0);
14160 if (VT != MVT::i32 && VT != MVT::i64)
14163 // Create BLSMSK instructions by finding X ^ (X-1)
14164 SDValue N0 = N->getOperand(0);
14165 SDValue N1 = N->getOperand(1);
14166 DebugLoc DL = N->getDebugLoc();
14168 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14169 isAllOnes(N0.getOperand(1)))
14170 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14172 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14173 isAllOnes(N1.getOperand(1)))
14174 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14179 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14180 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14181 const X86Subtarget *Subtarget) {
14182 LoadSDNode *Ld = cast<LoadSDNode>(N);
14183 EVT RegVT = Ld->getValueType(0);
14184 EVT MemVT = Ld->getMemoryVT();
14185 DebugLoc dl = Ld->getDebugLoc();
14186 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14188 ISD::LoadExtType Ext = Ld->getExtensionType();
14190 // If this is a vector EXT Load then attempt to optimize it using a
14191 // shuffle. We need SSE4 for the shuffles.
14192 // TODO: It is possible to support ZExt by zeroing the undef values
14193 // during the shuffle phase or after the shuffle.
14194 if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14195 assert(MemVT != RegVT && "Cannot extend to the same type");
14196 assert(MemVT.isVector() && "Must load a vector from memory");
14198 unsigned NumElems = RegVT.getVectorNumElements();
14199 unsigned RegSz = RegVT.getSizeInBits();
14200 unsigned MemSz = MemVT.getSizeInBits();
14201 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14202 // All sizes must be a power of two
14203 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
14205 // Attempt to load the original value using a single load op.
14206 // Find a scalar type which is equal to the loaded word size.
14207 MVT SclrLoadTy = MVT::i8;
14208 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14209 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14210 MVT Tp = (MVT::SimpleValueType)tp;
14211 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() == MemSz) {
14217 // Proceed if a load word is found.
14218 if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
14220 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14221 RegSz/SclrLoadTy.getSizeInBits());
14223 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14224 RegSz/MemVT.getScalarType().getSizeInBits());
14225 // Can't shuffle using an illegal type.
14226 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14228 // Perform a single load.
14229 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14231 Ld->getPointerInfo(), Ld->isVolatile(),
14232 Ld->isNonTemporal(), Ld->isInvariant(),
14233 Ld->getAlignment());
14235 // Insert the word loaded into a vector.
14236 SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14237 LoadUnitVecVT, ScalarLoad);
14239 // Bitcast the loaded value to a vector of the original element type, in
14240 // the size of the target vector type.
14241 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
14242 unsigned SizeRatio = RegSz/MemSz;
14244 // Redistribute the loaded elements into the different locations.
14245 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14246 for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
14248 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14249 DAG.getUNDEF(SlicedVec.getValueType()),
14250 ShuffleVec.data());
14252 // Bitcast to the requested type.
14253 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14254 // Replace the original load with the new sequence
14255 // and return the new chain.
14256 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
14257 return SDValue(ScalarLoad.getNode(), 1);
14263 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14264 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14265 const X86Subtarget *Subtarget) {
14266 StoreSDNode *St = cast<StoreSDNode>(N);
14267 EVT VT = St->getValue().getValueType();
14268 EVT StVT = St->getMemoryVT();
14269 DebugLoc dl = St->getDebugLoc();
14270 SDValue StoredVal = St->getOperand(1);
14271 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14273 // If we are saving a concatination of two XMM registers, perform two stores.
14274 // This is better in Sandy Bridge cause one 256-bit mem op is done via two
14275 // 128-bit ones. If in the future the cost becomes only one memory access the
14276 // first version would be better.
14277 if (VT.getSizeInBits() == 256 &&
14278 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14279 StoredVal.getNumOperands() == 2) {
14281 SDValue Value0 = StoredVal.getOperand(0);
14282 SDValue Value1 = StoredVal.getOperand(1);
14284 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14285 SDValue Ptr0 = St->getBasePtr();
14286 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14288 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14289 St->getPointerInfo(), St->isVolatile(),
14290 St->isNonTemporal(), St->getAlignment());
14291 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14292 St->getPointerInfo(), St->isVolatile(),
14293 St->isNonTemporal(), St->getAlignment());
14294 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14297 // Optimize trunc store (of multiple scalars) to shuffle and store.
14298 // First, pack all of the elements in one place. Next, store to memory
14299 // in fewer chunks.
14300 if (St->isTruncatingStore() && VT.isVector()) {
14301 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14302 unsigned NumElems = VT.getVectorNumElements();
14303 assert(StVT != VT && "Cannot truncate to the same type");
14304 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14305 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14307 // From, To sizes and ElemCount must be pow of two
14308 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14309 // We are going to use the original vector elt for storing.
14310 // Accumulated smaller vector elements must be a multiple of the store size.
14311 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14313 unsigned SizeRatio = FromSz / ToSz;
14315 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14317 // Create a type on which we perform the shuffle
14318 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14319 StVT.getScalarType(), NumElems*SizeRatio);
14321 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14323 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14324 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14325 for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
14327 // Can't shuffle using an illegal type
14328 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14330 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14331 DAG.getUNDEF(WideVec.getValueType()),
14332 ShuffleVec.data());
14333 // At this point all of the data is stored at the bottom of the
14334 // register. We now need to save it to mem.
14336 // Find the largest store unit
14337 MVT StoreType = MVT::i8;
14338 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14339 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14340 MVT Tp = (MVT::SimpleValueType)tp;
14341 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14345 // Bitcast the original vector into a vector of store-size units
14346 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14347 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14348 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14349 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14350 SmallVector<SDValue, 8> Chains;
14351 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14352 TLI.getPointerTy());
14353 SDValue Ptr = St->getBasePtr();
14355 // Perform one or more big stores into memory.
14356 for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14357 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14358 StoreType, ShuffWide,
14359 DAG.getIntPtrConstant(i));
14360 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14361 St->getPointerInfo(), St->isVolatile(),
14362 St->isNonTemporal(), St->getAlignment());
14363 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14364 Chains.push_back(Ch);
14367 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14372 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
14373 // the FP state in cases where an emms may be missing.
14374 // A preferable solution to the general problem is to figure out the right
14375 // places to insert EMMS. This qualifies as a quick hack.
14377 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14378 if (VT.getSizeInBits() != 64)
14381 const Function *F = DAG.getMachineFunction().getFunction();
14382 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14383 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
14384 && Subtarget->hasXMMInt();
14385 if ((VT.isVector() ||
14386 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14387 isa<LoadSDNode>(St->getValue()) &&
14388 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14389 St->getChain().hasOneUse() && !St->isVolatile()) {
14390 SDNode* LdVal = St->getValue().getNode();
14391 LoadSDNode *Ld = 0;
14392 int TokenFactorIndex = -1;
14393 SmallVector<SDValue, 8> Ops;
14394 SDNode* ChainVal = St->getChain().getNode();
14395 // Must be a store of a load. We currently handle two cases: the load
14396 // is a direct child, and it's under an intervening TokenFactor. It is
14397 // possible to dig deeper under nested TokenFactors.
14398 if (ChainVal == LdVal)
14399 Ld = cast<LoadSDNode>(St->getChain());
14400 else if (St->getValue().hasOneUse() &&
14401 ChainVal->getOpcode() == ISD::TokenFactor) {
14402 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14403 if (ChainVal->getOperand(i).getNode() == LdVal) {
14404 TokenFactorIndex = i;
14405 Ld = cast<LoadSDNode>(St->getValue());
14407 Ops.push_back(ChainVal->getOperand(i));
14411 if (!Ld || !ISD::isNormalLoad(Ld))
14414 // If this is not the MMX case, i.e. we are just turning i64 load/store
14415 // into f64 load/store, avoid the transformation if there are multiple
14416 // uses of the loaded value.
14417 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14420 DebugLoc LdDL = Ld->getDebugLoc();
14421 DebugLoc StDL = N->getDebugLoc();
14422 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14423 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14425 if (Subtarget->is64Bit() || F64IsLegal) {
14426 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14427 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14428 Ld->getPointerInfo(), Ld->isVolatile(),
14429 Ld->isNonTemporal(), Ld->isInvariant(),
14430 Ld->getAlignment());
14431 SDValue NewChain = NewLd.getValue(1);
14432 if (TokenFactorIndex != -1) {
14433 Ops.push_back(NewChain);
14434 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14437 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14438 St->getPointerInfo(),
14439 St->isVolatile(), St->isNonTemporal(),
14440 St->getAlignment());
14443 // Otherwise, lower to two pairs of 32-bit loads / stores.
14444 SDValue LoAddr = Ld->getBasePtr();
14445 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14446 DAG.getConstant(4, MVT::i32));
14448 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14449 Ld->getPointerInfo(),
14450 Ld->isVolatile(), Ld->isNonTemporal(),
14451 Ld->isInvariant(), Ld->getAlignment());
14452 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14453 Ld->getPointerInfo().getWithOffset(4),
14454 Ld->isVolatile(), Ld->isNonTemporal(),
14456 MinAlign(Ld->getAlignment(), 4));
14458 SDValue NewChain = LoLd.getValue(1);
14459 if (TokenFactorIndex != -1) {
14460 Ops.push_back(LoLd);
14461 Ops.push_back(HiLd);
14462 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14466 LoAddr = St->getBasePtr();
14467 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14468 DAG.getConstant(4, MVT::i32));
14470 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14471 St->getPointerInfo(),
14472 St->isVolatile(), St->isNonTemporal(),
14473 St->getAlignment());
14474 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14475 St->getPointerInfo().getWithOffset(4),
14477 St->isNonTemporal(),
14478 MinAlign(St->getAlignment(), 4));
14479 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14484 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14485 /// and return the operands for the horizontal operation in LHS and RHS. A
14486 /// horizontal operation performs the binary operation on successive elements
14487 /// of its first operand, then on successive elements of its second operand,
14488 /// returning the resulting values in a vector. For example, if
14489 /// A = < float a0, float a1, float a2, float a3 >
14491 /// B = < float b0, float b1, float b2, float b3 >
14492 /// then the result of doing a horizontal operation on A and B is
14493 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14494 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14495 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14496 /// set to A, RHS to B, and the routine returns 'true'.
14497 /// Note that the binary operation should have the property that if one of the
14498 /// operands is UNDEF then the result is UNDEF.
14499 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
14500 // Look for the following pattern: if
14501 // A = < float a0, float a1, float a2, float a3 >
14502 // B = < float b0, float b1, float b2, float b3 >
14504 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14505 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14506 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14507 // which is A horizontal-op B.
14509 // At least one of the operands should be a vector shuffle.
14510 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14511 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14514 EVT VT = LHS.getValueType();
14515 unsigned N = VT.getVectorNumElements();
14517 // View LHS in the form
14518 // LHS = VECTOR_SHUFFLE A, B, LMask
14519 // If LHS is not a shuffle then pretend it is the shuffle
14520 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14521 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14524 SmallVector<int, 8> LMask(N);
14525 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14526 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14527 A = LHS.getOperand(0);
14528 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14529 B = LHS.getOperand(1);
14530 cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14532 if (LHS.getOpcode() != ISD::UNDEF)
14534 for (unsigned i = 0; i != N; ++i)
14538 // Likewise, view RHS in the form
14539 // RHS = VECTOR_SHUFFLE C, D, RMask
14541 SmallVector<int, 8> RMask(N);
14542 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14543 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14544 C = RHS.getOperand(0);
14545 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14546 D = RHS.getOperand(1);
14547 cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14549 if (RHS.getOpcode() != ISD::UNDEF)
14551 for (unsigned i = 0; i != N; ++i)
14555 // Check that the shuffles are both shuffling the same vectors.
14556 if (!(A == C && B == D) && !(A == D && B == C))
14559 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14560 if (!A.getNode() && !B.getNode())
14563 // If A and B occur in reverse order in RHS, then "swap" them (which means
14564 // rewriting the mask).
14566 for (unsigned i = 0; i != N; ++i) {
14567 unsigned Idx = RMask[i];
14570 else if (Idx < 2*N)
14574 // At this point LHS and RHS are equivalent to
14575 // LHS = VECTOR_SHUFFLE A, B, LMask
14576 // RHS = VECTOR_SHUFFLE A, B, RMask
14577 // Check that the masks correspond to performing a horizontal operation.
14578 for (unsigned i = 0; i != N; ++i) {
14579 unsigned LIdx = LMask[i], RIdx = RMask[i];
14581 // Ignore any UNDEF components.
14582 if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
14583 || (!B.getNode() && (LIdx >= N || RIdx >= N)))
14586 // Check that successive elements are being operated on. If not, this is
14587 // not a horizontal operation.
14588 if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
14589 !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
14593 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14594 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14598 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14599 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14600 const X86Subtarget *Subtarget) {
14601 EVT VT = N->getValueType(0);
14602 SDValue LHS = N->getOperand(0);
14603 SDValue RHS = N->getOperand(1);
14605 // Try to synthesize horizontal adds from adds of shuffles.
14606 if (Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14607 isHorizontalBinOp(LHS, RHS, true))
14608 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14612 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14613 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14614 const X86Subtarget *Subtarget) {
14615 EVT VT = N->getValueType(0);
14616 SDValue LHS = N->getOperand(0);
14617 SDValue RHS = N->getOperand(1);
14619 // Try to synthesize horizontal subs from subs of shuffles.
14620 if (Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14621 isHorizontalBinOp(LHS, RHS, false))
14622 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14626 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14627 /// X86ISD::FXOR nodes.
14628 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14629 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14630 // F[X]OR(0.0, x) -> x
14631 // F[X]OR(x, 0.0) -> x
14632 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14633 if (C->getValueAPF().isPosZero())
14634 return N->getOperand(1);
14635 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14636 if (C->getValueAPF().isPosZero())
14637 return N->getOperand(0);
14641 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14642 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14643 // FAND(0.0, x) -> 0.0
14644 // FAND(x, 0.0) -> 0.0
14645 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14646 if (C->getValueAPF().isPosZero())
14647 return N->getOperand(0);
14648 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14649 if (C->getValueAPF().isPosZero())
14650 return N->getOperand(1);
14654 static SDValue PerformBTCombine(SDNode *N,
14656 TargetLowering::DAGCombinerInfo &DCI) {
14657 // BT ignores high bits in the bit index operand.
14658 SDValue Op1 = N->getOperand(1);
14659 if (Op1.hasOneUse()) {
14660 unsigned BitWidth = Op1.getValueSizeInBits();
14661 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14662 APInt KnownZero, KnownOne;
14663 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14664 !DCI.isBeforeLegalizeOps());
14665 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14666 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14667 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14668 DCI.CommitTargetLoweringOpt(TLO);
14673 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14674 SDValue Op = N->getOperand(0);
14675 if (Op.getOpcode() == ISD::BITCAST)
14676 Op = Op.getOperand(0);
14677 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14678 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14679 VT.getVectorElementType().getSizeInBits() ==
14680 OpVT.getVectorElementType().getSizeInBits()) {
14681 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14686 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14687 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
14688 // (and (i32 x86isd::setcc_carry), 1)
14689 // This eliminates the zext. This transformation is necessary because
14690 // ISD::SETCC is always legalized to i8.
14691 DebugLoc dl = N->getDebugLoc();
14692 SDValue N0 = N->getOperand(0);
14693 EVT VT = N->getValueType(0);
14694 if (N0.getOpcode() == ISD::AND &&
14696 N0.getOperand(0).hasOneUse()) {
14697 SDValue N00 = N0.getOperand(0);
14698 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14700 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14701 if (!C || C->getZExtValue() != 1)
14703 return DAG.getNode(ISD::AND, dl, VT,
14704 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14705 N00.getOperand(0), N00.getOperand(1)),
14706 DAG.getConstant(1, VT));
14712 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14713 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14714 unsigned X86CC = N->getConstantOperandVal(0);
14715 SDValue EFLAG = N->getOperand(1);
14716 DebugLoc DL = N->getDebugLoc();
14718 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14719 // a zext and produces an all-ones bit which is more useful than 0/1 in some
14721 if (X86CC == X86::COND_B)
14722 return DAG.getNode(ISD::AND, DL, MVT::i8,
14723 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14724 DAG.getConstant(X86CC, MVT::i8), EFLAG),
14725 DAG.getConstant(1, MVT::i8));
14730 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14731 const X86TargetLowering *XTLI) {
14732 SDValue Op0 = N->getOperand(0);
14733 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14734 // a 32-bit target where SSE doesn't support i64->FP operations.
14735 if (Op0.getOpcode() == ISD::LOAD) {
14736 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14737 EVT VT = Ld->getValueType(0);
14738 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14739 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14740 !XTLI->getSubtarget()->is64Bit() &&
14741 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14742 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14743 Ld->getChain(), Op0, DAG);
14744 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14751 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14752 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14753 X86TargetLowering::DAGCombinerInfo &DCI) {
14754 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14755 // the result is either zero or one (depending on the input carry bit).
14756 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14757 if (X86::isZeroNode(N->getOperand(0)) &&
14758 X86::isZeroNode(N->getOperand(1)) &&
14759 // We don't have a good way to replace an EFLAGS use, so only do this when
14761 SDValue(N, 1).use_empty()) {
14762 DebugLoc DL = N->getDebugLoc();
14763 EVT VT = N->getValueType(0);
14764 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14765 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14766 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14767 DAG.getConstant(X86::COND_B,MVT::i8),
14769 DAG.getConstant(1, VT));
14770 return DCI.CombineTo(N, Res1, CarryOut);
14776 // fold (add Y, (sete X, 0)) -> adc 0, Y
14777 // (add Y, (setne X, 0)) -> sbb -1, Y
14778 // (sub (sete X, 0), Y) -> sbb 0, Y
14779 // (sub (setne X, 0), Y) -> adc -1, Y
14780 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14781 DebugLoc DL = N->getDebugLoc();
14783 // Look through ZExts.
14784 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14785 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14788 SDValue SetCC = Ext.getOperand(0);
14789 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14792 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14793 if (CC != X86::COND_E && CC != X86::COND_NE)
14796 SDValue Cmp = SetCC.getOperand(1);
14797 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14798 !X86::isZeroNode(Cmp.getOperand(1)) ||
14799 !Cmp.getOperand(0).getValueType().isInteger())
14802 SDValue CmpOp0 = Cmp.getOperand(0);
14803 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14804 DAG.getConstant(1, CmpOp0.getValueType()));
14806 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14807 if (CC == X86::COND_NE)
14808 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14809 DL, OtherVal.getValueType(), OtherVal,
14810 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14811 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14812 DL, OtherVal.getValueType(), OtherVal,
14813 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14816 /// PerformADDCombine - Do target-specific dag combines on integer adds.
14817 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
14818 const X86Subtarget *Subtarget) {
14819 EVT VT = N->getValueType(0);
14820 SDValue Op0 = N->getOperand(0);
14821 SDValue Op1 = N->getOperand(1);
14823 // Try to synthesize horizontal adds from adds of shuffles.
14824 if ((Subtarget->hasSSSE3orAVX()) && (VT == MVT::v8i16 || VT == MVT::v4i32) &&
14825 isHorizontalBinOp(Op0, Op1, true))
14826 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
14828 return OptimizeConditionalInDecrement(N, DAG);
14831 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
14832 const X86Subtarget *Subtarget) {
14833 SDValue Op0 = N->getOperand(0);
14834 SDValue Op1 = N->getOperand(1);
14836 // X86 can't encode an immediate LHS of a sub. See if we can push the
14837 // negation into a preceding instruction.
14838 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14839 // If the RHS of the sub is a XOR with one use and a constant, invert the
14840 // immediate. Then add one to the LHS of the sub so we can turn
14841 // X-Y -> X+~Y+1, saving one register.
14842 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14843 isa<ConstantSDNode>(Op1.getOperand(1))) {
14844 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14845 EVT VT = Op0.getValueType();
14846 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14848 DAG.getConstant(~XorC, VT));
14849 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14850 DAG.getConstant(C->getAPIntValue()+1, VT));
14854 // Try to synthesize horizontal adds from adds of shuffles.
14855 EVT VT = N->getValueType(0);
14856 if ((Subtarget->hasSSSE3orAVX()) && (VT == MVT::v8i16 || VT == MVT::v4i32) &&
14857 isHorizontalBinOp(Op0, Op1, false))
14858 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
14860 return OptimizeConditionalInDecrement(N, DAG);
14863 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14864 DAGCombinerInfo &DCI) const {
14865 SelectionDAG &DAG = DCI.DAG;
14866 switch (N->getOpcode()) {
14868 case ISD::EXTRACT_VECTOR_ELT:
14869 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14871 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
14872 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
14873 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
14874 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
14875 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
14876 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
14879 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
14880 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
14881 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
14882 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
14883 case ISD::LOAD: return PerformLOADCombine(N, DAG, Subtarget);
14884 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
14885 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
14886 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
14887 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
14889 case X86ISD::FOR: return PerformFORCombine(N, DAG);
14890 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
14891 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
14892 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
14893 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
14894 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
14895 case X86ISD::SHUFPS: // Handle all target specific shuffles
14896 case X86ISD::SHUFPD:
14897 case X86ISD::PALIGN:
14898 case X86ISD::PUNPCKHBW:
14899 case X86ISD::PUNPCKHWD:
14900 case X86ISD::PUNPCKHDQ:
14901 case X86ISD::PUNPCKHQDQ:
14902 case X86ISD::VPUNPCKHBWY:
14903 case X86ISD::VPUNPCKHWDY:
14904 case X86ISD::VPUNPCKHDQY:
14905 case X86ISD::VPUNPCKHQDQY:
14906 case X86ISD::UNPCKHPS:
14907 case X86ISD::UNPCKHPD:
14908 case X86ISD::VUNPCKHPSY:
14909 case X86ISD::VUNPCKHPDY:
14910 case X86ISD::PUNPCKLBW:
14911 case X86ISD::PUNPCKLWD:
14912 case X86ISD::PUNPCKLDQ:
14913 case X86ISD::PUNPCKLQDQ:
14914 case X86ISD::VPUNPCKLBWY:
14915 case X86ISD::VPUNPCKLWDY:
14916 case X86ISD::VPUNPCKLDQY:
14917 case X86ISD::VPUNPCKLQDQY:
14918 case X86ISD::UNPCKLPS:
14919 case X86ISD::UNPCKLPD:
14920 case X86ISD::VUNPCKLPSY:
14921 case X86ISD::VUNPCKLPDY:
14922 case X86ISD::MOVHLPS:
14923 case X86ISD::MOVLHPS:
14924 case X86ISD::PSHUFD:
14925 case X86ISD::PSHUFHW:
14926 case X86ISD::PSHUFLW:
14927 case X86ISD::MOVSS:
14928 case X86ISD::MOVSD:
14929 case X86ISD::VPERMILPS:
14930 case X86ISD::VPERMILPSY:
14931 case X86ISD::VPERMILPD:
14932 case X86ISD::VPERMILPDY:
14933 case X86ISD::VPERM2F128:
14934 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14940 /// isTypeDesirableForOp - Return true if the target has native support for
14941 /// the specified value type and it is 'desirable' to use the type for the
14942 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14943 /// instruction encodings are longer and some i16 instructions are slow.
14944 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14945 if (!isTypeLegal(VT))
14947 if (VT != MVT::i16)
14954 case ISD::SIGN_EXTEND:
14955 case ISD::ZERO_EXTEND:
14956 case ISD::ANY_EXTEND:
14969 /// IsDesirableToPromoteOp - This method query the target whether it is
14970 /// beneficial for dag combiner to promote the specified node. If true, it
14971 /// should return the desired promotion type by reference.
14972 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14973 EVT VT = Op.getValueType();
14974 if (VT != MVT::i16)
14977 bool Promote = false;
14978 bool Commute = false;
14979 switch (Op.getOpcode()) {
14982 LoadSDNode *LD = cast<LoadSDNode>(Op);
14983 // If the non-extending load has a single use and it's not live out, then it
14984 // might be folded.
14985 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14986 Op.hasOneUse()*/) {
14987 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14988 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14989 // The only case where we'd want to promote LOAD (rather then it being
14990 // promoted as an operand is when it's only use is liveout.
14991 if (UI->getOpcode() != ISD::CopyToReg)
14998 case ISD::SIGN_EXTEND:
14999 case ISD::ZERO_EXTEND:
15000 case ISD::ANY_EXTEND:
15005 SDValue N0 = Op.getOperand(0);
15006 // Look out for (store (shl (load), x)).
15007 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
15020 SDValue N0 = Op.getOperand(0);
15021 SDValue N1 = Op.getOperand(1);
15022 if (!Commute && MayFoldLoad(N1))
15024 // Avoid disabling potential load folding opportunities.
15025 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
15027 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
15037 //===----------------------------------------------------------------------===//
15038 // X86 Inline Assembly Support
15039 //===----------------------------------------------------------------------===//
15041 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15042 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15044 std::string AsmStr = IA->getAsmString();
15046 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15047 SmallVector<StringRef, 4> AsmPieces;
15048 SplitString(AsmStr, AsmPieces, ";\n");
15050 switch (AsmPieces.size()) {
15051 default: return false;
15053 AsmStr = AsmPieces[0];
15055 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
15057 // FIXME: this should verify that we are targeting a 486 or better. If not,
15058 // we will turn this bswap into something that will be lowered to logical ops
15059 // instead of emitting the bswap asm. For now, we don't support 486 or lower
15060 // so don't worry about this.
15062 if (AsmPieces.size() == 2 &&
15063 (AsmPieces[0] == "bswap" ||
15064 AsmPieces[0] == "bswapq" ||
15065 AsmPieces[0] == "bswapl") &&
15066 (AsmPieces[1] == "$0" ||
15067 AsmPieces[1] == "${0:q}")) {
15068 // No need to check constraints, nothing other than the equivalent of
15069 // "=r,0" would be valid here.
15070 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15071 if (!Ty || Ty->getBitWidth() % 16 != 0)
15073 return IntrinsicLowering::LowerToByteSwap(CI);
15075 // rorw $$8, ${0:w} --> llvm.bswap.i16
15076 if (CI->getType()->isIntegerTy(16) &&
15077 AsmPieces.size() == 3 &&
15078 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
15079 AsmPieces[1] == "$$8," &&
15080 AsmPieces[2] == "${0:w}" &&
15081 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
15083 const std::string &ConstraintsStr = IA->getConstraintString();
15084 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15085 std::sort(AsmPieces.begin(), AsmPieces.end());
15086 if (AsmPieces.size() == 4 &&
15087 AsmPieces[0] == "~{cc}" &&
15088 AsmPieces[1] == "~{dirflag}" &&
15089 AsmPieces[2] == "~{flags}" &&
15090 AsmPieces[3] == "~{fpsr}") {
15091 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15092 if (!Ty || Ty->getBitWidth() % 16 != 0)
15094 return IntrinsicLowering::LowerToByteSwap(CI);
15099 if (CI->getType()->isIntegerTy(32) &&
15100 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
15101 SmallVector<StringRef, 4> Words;
15102 SplitString(AsmPieces[0], Words, " \t,");
15103 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
15104 Words[2] == "${0:w}") {
15106 SplitString(AsmPieces[1], Words, " \t,");
15107 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
15108 Words[2] == "$0") {
15110 SplitString(AsmPieces[2], Words, " \t,");
15111 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
15112 Words[2] == "${0:w}") {
15114 const std::string &ConstraintsStr = IA->getConstraintString();
15115 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15116 std::sort(AsmPieces.begin(), AsmPieces.end());
15117 if (AsmPieces.size() == 4 &&
15118 AsmPieces[0] == "~{cc}" &&
15119 AsmPieces[1] == "~{dirflag}" &&
15120 AsmPieces[2] == "~{flags}" &&
15121 AsmPieces[3] == "~{fpsr}") {
15122 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15123 if (!Ty || Ty->getBitWidth() % 16 != 0)
15125 return IntrinsicLowering::LowerToByteSwap(CI);
15132 if (CI->getType()->isIntegerTy(64)) {
15133 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15134 if (Constraints.size() >= 2 &&
15135 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15136 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15137 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
15138 SmallVector<StringRef, 4> Words;
15139 SplitString(AsmPieces[0], Words, " \t");
15140 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
15142 SplitString(AsmPieces[1], Words, " \t");
15143 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
15145 SplitString(AsmPieces[2], Words, " \t,");
15146 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
15147 Words[2] == "%edx") {
15148 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15149 if (!Ty || Ty->getBitWidth() % 16 != 0)
15151 return IntrinsicLowering::LowerToByteSwap(CI);
15164 /// getConstraintType - Given a constraint letter, return the type of
15165 /// constraint it is for this target.
15166 X86TargetLowering::ConstraintType
15167 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15168 if (Constraint.size() == 1) {
15169 switch (Constraint[0]) {
15180 return C_RegisterClass;
15204 return TargetLowering::getConstraintType(Constraint);
15207 /// Examine constraint type and operand type and determine a weight value.
15208 /// This object must already have been set up with the operand type
15209 /// and the current alternative constraint selected.
15210 TargetLowering::ConstraintWeight
15211 X86TargetLowering::getSingleConstraintMatchWeight(
15212 AsmOperandInfo &info, const char *constraint) const {
15213 ConstraintWeight weight = CW_Invalid;
15214 Value *CallOperandVal = info.CallOperandVal;
15215 // If we don't have a value, we can't do a match,
15216 // but allow it at the lowest weight.
15217 if (CallOperandVal == NULL)
15219 Type *type = CallOperandVal->getType();
15220 // Look at the constraint type.
15221 switch (*constraint) {
15223 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15234 if (CallOperandVal->getType()->isIntegerTy())
15235 weight = CW_SpecificReg;
15240 if (type->isFloatingPointTy())
15241 weight = CW_SpecificReg;
15244 if (type->isX86_MMXTy() && Subtarget->hasMMX())
15245 weight = CW_SpecificReg;
15249 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
15250 weight = CW_Register;
15253 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15254 if (C->getZExtValue() <= 31)
15255 weight = CW_Constant;
15259 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15260 if (C->getZExtValue() <= 63)
15261 weight = CW_Constant;
15265 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15266 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15267 weight = CW_Constant;
15271 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15272 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15273 weight = CW_Constant;
15277 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15278 if (C->getZExtValue() <= 3)
15279 weight = CW_Constant;
15283 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15284 if (C->getZExtValue() <= 0xff)
15285 weight = CW_Constant;
15290 if (dyn_cast<ConstantFP>(CallOperandVal)) {
15291 weight = CW_Constant;
15295 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15296 if ((C->getSExtValue() >= -0x80000000LL) &&
15297 (C->getSExtValue() <= 0x7fffffffLL))
15298 weight = CW_Constant;
15302 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15303 if (C->getZExtValue() <= 0xffffffff)
15304 weight = CW_Constant;
15311 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15312 /// with another that has more specific requirements based on the type of the
15313 /// corresponding operand.
15314 const char *X86TargetLowering::
15315 LowerXConstraint(EVT ConstraintVT) const {
15316 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15317 // 'f' like normal targets.
15318 if (ConstraintVT.isFloatingPoint()) {
15319 if (Subtarget->hasXMMInt())
15321 if (Subtarget->hasXMM())
15325 return TargetLowering::LowerXConstraint(ConstraintVT);
15328 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15329 /// vector. If it is invalid, don't add anything to Ops.
15330 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15331 std::string &Constraint,
15332 std::vector<SDValue>&Ops,
15333 SelectionDAG &DAG) const {
15334 SDValue Result(0, 0);
15336 // Only support length 1 constraints for now.
15337 if (Constraint.length() > 1) return;
15339 char ConstraintLetter = Constraint[0];
15340 switch (ConstraintLetter) {
15343 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15344 if (C->getZExtValue() <= 31) {
15345 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15351 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15352 if (C->getZExtValue() <= 63) {
15353 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15359 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15360 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15361 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15367 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15368 if (C->getZExtValue() <= 255) {
15369 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15375 // 32-bit signed value
15376 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15377 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15378 C->getSExtValue())) {
15379 // Widen to 64 bits here to get it sign extended.
15380 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15383 // FIXME gcc accepts some relocatable values here too, but only in certain
15384 // memory models; it's complicated.
15389 // 32-bit unsigned value
15390 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15391 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15392 C->getZExtValue())) {
15393 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15397 // FIXME gcc accepts some relocatable values here too, but only in certain
15398 // memory models; it's complicated.
15402 // Literal immediates are always ok.
15403 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15404 // Widen to 64 bits here to get it sign extended.
15405 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15409 // In any sort of PIC mode addresses need to be computed at runtime by
15410 // adding in a register or some sort of table lookup. These can't
15411 // be used as immediates.
15412 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15415 // If we are in non-pic codegen mode, we allow the address of a global (with
15416 // an optional displacement) to be used with 'i'.
15417 GlobalAddressSDNode *GA = 0;
15418 int64_t Offset = 0;
15420 // Match either (GA), (GA+C), (GA+C1+C2), etc.
15422 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15423 Offset += GA->getOffset();
15425 } else if (Op.getOpcode() == ISD::ADD) {
15426 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15427 Offset += C->getZExtValue();
15428 Op = Op.getOperand(0);
15431 } else if (Op.getOpcode() == ISD::SUB) {
15432 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15433 Offset += -C->getZExtValue();
15434 Op = Op.getOperand(0);
15439 // Otherwise, this isn't something we can handle, reject it.
15443 const GlobalValue *GV = GA->getGlobal();
15444 // If we require an extra load to get this address, as in PIC mode, we
15445 // can't accept it.
15446 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15447 getTargetMachine())))
15450 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15451 GA->getValueType(0), Offset);
15456 if (Result.getNode()) {
15457 Ops.push_back(Result);
15460 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15463 std::pair<unsigned, const TargetRegisterClass*>
15464 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15466 // First, see if this is a constraint that directly corresponds to an LLVM
15468 if (Constraint.size() == 1) {
15469 // GCC Constraint Letters
15470 switch (Constraint[0]) {
15472 // TODO: Slight differences here in allocation order and leaving
15473 // RIP in the class. Do they matter any more here than they do
15474 // in the normal allocation?
15475 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15476 if (Subtarget->is64Bit()) {
15477 if (VT == MVT::i32 || VT == MVT::f32)
15478 return std::make_pair(0U, X86::GR32RegisterClass);
15479 else if (VT == MVT::i16)
15480 return std::make_pair(0U, X86::GR16RegisterClass);
15481 else if (VT == MVT::i8 || VT == MVT::i1)
15482 return std::make_pair(0U, X86::GR8RegisterClass);
15483 else if (VT == MVT::i64 || VT == MVT::f64)
15484 return std::make_pair(0U, X86::GR64RegisterClass);
15487 // 32-bit fallthrough
15488 case 'Q': // Q_REGS
15489 if (VT == MVT::i32 || VT == MVT::f32)
15490 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15491 else if (VT == MVT::i16)
15492 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15493 else if (VT == MVT::i8 || VT == MVT::i1)
15494 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15495 else if (VT == MVT::i64)
15496 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15498 case 'r': // GENERAL_REGS
15499 case 'l': // INDEX_REGS
15500 if (VT == MVT::i8 || VT == MVT::i1)
15501 return std::make_pair(0U, X86::GR8RegisterClass);
15502 if (VT == MVT::i16)
15503 return std::make_pair(0U, X86::GR16RegisterClass);
15504 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15505 return std::make_pair(0U, X86::GR32RegisterClass);
15506 return std::make_pair(0U, X86::GR64RegisterClass);
15507 case 'R': // LEGACY_REGS
15508 if (VT == MVT::i8 || VT == MVT::i1)
15509 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15510 if (VT == MVT::i16)
15511 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15512 if (VT == MVT::i32 || !Subtarget->is64Bit())
15513 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15514 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15515 case 'f': // FP Stack registers.
15516 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15517 // value to the correct fpstack register class.
15518 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15519 return std::make_pair(0U, X86::RFP32RegisterClass);
15520 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15521 return std::make_pair(0U, X86::RFP64RegisterClass);
15522 return std::make_pair(0U, X86::RFP80RegisterClass);
15523 case 'y': // MMX_REGS if MMX allowed.
15524 if (!Subtarget->hasMMX()) break;
15525 return std::make_pair(0U, X86::VR64RegisterClass);
15526 case 'Y': // SSE_REGS if SSE2 allowed
15527 if (!Subtarget->hasXMMInt()) break;
15529 case 'x': // SSE_REGS if SSE1 allowed
15530 if (!Subtarget->hasXMM()) break;
15532 switch (VT.getSimpleVT().SimpleTy) {
15534 // Scalar SSE types.
15537 return std::make_pair(0U, X86::FR32RegisterClass);
15540 return std::make_pair(0U, X86::FR64RegisterClass);
15548 return std::make_pair(0U, X86::VR128RegisterClass);
15554 // Use the default implementation in TargetLowering to convert the register
15555 // constraint into a member of a register class.
15556 std::pair<unsigned, const TargetRegisterClass*> Res;
15557 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15559 // Not found as a standard register?
15560 if (Res.second == 0) {
15561 // Map st(0) -> st(7) -> ST0
15562 if (Constraint.size() == 7 && Constraint[0] == '{' &&
15563 tolower(Constraint[1]) == 's' &&
15564 tolower(Constraint[2]) == 't' &&
15565 Constraint[3] == '(' &&
15566 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15567 Constraint[5] == ')' &&
15568 Constraint[6] == '}') {
15570 Res.first = X86::ST0+Constraint[4]-'0';
15571 Res.second = X86::RFP80RegisterClass;
15575 // GCC allows "st(0)" to be called just plain "st".
15576 if (StringRef("{st}").equals_lower(Constraint)) {
15577 Res.first = X86::ST0;
15578 Res.second = X86::RFP80RegisterClass;
15583 if (StringRef("{flags}").equals_lower(Constraint)) {
15584 Res.first = X86::EFLAGS;
15585 Res.second = X86::CCRRegisterClass;
15589 // 'A' means EAX + EDX.
15590 if (Constraint == "A") {
15591 Res.first = X86::EAX;
15592 Res.second = X86::GR32_ADRegisterClass;
15598 // Otherwise, check to see if this is a register class of the wrong value
15599 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15600 // turn into {ax},{dx}.
15601 if (Res.second->hasType(VT))
15602 return Res; // Correct type already, nothing to do.
15604 // All of the single-register GCC register classes map their values onto
15605 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
15606 // really want an 8-bit or 32-bit register, map to the appropriate register
15607 // class and return the appropriate register.
15608 if (Res.second == X86::GR16RegisterClass) {
15609 if (VT == MVT::i8) {
15610 unsigned DestReg = 0;
15611 switch (Res.first) {
15613 case X86::AX: DestReg = X86::AL; break;
15614 case X86::DX: DestReg = X86::DL; break;
15615 case X86::CX: DestReg = X86::CL; break;
15616 case X86::BX: DestReg = X86::BL; break;
15619 Res.first = DestReg;
15620 Res.second = X86::GR8RegisterClass;
15622 } else if (VT == MVT::i32) {
15623 unsigned DestReg = 0;
15624 switch (Res.first) {
15626 case X86::AX: DestReg = X86::EAX; break;
15627 case X86::DX: DestReg = X86::EDX; break;
15628 case X86::CX: DestReg = X86::ECX; break;
15629 case X86::BX: DestReg = X86::EBX; break;
15630 case X86::SI: DestReg = X86::ESI; break;
15631 case X86::DI: DestReg = X86::EDI; break;
15632 case X86::BP: DestReg = X86::EBP; break;
15633 case X86::SP: DestReg = X86::ESP; break;
15636 Res.first = DestReg;
15637 Res.second = X86::GR32RegisterClass;
15639 } else if (VT == MVT::i64) {
15640 unsigned DestReg = 0;
15641 switch (Res.first) {
15643 case X86::AX: DestReg = X86::RAX; break;
15644 case X86::DX: DestReg = X86::RDX; break;
15645 case X86::CX: DestReg = X86::RCX; break;
15646 case X86::BX: DestReg = X86::RBX; break;
15647 case X86::SI: DestReg = X86::RSI; break;
15648 case X86::DI: DestReg = X86::RDI; break;
15649 case X86::BP: DestReg = X86::RBP; break;
15650 case X86::SP: DestReg = X86::RSP; break;
15653 Res.first = DestReg;
15654 Res.second = X86::GR64RegisterClass;
15657 } else if (Res.second == X86::FR32RegisterClass ||
15658 Res.second == X86::FR64RegisterClass ||
15659 Res.second == X86::VR128RegisterClass) {
15660 // Handle references to XMM physical registers that got mapped into the
15661 // wrong class. This can happen with constraints like {xmm0} where the
15662 // target independent register mapper will just pick the first match it can
15663 // find, ignoring the required type.
15664 if (VT == MVT::f32)
15665 Res.second = X86::FR32RegisterClass;
15666 else if (VT == MVT::f64)
15667 Res.second = X86::FR64RegisterClass;
15668 else if (X86::VR128RegisterClass->hasType(VT))
15669 Res.second = X86::VR128RegisterClass;