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::UNPCKLP:
2847 case X86ISD::PUNPCKL:
2848 case X86ISD::UNPCKHP:
2849 case X86ISD::PUNPCKH:
2850 case X86ISD::VPERMILPS:
2851 case X86ISD::VPERMILPD:
2852 case X86ISD::VPERM2F128:
2853 case X86ISD::VPERM2I128:
2859 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2860 SDValue V1, SelectionDAG &DAG) {
2862 default: llvm_unreachable("Unknown x86 shuffle node");
2863 case X86ISD::MOVSHDUP:
2864 case X86ISD::MOVSLDUP:
2865 case X86ISD::MOVDDUP:
2866 return DAG.getNode(Opc, dl, VT, V1);
2872 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2873 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2875 default: llvm_unreachable("Unknown x86 shuffle node");
2876 case X86ISD::PSHUFD:
2877 case X86ISD::PSHUFHW:
2878 case X86ISD::PSHUFLW:
2879 case X86ISD::VPERMILPS:
2880 case X86ISD::VPERMILPD:
2881 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2887 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2888 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2890 default: llvm_unreachable("Unknown x86 shuffle node");
2891 case X86ISD::PALIGN:
2892 case X86ISD::SHUFPD:
2893 case X86ISD::SHUFPS:
2894 case X86ISD::VPERM2F128:
2895 case X86ISD::VPERM2I128:
2896 return DAG.getNode(Opc, dl, VT, V1, V2,
2897 DAG.getConstant(TargetMask, MVT::i8));
2902 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2903 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2905 default: llvm_unreachable("Unknown x86 shuffle node");
2906 case X86ISD::MOVLHPS:
2907 case X86ISD::MOVLHPD:
2908 case X86ISD::MOVHLPS:
2909 case X86ISD::MOVLPS:
2910 case X86ISD::MOVLPD:
2913 case X86ISD::UNPCKLP:
2914 case X86ISD::PUNPCKL:
2915 case X86ISD::UNPCKHP:
2916 case X86ISD::PUNPCKH:
2917 return DAG.getNode(Opc, dl, VT, V1, V2);
2922 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2923 MachineFunction &MF = DAG.getMachineFunction();
2924 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2925 int ReturnAddrIndex = FuncInfo->getRAIndex();
2927 if (ReturnAddrIndex == 0) {
2928 // Set up a frame object for the return address.
2929 uint64_t SlotSize = TD->getPointerSize();
2930 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2932 FuncInfo->setRAIndex(ReturnAddrIndex);
2935 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2939 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2940 bool hasSymbolicDisplacement) {
2941 // Offset should fit into 32 bit immediate field.
2942 if (!isInt<32>(Offset))
2945 // If we don't have a symbolic displacement - we don't have any extra
2947 if (!hasSymbolicDisplacement)
2950 // FIXME: Some tweaks might be needed for medium code model.
2951 if (M != CodeModel::Small && M != CodeModel::Kernel)
2954 // For small code model we assume that latest object is 16MB before end of 31
2955 // bits boundary. We may also accept pretty large negative constants knowing
2956 // that all objects are in the positive half of address space.
2957 if (M == CodeModel::Small && Offset < 16*1024*1024)
2960 // For kernel code model we know that all object resist in the negative half
2961 // of 32bits address space. We may not accept negative offsets, since they may
2962 // be just off and we may accept pretty large positive ones.
2963 if (M == CodeModel::Kernel && Offset > 0)
2969 /// isCalleePop - Determines whether the callee is required to pop its
2970 /// own arguments. Callee pop is necessary to support tail calls.
2971 bool X86::isCalleePop(CallingConv::ID CallingConv,
2972 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2976 switch (CallingConv) {
2979 case CallingConv::X86_StdCall:
2981 case CallingConv::X86_FastCall:
2983 case CallingConv::X86_ThisCall:
2985 case CallingConv::Fast:
2987 case CallingConv::GHC:
2992 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2993 /// specific condition code, returning the condition code and the LHS/RHS of the
2994 /// comparison to make.
2995 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2996 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2998 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2999 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3000 // X > -1 -> X == 0, jump !sign.
3001 RHS = DAG.getConstant(0, RHS.getValueType());
3002 return X86::COND_NS;
3003 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3004 // X < 0 -> X == 0, jump on sign.
3006 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3008 RHS = DAG.getConstant(0, RHS.getValueType());
3009 return X86::COND_LE;
3013 switch (SetCCOpcode) {
3014 default: llvm_unreachable("Invalid integer condition!");
3015 case ISD::SETEQ: return X86::COND_E;
3016 case ISD::SETGT: return X86::COND_G;
3017 case ISD::SETGE: return X86::COND_GE;
3018 case ISD::SETLT: return X86::COND_L;
3019 case ISD::SETLE: return X86::COND_LE;
3020 case ISD::SETNE: return X86::COND_NE;
3021 case ISD::SETULT: return X86::COND_B;
3022 case ISD::SETUGT: return X86::COND_A;
3023 case ISD::SETULE: return X86::COND_BE;
3024 case ISD::SETUGE: return X86::COND_AE;
3028 // First determine if it is required or is profitable to flip the operands.
3030 // If LHS is a foldable load, but RHS is not, flip the condition.
3031 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3032 !ISD::isNON_EXTLoad(RHS.getNode())) {
3033 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3034 std::swap(LHS, RHS);
3037 switch (SetCCOpcode) {
3043 std::swap(LHS, RHS);
3047 // On a floating point condition, the flags are set as follows:
3049 // 0 | 0 | 0 | X > Y
3050 // 0 | 0 | 1 | X < Y
3051 // 1 | 0 | 0 | X == Y
3052 // 1 | 1 | 1 | unordered
3053 switch (SetCCOpcode) {
3054 default: llvm_unreachable("Condcode should be pre-legalized away");
3056 case ISD::SETEQ: return X86::COND_E;
3057 case ISD::SETOLT: // flipped
3059 case ISD::SETGT: return X86::COND_A;
3060 case ISD::SETOLE: // flipped
3062 case ISD::SETGE: return X86::COND_AE;
3063 case ISD::SETUGT: // flipped
3065 case ISD::SETLT: return X86::COND_B;
3066 case ISD::SETUGE: // flipped
3068 case ISD::SETLE: return X86::COND_BE;
3070 case ISD::SETNE: return X86::COND_NE;
3071 case ISD::SETUO: return X86::COND_P;
3072 case ISD::SETO: return X86::COND_NP;
3074 case ISD::SETUNE: return X86::COND_INVALID;
3078 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3079 /// code. Current x86 isa includes the following FP cmov instructions:
3080 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3081 static bool hasFPCMov(unsigned X86CC) {
3097 /// isFPImmLegal - Returns true if the target can instruction select the
3098 /// specified FP immediate natively. If false, the legalizer will
3099 /// materialize the FP immediate as a load from a constant pool.
3100 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3101 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3102 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3108 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3109 /// the specified range (L, H].
3110 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3111 return (Val < 0) || (Val >= Low && Val < Hi);
3114 /// isUndefOrInRange - Return true if every element in Mask, begining
3115 /// from position Pos and ending in Pos+Size, falls within the specified
3116 /// range (L, L+Pos]. or is undef.
3117 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3118 int Pos, int Size, int Low, int Hi) {
3119 for (int i = Pos, e = Pos+Size; i != e; ++i)
3120 if (!isUndefOrInRange(Mask[i], Low, Hi))
3125 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3126 /// specified value.
3127 static bool isUndefOrEqual(int Val, int CmpVal) {
3128 if (Val < 0 || Val == CmpVal)
3133 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3134 /// from position Pos and ending in Pos+Size, falls within the specified
3135 /// sequential range (L, L+Pos]. or is undef.
3136 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3137 int Pos, int Size, int Low) {
3138 for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3139 if (!isUndefOrEqual(Mask[i], Low))
3144 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3145 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3146 /// the second operand.
3147 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3148 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3149 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3150 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3151 return (Mask[0] < 2 && Mask[1] < 2);
3155 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3156 SmallVector<int, 8> M;
3158 return ::isPSHUFDMask(M, N->getValueType(0));
3161 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3162 /// is suitable for input to PSHUFHW.
3163 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3164 if (VT != MVT::v8i16)
3167 // Lower quadword copied in order or undef.
3168 for (int i = 0; i != 4; ++i)
3169 if (Mask[i] >= 0 && Mask[i] != i)
3172 // Upper quadword shuffled.
3173 for (int i = 4; i != 8; ++i)
3174 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3180 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3181 SmallVector<int, 8> M;
3183 return ::isPSHUFHWMask(M, N->getValueType(0));
3186 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3187 /// is suitable for input to PSHUFLW.
3188 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3189 if (VT != MVT::v8i16)
3192 // Upper quadword copied in order.
3193 for (int i = 4; i != 8; ++i)
3194 if (Mask[i] >= 0 && Mask[i] != i)
3197 // Lower quadword shuffled.
3198 for (int i = 0; i != 4; ++i)
3205 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3206 SmallVector<int, 8> M;
3208 return ::isPSHUFLWMask(M, N->getValueType(0));
3211 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3212 /// is suitable for input to PALIGNR.
3213 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3214 bool hasSSSE3OrAVX) {
3215 int i, e = VT.getVectorNumElements();
3216 if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3219 // Do not handle v2i64 / v2f64 shuffles with palignr.
3220 if (e < 4 || !hasSSSE3OrAVX)
3223 for (i = 0; i != e; ++i)
3227 // All undef, not a palignr.
3231 // Make sure we're shifting in the right direction.
3235 int s = Mask[i] - i;
3237 // Check the rest of the elements to see if they are consecutive.
3238 for (++i; i != e; ++i) {
3240 if (m >= 0 && m != s+i)
3246 /// isVSHUFPYMask - Return true if the specified VECTOR_SHUFFLE operand
3247 /// specifies a shuffle of elements that is suitable for input to 256-bit
3249 static bool isVSHUFPYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3251 int NumElems = VT.getVectorNumElements();
3253 if (!HasAVX || VT.getSizeInBits() != 256)
3256 if (NumElems != 4 && NumElems != 8)
3259 // VSHUFPSY divides the resulting vector into 4 chunks.
3260 // The sources are also splitted into 4 chunks, and each destination
3261 // chunk must come from a different source chunk.
3263 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3264 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3266 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3267 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3269 // VSHUFPDY divides the resulting vector into 4 chunks.
3270 // The sources are also splitted into 4 chunks, and each destination
3271 // chunk must come from a different source chunk.
3273 // SRC1 => X3 X2 X1 X0
3274 // SRC2 => Y3 Y2 Y1 Y0
3276 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3278 int QuarterSize = NumElems/4;
3279 int HalfSize = QuarterSize*2;
3280 for (int i = 0; i < QuarterSize; ++i)
3281 if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3283 for (int i = QuarterSize; i < QuarterSize*2; ++i)
3284 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3287 // For VSHUFPSY, the mask of the second half must be the same as the first
3288 // but with the appropriate offsets. This works in the same way as
3289 // VPERMILPS works with masks.
3290 for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3291 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3295 // VSHUFPSY handling
3296 int FstHalfIdx = i-HalfSize;
3297 if (Mask[FstHalfIdx] < 0)
3299 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3302 for (int i = QuarterSize*3; i < NumElems; ++i) {
3303 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3305 int FstHalfIdx = i-HalfSize;
3308 // VSHUFPSY handling
3309 if (Mask[FstHalfIdx] < 0)
3311 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3318 /// isCommutedVSHUFP() - Returns true if the shuffle mask is exactly
3319 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3320 /// half elements to come from vector 1 (which would equal the dest.) and
3321 /// the upper half to come from vector 2.
3322 static bool isCommutedVSHUFPY(ShuffleVectorSDNode *N, bool HasAVX) {
3323 EVT VT = N->getValueType(0);
3324 int NumElems = VT.getVectorNumElements();
3325 SmallVector<int, 8> Mask;
3328 if (!HasAVX || VT.getSizeInBits() != 256)
3331 if (NumElems != 4 && NumElems != 8)
3334 // VSHUFPSY divides the resulting vector into 4 chunks.
3335 // The sources are also splitted into 4 chunks, and each destination
3336 // chunk must come from a different source chunk.
3338 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3339 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3341 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3342 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3344 // VSHUFPDY divides the resulting vector into 4 chunks.
3345 // The sources are also splitted into 4 chunks, and each destination
3346 // chunk must come from a different source chunk.
3348 // SRC1 => X3 X2 X1 X0
3349 // SRC2 => Y3 Y2 Y1 Y0
3351 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3353 int QuarterSize = NumElems/4;
3354 int HalfSize = QuarterSize*2;
3355 for (int i = 0; i < QuarterSize; ++i)
3356 if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3358 for (int i = QuarterSize; i < QuarterSize*2; ++i)
3359 if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3362 // For VSHUFPSY, the mask of the second half must be the same as the first
3363 // but with the appropriate offsets. This works in the same way as
3364 // VPERMILPS works with masks.
3365 for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3366 if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3370 // VSHUFPSY handling
3371 int FstHalfIdx = i-HalfSize;
3372 if (Mask[FstHalfIdx] < 0)
3374 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3377 for (int i = QuarterSize*3; i < NumElems; ++i) {
3378 if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3382 // VSHUFPSY handling
3383 int FstHalfIdx = i-HalfSize;
3384 if (Mask[FstHalfIdx] < 0)
3386 if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3393 /// getShuffleVSHUFPYImmediate - Return the appropriate immediate to shuffle
3394 /// the specified VECTOR_MASK mask with VSHUFPSY/VSHUFPDY instructions.
3395 static unsigned getShuffleVSHUFPYImmediate(SDNode *N) {
3396 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3397 EVT VT = SVOp->getValueType(0);
3398 int NumElems = VT.getVectorNumElements();
3400 assert(VT.getSizeInBits() == 256 && "Only supports 256-bit types");
3401 assert((NumElems == 4 || NumElems == 8) && "Only supports v4 and v8 types");
3403 int HalfSize = NumElems/2;
3404 unsigned Mul = (NumElems == 8) ? 2 : 1;
3406 for (int i = 0; i != NumElems; ++i) {
3407 int Elt = SVOp->getMaskElt(i);
3412 // For VSHUFPSY, the mask of the first half must be equal to the second one.
3413 if (NumElems == 8) Shamt %= HalfSize;
3414 Mask |= Elt << (Shamt*Mul);
3420 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3421 /// the two vector operands have swapped position.
3422 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3423 unsigned NumElems = VT.getVectorNumElements();
3424 for (unsigned i = 0; i != NumElems; ++i) {
3428 else if (idx < (int)NumElems)
3429 Mask[i] = idx + NumElems;
3431 Mask[i] = idx - NumElems;
3435 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3436 /// specifies a shuffle of elements that is suitable for input to 128-bit
3437 /// SHUFPS and SHUFPD.
3438 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3439 int NumElems = VT.getVectorNumElements();
3441 if (VT.getSizeInBits() != 128)
3444 if (NumElems != 2 && NumElems != 4)
3447 int Half = NumElems / 2;
3448 for (int i = 0; i < Half; ++i)
3449 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3451 for (int i = Half; i < NumElems; ++i)
3452 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3458 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3459 SmallVector<int, 8> M;
3461 return ::isSHUFPMask(M, N->getValueType(0));
3464 /// isCommutedSHUFPMask - Returns true if the shuffle mask is exactly
3465 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3466 /// half elements to come from vector 1 (which would equal the dest.) and
3467 /// the upper half to come from vector 2.
3468 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3469 int NumElems = VT.getVectorNumElements();
3471 if (NumElems != 2 && NumElems != 4)
3474 int Half = NumElems / 2;
3475 for (int i = 0; i < Half; ++i)
3476 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3478 for (int i = Half; i < NumElems; ++i)
3479 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3484 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3485 SmallVector<int, 8> M;
3487 return isCommutedSHUFPMask(M, N->getValueType(0));
3490 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3491 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3492 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3493 EVT VT = N->getValueType(0);
3494 unsigned NumElems = VT.getVectorNumElements();
3496 if (VT.getSizeInBits() != 128)
3502 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3503 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3504 isUndefOrEqual(N->getMaskElt(1), 7) &&
3505 isUndefOrEqual(N->getMaskElt(2), 2) &&
3506 isUndefOrEqual(N->getMaskElt(3), 3);
3509 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3510 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3512 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3513 EVT VT = N->getValueType(0);
3514 unsigned NumElems = VT.getVectorNumElements();
3516 if (VT.getSizeInBits() != 128)
3522 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3523 isUndefOrEqual(N->getMaskElt(1), 3) &&
3524 isUndefOrEqual(N->getMaskElt(2), 2) &&
3525 isUndefOrEqual(N->getMaskElt(3), 3);
3528 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3529 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3530 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3531 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3533 if (NumElems != 2 && NumElems != 4)
3536 for (unsigned i = 0; i < NumElems/2; ++i)
3537 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3540 for (unsigned i = NumElems/2; i < NumElems; ++i)
3541 if (!isUndefOrEqual(N->getMaskElt(i), i))
3547 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3548 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3549 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3550 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3552 if ((NumElems != 2 && NumElems != 4)
3553 || N->getValueType(0).getSizeInBits() > 128)
3556 for (unsigned i = 0; i < NumElems/2; ++i)
3557 if (!isUndefOrEqual(N->getMaskElt(i), i))
3560 for (unsigned i = 0; i < NumElems/2; ++i)
3561 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3567 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3568 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3569 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3570 bool HasAVX2, bool V2IsSplat = false) {
3571 int NumElts = VT.getVectorNumElements();
3573 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3574 "Unsupported vector type for unpckh");
3576 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3577 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3580 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3581 // independently on 128-bit lanes.
3582 unsigned NumLanes = VT.getSizeInBits()/128;
3583 unsigned NumLaneElts = NumElts/NumLanes;
3586 unsigned End = NumLaneElts;
3587 for (unsigned s = 0; s < NumLanes; ++s) {
3588 for (unsigned i = Start, j = s * NumLaneElts;
3592 int BitI1 = Mask[i+1];
3593 if (!isUndefOrEqual(BitI, j))
3596 if (!isUndefOrEqual(BitI1, NumElts))
3599 if (!isUndefOrEqual(BitI1, j + NumElts))
3603 // Process the next 128 bits.
3604 Start += NumLaneElts;
3611 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3612 SmallVector<int, 8> M;
3614 return ::isUNPCKLMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3617 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3618 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3619 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3620 bool HasAVX2, bool V2IsSplat = false) {
3621 int NumElts = VT.getVectorNumElements();
3623 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3624 "Unsupported vector type for unpckh");
3626 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3627 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3630 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3631 // independently on 128-bit lanes.
3632 unsigned NumLanes = VT.getSizeInBits()/128;
3633 unsigned NumLaneElts = NumElts/NumLanes;
3636 unsigned End = NumLaneElts;
3637 for (unsigned l = 0; l != NumLanes; ++l) {
3638 for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3639 i != End; i += 2, ++j) {
3641 int BitI1 = Mask[i+1];
3642 if (!isUndefOrEqual(BitI, j))
3645 if (isUndefOrEqual(BitI1, NumElts))
3648 if (!isUndefOrEqual(BitI1, j+NumElts))
3652 // Process the next 128 bits.
3653 Start += NumLaneElts;
3659 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3660 SmallVector<int, 8> M;
3662 return ::isUNPCKHMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3665 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3666 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3668 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3669 int NumElems = VT.getVectorNumElements();
3670 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3673 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3674 // FIXME: Need a better way to get rid of this, there's no latency difference
3675 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3676 // the former later. We should also remove the "_undef" special mask.
3677 if (NumElems == 4 && VT.getSizeInBits() == 256)
3680 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3681 // independently on 128-bit lanes.
3682 unsigned NumLanes = VT.getSizeInBits() / 128;
3683 unsigned NumLaneElts = NumElems / NumLanes;
3685 for (unsigned s = 0; s < NumLanes; ++s) {
3686 for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3687 i != NumLaneElts * (s + 1);
3690 int BitI1 = Mask[i+1];
3692 if (!isUndefOrEqual(BitI, j))
3694 if (!isUndefOrEqual(BitI1, j))
3702 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3703 SmallVector<int, 8> M;
3705 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3708 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3709 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3711 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3712 int NumElems = VT.getVectorNumElements();
3713 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3716 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3718 int BitI1 = Mask[i+1];
3719 if (!isUndefOrEqual(BitI, j))
3721 if (!isUndefOrEqual(BitI1, j))
3727 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3728 SmallVector<int, 8> M;
3730 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3733 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3734 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3735 /// MOVSD, and MOVD, i.e. setting the lowest element.
3736 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3737 if (VT.getVectorElementType().getSizeInBits() < 32)
3740 int NumElts = VT.getVectorNumElements();
3742 if (!isUndefOrEqual(Mask[0], NumElts))
3745 for (int i = 1; i < NumElts; ++i)
3746 if (!isUndefOrEqual(Mask[i], i))
3752 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3753 SmallVector<int, 8> M;
3755 return ::isMOVLMask(M, N->getValueType(0));
3758 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3759 /// as permutations between 128-bit chunks or halves. As an example: this
3761 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3762 /// The first half comes from the second half of V1 and the second half from the
3763 /// the second half of V2.
3764 static bool isVPERM2X128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3766 if (!HasAVX || VT.getSizeInBits() != 256)
3769 // The shuffle result is divided into half A and half B. In total the two
3770 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3771 // B must come from C, D, E or F.
3772 int HalfSize = VT.getVectorNumElements()/2;
3773 bool MatchA = false, MatchB = false;
3775 // Check if A comes from one of C, D, E, F.
3776 for (int Half = 0; Half < 4; ++Half) {
3777 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3783 // Check if B comes from one of C, D, E, F.
3784 for (int Half = 0; Half < 4; ++Half) {
3785 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3791 return MatchA && MatchB;
3794 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3795 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3796 static unsigned getShuffleVPERM2X128Immediate(SDNode *N) {
3797 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3798 EVT VT = SVOp->getValueType(0);
3800 int HalfSize = VT.getVectorNumElements()/2;
3802 int FstHalf = 0, SndHalf = 0;
3803 for (int i = 0; i < HalfSize; ++i) {
3804 if (SVOp->getMaskElt(i) > 0) {
3805 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3809 for (int i = HalfSize; i < HalfSize*2; ++i) {
3810 if (SVOp->getMaskElt(i) > 0) {
3811 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3816 return (FstHalf | (SndHalf << 4));
3819 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3820 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3821 /// Note that VPERMIL mask matching is different depending whether theunderlying
3822 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3823 /// to the same elements of the low, but to the higher half of the source.
3824 /// In VPERMILPD the two lanes could be shuffled independently of each other
3825 /// with the same restriction that lanes can't be crossed.
3826 static bool isVPERMILPMask(const SmallVectorImpl<int> &Mask, EVT VT,
3828 int NumElts = VT.getVectorNumElements();
3829 int NumLanes = VT.getSizeInBits()/128;
3834 // Only match 256-bit with 32/64-bit types
3835 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3838 int LaneSize = NumElts/NumLanes;
3839 for (int l = 0; l != NumLanes; ++l) {
3840 int LaneStart = l*LaneSize;
3841 for (int i = 0; i != LaneSize; ++i) {
3842 if (!isUndefOrInRange(Mask[i+LaneStart], LaneStart, LaneStart+LaneSize))
3844 if (NumElts == 4 || l == 0)
3846 // VPERMILPS handling
3849 if (!isUndefOrEqual(Mask[i+LaneStart], Mask[i]+LaneSize))
3857 /// getShuffleVPERMILPImmediate - Return the appropriate immediate to shuffle
3858 /// the specified VECTOR_MASK mask with VPERMILPS/D* instructions.
3859 static unsigned getShuffleVPERMILPImmediate(SDNode *N) {
3860 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3861 EVT VT = SVOp->getValueType(0);
3863 int NumElts = VT.getVectorNumElements();
3864 int NumLanes = VT.getSizeInBits()/128;
3865 int LaneSize = NumElts/NumLanes;
3867 // Although the mask is equal for both lanes do it twice to get the cases
3868 // where a mask will match because the same mask element is undef on the
3869 // first half but valid on the second. This would get pathological cases
3870 // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3871 unsigned Shift = (LaneSize == 4) ? 2 : 1;
3873 for (int i = 0; i != NumElts; ++i) {
3874 int MaskElt = SVOp->getMaskElt(i);
3877 MaskElt %= LaneSize;
3879 // VPERMILPSY, the mask of the first half must be equal to the second one
3880 if (NumElts == 8) Shamt %= LaneSize;
3881 Mask |= MaskElt << (Shamt*Shift);
3887 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3888 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3889 /// element of vector 2 and the other elements to come from vector 1 in order.
3890 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3891 bool V2IsSplat = false, bool V2IsUndef = false) {
3892 int NumOps = VT.getVectorNumElements();
3893 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3896 if (!isUndefOrEqual(Mask[0], 0))
3899 for (int i = 1; i < NumOps; ++i)
3900 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3901 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3902 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3908 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3909 bool V2IsUndef = false) {
3910 SmallVector<int, 8> M;
3912 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3915 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3916 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3917 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3918 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3919 const X86Subtarget *Subtarget) {
3920 if (!Subtarget->hasSSE3orAVX())
3923 // The second vector must be undef
3924 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3927 EVT VT = N->getValueType(0);
3928 unsigned NumElems = VT.getVectorNumElements();
3930 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3931 (VT.getSizeInBits() == 256 && NumElems != 8))
3934 // "i+1" is the value the indexed mask element must have
3935 for (unsigned i = 0; i < NumElems; i += 2)
3936 if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3937 !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3943 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3944 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3945 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3946 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3947 const X86Subtarget *Subtarget) {
3948 if (!Subtarget->hasSSE3orAVX())
3951 // The second vector must be undef
3952 if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3955 EVT VT = N->getValueType(0);
3956 unsigned NumElems = VT.getVectorNumElements();
3958 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3959 (VT.getSizeInBits() == 256 && NumElems != 8))
3962 // "i" is the value the indexed mask element must have
3963 for (unsigned i = 0; i < NumElems; i += 2)
3964 if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3965 !isUndefOrEqual(N->getMaskElt(i+1), i))
3971 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3972 /// specifies a shuffle of elements that is suitable for input to 256-bit
3973 /// version of MOVDDUP.
3974 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
3975 const X86Subtarget *Subtarget) {
3976 EVT VT = N->getValueType(0);
3977 int NumElts = VT.getVectorNumElements();
3978 bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
3980 if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
3981 !V2IsUndef || NumElts != 4)
3984 for (int i = 0; i != NumElts/2; ++i)
3985 if (!isUndefOrEqual(N->getMaskElt(i), 0))
3987 for (int i = NumElts/2; i != NumElts; ++i)
3988 if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
3993 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3994 /// specifies a shuffle of elements that is suitable for input to 128-bit
3995 /// version of MOVDDUP.
3996 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3997 EVT VT = N->getValueType(0);
3999 if (VT.getSizeInBits() != 128)
4002 int e = VT.getVectorNumElements() / 2;
4003 for (int i = 0; i < e; ++i)
4004 if (!isUndefOrEqual(N->getMaskElt(i), i))
4006 for (int i = 0; i < e; ++i)
4007 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
4012 /// isVEXTRACTF128Index - Return true if the specified
4013 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4014 /// suitable for input to VEXTRACTF128.
4015 bool X86::isVEXTRACTF128Index(SDNode *N) {
4016 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4019 // The index should be aligned on a 128-bit boundary.
4021 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4023 unsigned VL = N->getValueType(0).getVectorNumElements();
4024 unsigned VBits = N->getValueType(0).getSizeInBits();
4025 unsigned ElSize = VBits / VL;
4026 bool Result = (Index * ElSize) % 128 == 0;
4031 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4032 /// operand specifies a subvector insert that is suitable for input to
4034 bool X86::isVINSERTF128Index(SDNode *N) {
4035 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4038 // The index should be aligned on a 128-bit boundary.
4040 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4042 unsigned VL = N->getValueType(0).getVectorNumElements();
4043 unsigned VBits = N->getValueType(0).getSizeInBits();
4044 unsigned ElSize = VBits / VL;
4045 bool Result = (Index * ElSize) % 128 == 0;
4050 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4051 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4052 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4053 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4054 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4056 unsigned Shift = (NumOperands == 4) ? 2 : 1;
4058 for (int i = 0; i < NumOperands; ++i) {
4059 int Val = SVOp->getMaskElt(NumOperands-i-1);
4060 if (Val < 0) Val = 0;
4061 if (Val >= NumOperands) Val -= NumOperands;
4063 if (i != NumOperands - 1)
4069 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4070 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4071 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4072 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4074 // 8 nodes, but we only care about the last 4.
4075 for (unsigned i = 7; i >= 4; --i) {
4076 int Val = SVOp->getMaskElt(i);
4085 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4086 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4087 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4088 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4090 // 8 nodes, but we only care about the first 4.
4091 for (int i = 3; i >= 0; --i) {
4092 int Val = SVOp->getMaskElt(i);
4101 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4102 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4103 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4104 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4105 EVT VVT = N->getValueType(0);
4106 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4110 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4111 Val = SVOp->getMaskElt(i);
4115 assert(Val - i > 0 && "PALIGNR imm should be positive");
4116 return (Val - i) * EltSize;
4119 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4120 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4122 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4123 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4124 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4127 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4129 EVT VecVT = N->getOperand(0).getValueType();
4130 EVT ElVT = VecVT.getVectorElementType();
4132 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4133 return Index / NumElemsPerChunk;
4136 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4137 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4139 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4140 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4141 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4144 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4146 EVT VecVT = N->getValueType(0);
4147 EVT ElVT = VecVT.getVectorElementType();
4149 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4150 return Index / NumElemsPerChunk;
4153 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4155 bool X86::isZeroNode(SDValue Elt) {
4156 return ((isa<ConstantSDNode>(Elt) &&
4157 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4158 (isa<ConstantFPSDNode>(Elt) &&
4159 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4162 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4163 /// their permute mask.
4164 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4165 SelectionDAG &DAG) {
4166 EVT VT = SVOp->getValueType(0);
4167 unsigned NumElems = VT.getVectorNumElements();
4168 SmallVector<int, 8> MaskVec;
4170 for (unsigned i = 0; i != NumElems; ++i) {
4171 int idx = SVOp->getMaskElt(i);
4173 MaskVec.push_back(idx);
4174 else if (idx < (int)NumElems)
4175 MaskVec.push_back(idx + NumElems);
4177 MaskVec.push_back(idx - NumElems);
4179 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4180 SVOp->getOperand(0), &MaskVec[0]);
4183 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4184 /// match movhlps. The lower half elements should come from upper half of
4185 /// V1 (and in order), and the upper half elements should come from the upper
4186 /// half of V2 (and in order).
4187 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4188 EVT VT = Op->getValueType(0);
4189 if (VT.getSizeInBits() != 128)
4191 if (VT.getVectorNumElements() != 4)
4193 for (unsigned i = 0, e = 2; i != e; ++i)
4194 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4196 for (unsigned i = 2; i != 4; ++i)
4197 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4202 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4203 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4205 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4206 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4208 N = N->getOperand(0).getNode();
4209 if (!ISD::isNON_EXTLoad(N))
4212 *LD = cast<LoadSDNode>(N);
4216 // Test whether the given value is a vector value which will be legalized
4218 static bool WillBeConstantPoolLoad(SDNode *N) {
4219 if (N->getOpcode() != ISD::BUILD_VECTOR)
4222 // Check for any non-constant elements.
4223 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4224 switch (N->getOperand(i).getNode()->getOpcode()) {
4226 case ISD::ConstantFP:
4233 // Vectors of all-zeros and all-ones are materialized with special
4234 // instructions rather than being loaded.
4235 return !ISD::isBuildVectorAllZeros(N) &&
4236 !ISD::isBuildVectorAllOnes(N);
4239 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4240 /// match movlp{s|d}. The lower half elements should come from lower half of
4241 /// V1 (and in order), and the upper half elements should come from the upper
4242 /// half of V2 (and in order). And since V1 will become the source of the
4243 /// MOVLP, it must be either a vector load or a scalar load to vector.
4244 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4245 ShuffleVectorSDNode *Op) {
4246 EVT VT = Op->getValueType(0);
4247 if (VT.getSizeInBits() != 128)
4250 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4252 // Is V2 is a vector load, don't do this transformation. We will try to use
4253 // load folding shufps op.
4254 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4257 unsigned NumElems = VT.getVectorNumElements();
4259 if (NumElems != 2 && NumElems != 4)
4261 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4262 if (!isUndefOrEqual(Op->getMaskElt(i), i))
4264 for (unsigned i = NumElems/2; i != NumElems; ++i)
4265 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4270 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4272 static bool isSplatVector(SDNode *N) {
4273 if (N->getOpcode() != ISD::BUILD_VECTOR)
4276 SDValue SplatValue = N->getOperand(0);
4277 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4278 if (N->getOperand(i) != SplatValue)
4283 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4284 /// to an zero vector.
4285 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4286 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4287 SDValue V1 = N->getOperand(0);
4288 SDValue V2 = N->getOperand(1);
4289 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4290 for (unsigned i = 0; i != NumElems; ++i) {
4291 int Idx = N->getMaskElt(i);
4292 if (Idx >= (int)NumElems) {
4293 unsigned Opc = V2.getOpcode();
4294 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4296 if (Opc != ISD::BUILD_VECTOR ||
4297 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4299 } else if (Idx >= 0) {
4300 unsigned Opc = V1.getOpcode();
4301 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4303 if (Opc != ISD::BUILD_VECTOR ||
4304 !X86::isZeroNode(V1.getOperand(Idx)))
4311 /// getZeroVector - Returns a vector of specified type with all zero elements.
4313 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4315 assert(VT.isVector() && "Expected a vector type");
4317 // Always build SSE zero vectors as <4 x i32> bitcasted
4318 // to their dest type. This ensures they get CSE'd.
4320 if (VT.getSizeInBits() == 128) { // SSE
4321 if (HasXMMInt) { // SSE2
4322 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4323 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4325 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4326 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4328 } else if (VT.getSizeInBits() == 256) { // AVX
4329 // 256-bit logic and arithmetic instructions in AVX are
4330 // all floating-point, no support for integer ops. Default
4331 // to emitting fp zeroed vectors then.
4332 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4333 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4334 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4336 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4339 /// getOnesVector - Returns a vector of specified type with all bits set.
4340 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4341 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4342 /// Then bitcast to their original type, ensuring they get CSE'd.
4343 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4345 assert(VT.isVector() && "Expected a vector type");
4346 assert((VT.is128BitVector() || VT.is256BitVector())
4347 && "Expected a 128-bit or 256-bit vector type");
4349 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4351 if (VT.getSizeInBits() == 256) {
4352 if (HasAVX2) { // AVX2
4353 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4354 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4356 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4357 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4358 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4359 Vec = Insert128BitVector(InsV, Vec,
4360 DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4363 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4366 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4369 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4370 /// that point to V2 points to its first element.
4371 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4372 EVT VT = SVOp->getValueType(0);
4373 unsigned NumElems = VT.getVectorNumElements();
4375 bool Changed = false;
4376 SmallVector<int, 8> MaskVec;
4377 SVOp->getMask(MaskVec);
4379 for (unsigned i = 0; i != NumElems; ++i) {
4380 if (MaskVec[i] > (int)NumElems) {
4381 MaskVec[i] = NumElems;
4386 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4387 SVOp->getOperand(1), &MaskVec[0]);
4388 return SDValue(SVOp, 0);
4391 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4392 /// operation of specified width.
4393 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4395 unsigned NumElems = VT.getVectorNumElements();
4396 SmallVector<int, 8> Mask;
4397 Mask.push_back(NumElems);
4398 for (unsigned i = 1; i != NumElems; ++i)
4400 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4403 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4404 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4406 unsigned NumElems = VT.getVectorNumElements();
4407 SmallVector<int, 8> Mask;
4408 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4410 Mask.push_back(i + NumElems);
4412 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4415 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4416 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4418 unsigned NumElems = VT.getVectorNumElements();
4419 unsigned Half = NumElems/2;
4420 SmallVector<int, 8> Mask;
4421 for (unsigned i = 0; i != Half; ++i) {
4422 Mask.push_back(i + Half);
4423 Mask.push_back(i + NumElems + Half);
4425 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4428 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4429 // a generic shuffle instruction because the target has no such instructions.
4430 // Generate shuffles which repeat i16 and i8 several times until they can be
4431 // represented by v4f32 and then be manipulated by target suported shuffles.
4432 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4433 EVT VT = V.getValueType();
4434 int NumElems = VT.getVectorNumElements();
4435 DebugLoc dl = V.getDebugLoc();
4437 while (NumElems > 4) {
4438 if (EltNo < NumElems/2) {
4439 V = getUnpackl(DAG, dl, VT, V, V);
4441 V = getUnpackh(DAG, dl, VT, V, V);
4442 EltNo -= NumElems/2;
4449 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4450 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4451 EVT VT = V.getValueType();
4452 DebugLoc dl = V.getDebugLoc();
4453 assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4454 && "Vector size not supported");
4456 if (VT.getSizeInBits() == 128) {
4457 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4458 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4459 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4462 // To use VPERMILPS to splat scalars, the second half of indicies must
4463 // refer to the higher part, which is a duplication of the lower one,
4464 // because VPERMILPS can only handle in-lane permutations.
4465 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4466 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4468 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4469 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4473 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4476 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4477 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4478 EVT SrcVT = SV->getValueType(0);
4479 SDValue V1 = SV->getOperand(0);
4480 DebugLoc dl = SV->getDebugLoc();
4482 int EltNo = SV->getSplatIndex();
4483 int NumElems = SrcVT.getVectorNumElements();
4484 unsigned Size = SrcVT.getSizeInBits();
4486 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4487 "Unknown how to promote splat for type");
4489 // Extract the 128-bit part containing the splat element and update
4490 // the splat element index when it refers to the higher register.
4492 unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4493 V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4495 EltNo -= NumElems/2;
4498 // All i16 and i8 vector types can't be used directly by a generic shuffle
4499 // instruction because the target has no such instruction. Generate shuffles
4500 // which repeat i16 and i8 several times until they fit in i32, and then can
4501 // be manipulated by target suported shuffles.
4502 EVT EltVT = SrcVT.getVectorElementType();
4503 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4504 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4506 // Recreate the 256-bit vector and place the same 128-bit vector
4507 // into the low and high part. This is necessary because we want
4508 // to use VPERM* to shuffle the vectors
4510 SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4511 DAG.getConstant(0, MVT::i32), DAG, dl);
4512 V1 = Insert128BitVector(InsV, V1,
4513 DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4516 return getLegalSplat(DAG, V1, EltNo);
4519 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4520 /// vector of zero or undef vector. This produces a shuffle where the low
4521 /// element of V2 is swizzled into the zero/undef vector, landing at element
4522 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4523 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4524 bool isZero, bool HasXMMInt,
4525 SelectionDAG &DAG) {
4526 EVT VT = V2.getValueType();
4528 ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4529 unsigned NumElems = VT.getVectorNumElements();
4530 SmallVector<int, 16> MaskVec;
4531 for (unsigned i = 0; i != NumElems; ++i)
4532 // If this is the insertion idx, put the low elt of V2 here.
4533 MaskVec.push_back(i == Idx ? NumElems : i);
4534 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4537 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4538 /// element of the result of the vector shuffle.
4539 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4542 return SDValue(); // Limit search depth.
4544 SDValue V = SDValue(N, 0);
4545 EVT VT = V.getValueType();
4546 unsigned Opcode = V.getOpcode();
4548 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4549 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4550 Index = SV->getMaskElt(Index);
4553 return DAG.getUNDEF(VT.getVectorElementType());
4555 int NumElems = VT.getVectorNumElements();
4556 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4557 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4560 // Recurse into target specific vector shuffles to find scalars.
4561 if (isTargetShuffle(Opcode)) {
4562 int NumElems = VT.getVectorNumElements();
4563 SmallVector<unsigned, 16> ShuffleMask;
4567 case X86ISD::SHUFPS:
4568 case X86ISD::SHUFPD:
4569 ImmN = N->getOperand(N->getNumOperands()-1);
4570 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4573 case X86ISD::PUNPCKH:
4574 DecodePUNPCKHMask(NumElems, ShuffleMask);
4576 case X86ISD::UNPCKHP:
4577 DecodeUNPCKHPMask(VT, ShuffleMask);
4579 case X86ISD::PUNPCKL:
4580 DecodePUNPCKLMask(VT, ShuffleMask);
4582 case X86ISD::UNPCKLP:
4583 DecodeUNPCKLPMask(VT, ShuffleMask);
4585 case X86ISD::MOVHLPS:
4586 DecodeMOVHLPSMask(NumElems, ShuffleMask);
4588 case X86ISD::MOVLHPS:
4589 DecodeMOVLHPSMask(NumElems, ShuffleMask);
4591 case X86ISD::PSHUFD:
4592 ImmN = N->getOperand(N->getNumOperands()-1);
4593 DecodePSHUFMask(NumElems,
4594 cast<ConstantSDNode>(ImmN)->getZExtValue(),
4597 case X86ISD::PSHUFHW:
4598 ImmN = N->getOperand(N->getNumOperands()-1);
4599 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4602 case X86ISD::PSHUFLW:
4603 ImmN = N->getOperand(N->getNumOperands()-1);
4604 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4608 case X86ISD::MOVSD: {
4609 // The index 0 always comes from the first element of the second source,
4610 // this is why MOVSS and MOVSD are used in the first place. The other
4611 // elements come from the other positions of the first source vector.
4612 unsigned OpNum = (Index == 0) ? 1 : 0;
4613 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4616 case X86ISD::VPERMILPS:
4617 ImmN = N->getOperand(N->getNumOperands()-1);
4618 DecodeVPERMILPSMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4621 case X86ISD::VPERMILPD:
4622 ImmN = N->getOperand(N->getNumOperands()-1);
4623 DecodeVPERMILPDMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4626 case X86ISD::VPERM2F128:
4627 case X86ISD::VPERM2I128:
4628 ImmN = N->getOperand(N->getNumOperands()-1);
4629 DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4632 case X86ISD::MOVDDUP:
4633 case X86ISD::MOVLHPD:
4634 case X86ISD::MOVLPD:
4635 case X86ISD::MOVLPS:
4636 case X86ISD::MOVSHDUP:
4637 case X86ISD::MOVSLDUP:
4638 case X86ISD::PALIGN:
4639 return SDValue(); // Not yet implemented.
4641 assert(0 && "unknown target shuffle node");
4645 Index = ShuffleMask[Index];
4647 return DAG.getUNDEF(VT.getVectorElementType());
4649 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4650 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4654 // Actual nodes that may contain scalar elements
4655 if (Opcode == ISD::BITCAST) {
4656 V = V.getOperand(0);
4657 EVT SrcVT = V.getValueType();
4658 unsigned NumElems = VT.getVectorNumElements();
4660 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4664 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4665 return (Index == 0) ? V.getOperand(0)
4666 : DAG.getUNDEF(VT.getVectorElementType());
4668 if (V.getOpcode() == ISD::BUILD_VECTOR)
4669 return V.getOperand(Index);
4674 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4675 /// shuffle operation which come from a consecutively from a zero. The
4676 /// search can start in two different directions, from left or right.
4678 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4679 bool ZerosFromLeft, SelectionDAG &DAG) {
4682 while (i < NumElems) {
4683 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4684 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4685 if (!(Elt.getNode() &&
4686 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4694 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4695 /// MaskE correspond consecutively to elements from one of the vector operands,
4696 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4698 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4699 int OpIdx, int NumElems, unsigned &OpNum) {
4700 bool SeenV1 = false;
4701 bool SeenV2 = false;
4703 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4704 int Idx = SVOp->getMaskElt(i);
4705 // Ignore undef indicies
4714 // Only accept consecutive elements from the same vector
4715 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4719 OpNum = SeenV1 ? 0 : 1;
4723 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4724 /// logical left shift of a vector.
4725 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4726 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4727 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4728 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4729 false /* check zeros from right */, DAG);
4735 // Considering the elements in the mask that are not consecutive zeros,
4736 // check if they consecutively come from only one of the source vectors.
4738 // V1 = {X, A, B, C} 0
4740 // vector_shuffle V1, V2 <1, 2, 3, X>
4742 if (!isShuffleMaskConsecutive(SVOp,
4743 0, // Mask Start Index
4744 NumElems-NumZeros-1, // Mask End Index
4745 NumZeros, // Where to start looking in the src vector
4746 NumElems, // Number of elements in vector
4747 OpSrc)) // Which source operand ?
4752 ShVal = SVOp->getOperand(OpSrc);
4756 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4757 /// logical left shift of a vector.
4758 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4759 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4760 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4761 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4762 true /* check zeros from left */, DAG);
4768 // Considering the elements in the mask that are not consecutive zeros,
4769 // check if they consecutively come from only one of the source vectors.
4771 // 0 { A, B, X, X } = V2
4773 // vector_shuffle V1, V2 <X, X, 4, 5>
4775 if (!isShuffleMaskConsecutive(SVOp,
4776 NumZeros, // Mask Start Index
4777 NumElems-1, // Mask End Index
4778 0, // Where to start looking in the src vector
4779 NumElems, // Number of elements in vector
4780 OpSrc)) // Which source operand ?
4785 ShVal = SVOp->getOperand(OpSrc);
4789 /// isVectorShift - Returns true if the shuffle can be implemented as a
4790 /// logical left or right shift of a vector.
4791 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4792 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4793 // Although the logic below support any bitwidth size, there are no
4794 // shift instructions which handle more than 128-bit vectors.
4795 if (SVOp->getValueType(0).getSizeInBits() > 128)
4798 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4799 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4805 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4807 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4808 unsigned NumNonZero, unsigned NumZero,
4810 const TargetLowering &TLI) {
4814 DebugLoc dl = Op.getDebugLoc();
4817 for (unsigned i = 0; i < 16; ++i) {
4818 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4819 if (ThisIsNonZero && First) {
4821 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4823 V = DAG.getUNDEF(MVT::v8i16);
4828 SDValue ThisElt(0, 0), LastElt(0, 0);
4829 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4830 if (LastIsNonZero) {
4831 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4832 MVT::i16, Op.getOperand(i-1));
4834 if (ThisIsNonZero) {
4835 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4836 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4837 ThisElt, DAG.getConstant(8, MVT::i8));
4839 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4843 if (ThisElt.getNode())
4844 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4845 DAG.getIntPtrConstant(i/2));
4849 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4852 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4854 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4855 unsigned NumNonZero, unsigned NumZero,
4857 const TargetLowering &TLI) {
4861 DebugLoc dl = Op.getDebugLoc();
4864 for (unsigned i = 0; i < 8; ++i) {
4865 bool isNonZero = (NonZeros & (1 << i)) != 0;
4869 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4871 V = DAG.getUNDEF(MVT::v8i16);
4874 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4875 MVT::v8i16, V, Op.getOperand(i),
4876 DAG.getIntPtrConstant(i));
4883 /// getVShift - Return a vector logical shift node.
4885 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4886 unsigned NumBits, SelectionDAG &DAG,
4887 const TargetLowering &TLI, DebugLoc dl) {
4888 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4889 EVT ShVT = MVT::v2i64;
4890 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4891 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4892 return DAG.getNode(ISD::BITCAST, dl, VT,
4893 DAG.getNode(Opc, dl, ShVT, SrcOp,
4894 DAG.getConstant(NumBits,
4895 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4899 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4900 SelectionDAG &DAG) const {
4902 // Check if the scalar load can be widened into a vector load. And if
4903 // the address is "base + cst" see if the cst can be "absorbed" into
4904 // the shuffle mask.
4905 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4906 SDValue Ptr = LD->getBasePtr();
4907 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4909 EVT PVT = LD->getValueType(0);
4910 if (PVT != MVT::i32 && PVT != MVT::f32)
4915 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4916 FI = FINode->getIndex();
4918 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4919 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4920 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4921 Offset = Ptr.getConstantOperandVal(1);
4922 Ptr = Ptr.getOperand(0);
4927 // FIXME: 256-bit vector instructions don't require a strict alignment,
4928 // improve this code to support it better.
4929 unsigned RequiredAlign = VT.getSizeInBits()/8;
4930 SDValue Chain = LD->getChain();
4931 // Make sure the stack object alignment is at least 16 or 32.
4932 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4933 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4934 if (MFI->isFixedObjectIndex(FI)) {
4935 // Can't change the alignment. FIXME: It's possible to compute
4936 // the exact stack offset and reference FI + adjust offset instead.
4937 // If someone *really* cares about this. That's the way to implement it.
4940 MFI->setObjectAlignment(FI, RequiredAlign);
4944 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4945 // Ptr + (Offset & ~15).
4948 if ((Offset % RequiredAlign) & 3)
4950 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4952 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4953 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4955 int EltNo = (Offset - StartOffset) >> 2;
4956 int NumElems = VT.getVectorNumElements();
4958 EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4959 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4960 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4961 LD->getPointerInfo().getWithOffset(StartOffset),
4962 false, false, false, 0);
4964 // Canonicalize it to a v4i32 or v8i32 shuffle.
4965 SmallVector<int, 8> Mask;
4966 for (int i = 0; i < NumElems; ++i)
4967 Mask.push_back(EltNo);
4969 V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4970 return DAG.getNode(ISD::BITCAST, dl, NVT,
4971 DAG.getVectorShuffle(CanonVT, dl, V1,
4972 DAG.getUNDEF(CanonVT),&Mask[0]));
4978 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4979 /// vector of type 'VT', see if the elements can be replaced by a single large
4980 /// load which has the same value as a build_vector whose operands are 'elts'.
4982 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4984 /// FIXME: we'd also like to handle the case where the last elements are zero
4985 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4986 /// There's even a handy isZeroNode for that purpose.
4987 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4988 DebugLoc &DL, SelectionDAG &DAG) {
4989 EVT EltVT = VT.getVectorElementType();
4990 unsigned NumElems = Elts.size();
4992 LoadSDNode *LDBase = NULL;
4993 unsigned LastLoadedElt = -1U;
4995 // For each element in the initializer, see if we've found a load or an undef.
4996 // If we don't find an initial load element, or later load elements are
4997 // non-consecutive, bail out.
4998 for (unsigned i = 0; i < NumElems; ++i) {
4999 SDValue Elt = Elts[i];
5001 if (!Elt.getNode() ||
5002 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5005 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5007 LDBase = cast<LoadSDNode>(Elt.getNode());
5011 if (Elt.getOpcode() == ISD::UNDEF)
5014 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5015 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5020 // If we have found an entire vector of loads and undefs, then return a large
5021 // load of the entire vector width starting at the base pointer. If we found
5022 // consecutive loads for the low half, generate a vzext_load node.
5023 if (LastLoadedElt == NumElems - 1) {
5024 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5025 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5026 LDBase->getPointerInfo(),
5027 LDBase->isVolatile(), LDBase->isNonTemporal(),
5028 LDBase->isInvariant(), 0);
5029 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5030 LDBase->getPointerInfo(),
5031 LDBase->isVolatile(), LDBase->isNonTemporal(),
5032 LDBase->isInvariant(), LDBase->getAlignment());
5033 } else if (NumElems == 4 && LastLoadedElt == 1 &&
5034 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5035 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5036 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5038 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5039 LDBase->getPointerInfo(),
5040 LDBase->getAlignment(),
5041 false/*isVolatile*/, true/*ReadMem*/,
5043 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5048 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
5049 /// a vbroadcast node. We support two patterns:
5050 /// 1. A splat BUILD_VECTOR which uses a single scalar load.
5051 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5053 /// The scalar load node is returned when a pattern is found,
5054 /// or SDValue() otherwise.
5055 static SDValue isVectorBroadcast(SDValue &Op, bool hasAVX2) {
5056 EVT VT = Op.getValueType();
5059 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5060 V = V.getOperand(0);
5062 //A suspected load to be broadcasted.
5065 switch (V.getOpcode()) {
5067 // Unknown pattern found.
5070 case ISD::BUILD_VECTOR: {
5071 // The BUILD_VECTOR node must be a splat.
5072 if (!isSplatVector(V.getNode()))
5075 Ld = V.getOperand(0);
5077 // The suspected load node has several users. Make sure that all
5078 // of its users are from the BUILD_VECTOR node.
5079 if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5084 case ISD::VECTOR_SHUFFLE: {
5085 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5087 // Shuffles must have a splat mask where the first element is
5089 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5092 SDValue Sc = Op.getOperand(0);
5093 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
5096 Ld = Sc.getOperand(0);
5098 // The scalar_to_vector node and the suspected
5099 // load node must have exactly one user.
5100 if (!Sc.hasOneUse() || !Ld.hasOneUse())
5106 // The scalar source must be a normal load.
5107 if (!ISD::isNormalLoad(Ld.getNode()))
5110 bool Is256 = VT.getSizeInBits() == 256;
5111 bool Is128 = VT.getSizeInBits() == 128;
5112 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5115 // VBroadcast to YMM
5116 if (Is256 && (ScalarSize == 8 || ScalarSize == 16 ||
5117 ScalarSize == 32 || ScalarSize == 64 ))
5120 // VBroadcast to XMM
5121 if (Is128 && (ScalarSize == 8 || ScalarSize == 32 ||
5122 ScalarSize == 16 || ScalarSize == 64 ))
5126 // VBroadcast to YMM
5127 if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
5130 // VBroadcast to XMM
5131 if (Is128 && (ScalarSize == 32))
5135 // Unsupported broadcast.
5140 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5141 DebugLoc dl = Op.getDebugLoc();
5143 EVT VT = Op.getValueType();
5144 EVT ExtVT = VT.getVectorElementType();
5145 unsigned NumElems = Op.getNumOperands();
5147 // Vectors containing all zeros can be matched by pxor and xorps later
5148 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5149 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5150 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5151 if (Op.getValueType() == MVT::v4i32 ||
5152 Op.getValueType() == MVT::v8i32)
5155 return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5158 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5159 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5160 // vpcmpeqd on 256-bit vectors.
5161 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5162 if (Op.getValueType() == MVT::v4i32 ||
5163 (Op.getValueType() == MVT::v8i32 && Subtarget->hasAVX2()))
5166 return getOnesVector(Op.getValueType(), Subtarget->hasAVX2(), DAG, dl);
5169 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
5170 if (Subtarget->hasAVX() && LD.getNode())
5171 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5173 unsigned EVTBits = ExtVT.getSizeInBits();
5175 unsigned NumZero = 0;
5176 unsigned NumNonZero = 0;
5177 unsigned NonZeros = 0;
5178 bool IsAllConstants = true;
5179 SmallSet<SDValue, 8> Values;
5180 for (unsigned i = 0; i < NumElems; ++i) {
5181 SDValue Elt = Op.getOperand(i);
5182 if (Elt.getOpcode() == ISD::UNDEF)
5185 if (Elt.getOpcode() != ISD::Constant &&
5186 Elt.getOpcode() != ISD::ConstantFP)
5187 IsAllConstants = false;
5188 if (X86::isZeroNode(Elt))
5191 NonZeros |= (1 << i);
5196 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5197 if (NumNonZero == 0)
5198 return DAG.getUNDEF(VT);
5200 // Special case for single non-zero, non-undef, element.
5201 if (NumNonZero == 1) {
5202 unsigned Idx = CountTrailingZeros_32(NonZeros);
5203 SDValue Item = Op.getOperand(Idx);
5205 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5206 // the value are obviously zero, truncate the value to i32 and do the
5207 // insertion that way. Only do this if the value is non-constant or if the
5208 // value is a constant being inserted into element 0. It is cheaper to do
5209 // a constant pool load than it is to do a movd + shuffle.
5210 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5211 (!IsAllConstants || Idx == 0)) {
5212 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5214 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5215 EVT VecVT = MVT::v4i32;
5216 unsigned VecElts = 4;
5218 // Truncate the value (which may itself be a constant) to i32, and
5219 // convert it to a vector with movd (S2V+shuffle to zero extend).
5220 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5221 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5222 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5223 Subtarget->hasXMMInt(), DAG);
5225 // Now we have our 32-bit value zero extended in the low element of
5226 // a vector. If Idx != 0, swizzle it into place.
5228 SmallVector<int, 4> Mask;
5229 Mask.push_back(Idx);
5230 for (unsigned i = 1; i != VecElts; ++i)
5232 Item = DAG.getVectorShuffle(VecVT, dl, Item,
5233 DAG.getUNDEF(Item.getValueType()),
5236 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5240 // If we have a constant or non-constant insertion into the low element of
5241 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5242 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5243 // depending on what the source datatype is.
5246 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5247 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5248 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5249 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5250 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5251 return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5253 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5254 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5255 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5256 EVT MiddleVT = MVT::v4i32;
5257 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5258 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5259 Subtarget->hasXMMInt(), DAG);
5260 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5264 // Is it a vector logical left shift?
5265 if (NumElems == 2 && Idx == 1 &&
5266 X86::isZeroNode(Op.getOperand(0)) &&
5267 !X86::isZeroNode(Op.getOperand(1))) {
5268 unsigned NumBits = VT.getSizeInBits();
5269 return getVShift(true, VT,
5270 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5271 VT, Op.getOperand(1)),
5272 NumBits/2, DAG, *this, dl);
5275 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5278 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5279 // is a non-constant being inserted into an element other than the low one,
5280 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5281 // movd/movss) to move this into the low element, then shuffle it into
5283 if (EVTBits == 32) {
5284 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5286 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5287 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5288 Subtarget->hasXMMInt(), DAG);
5289 SmallVector<int, 8> MaskVec;
5290 for (unsigned i = 0; i < NumElems; i++)
5291 MaskVec.push_back(i == Idx ? 0 : 1);
5292 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5296 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5297 if (Values.size() == 1) {
5298 if (EVTBits == 32) {
5299 // Instead of a shuffle like this:
5300 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5301 // Check if it's possible to issue this instead.
5302 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5303 unsigned Idx = CountTrailingZeros_32(NonZeros);
5304 SDValue Item = Op.getOperand(Idx);
5305 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5306 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5311 // A vector full of immediates; various special cases are already
5312 // handled, so this is best done with a single constant-pool load.
5316 // For AVX-length vectors, build the individual 128-bit pieces and use
5317 // shuffles to put them in place.
5318 if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5319 SmallVector<SDValue, 32> V;
5320 for (unsigned i = 0; i < NumElems; ++i)
5321 V.push_back(Op.getOperand(i));
5323 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5325 // Build both the lower and upper subvector.
5326 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5327 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5330 // Recreate the wider vector with the lower and upper part.
5331 SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5332 DAG.getConstant(0, MVT::i32), DAG, dl);
5333 return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5337 // Let legalizer expand 2-wide build_vectors.
5338 if (EVTBits == 64) {
5339 if (NumNonZero == 1) {
5340 // One half is zero or undef.
5341 unsigned Idx = CountTrailingZeros_32(NonZeros);
5342 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5343 Op.getOperand(Idx));
5344 return getShuffleVectorZeroOrUndef(V2, Idx, true,
5345 Subtarget->hasXMMInt(), DAG);
5350 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5351 if (EVTBits == 8 && NumElems == 16) {
5352 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5354 if (V.getNode()) return V;
5357 if (EVTBits == 16 && NumElems == 8) {
5358 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5360 if (V.getNode()) return V;
5363 // If element VT is == 32 bits, turn it into a number of shuffles.
5364 SmallVector<SDValue, 8> V;
5366 if (NumElems == 4 && NumZero > 0) {
5367 for (unsigned i = 0; i < 4; ++i) {
5368 bool isZero = !(NonZeros & (1 << i));
5370 V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5372 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5375 for (unsigned i = 0; i < 2; ++i) {
5376 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5379 V[i] = V[i*2]; // Must be a zero vector.
5382 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5385 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5388 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5393 SmallVector<int, 8> MaskVec;
5394 bool Reverse = (NonZeros & 0x3) == 2;
5395 for (unsigned i = 0; i < 2; ++i)
5396 MaskVec.push_back(Reverse ? 1-i : i);
5397 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5398 for (unsigned i = 0; i < 2; ++i)
5399 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5400 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5403 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5404 // Check for a build vector of consecutive loads.
5405 for (unsigned i = 0; i < NumElems; ++i)
5406 V[i] = Op.getOperand(i);
5408 // Check for elements which are consecutive loads.
5409 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5413 // For SSE 4.1, use insertps to put the high elements into the low element.
5414 if (getSubtarget()->hasSSE41orAVX()) {
5416 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5417 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5419 Result = DAG.getUNDEF(VT);
5421 for (unsigned i = 1; i < NumElems; ++i) {
5422 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5423 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5424 Op.getOperand(i), DAG.getIntPtrConstant(i));
5429 // Otherwise, expand into a number of unpckl*, start by extending each of
5430 // our (non-undef) elements to the full vector width with the element in the
5431 // bottom slot of the vector (which generates no code for SSE).
5432 for (unsigned i = 0; i < NumElems; ++i) {
5433 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5434 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5436 V[i] = DAG.getUNDEF(VT);
5439 // Next, we iteratively mix elements, e.g. for v4f32:
5440 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5441 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5442 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5443 unsigned EltStride = NumElems >> 1;
5444 while (EltStride != 0) {
5445 for (unsigned i = 0; i < EltStride; ++i) {
5446 // If V[i+EltStride] is undef and this is the first round of mixing,
5447 // then it is safe to just drop this shuffle: V[i] is already in the
5448 // right place, the one element (since it's the first round) being
5449 // inserted as undef can be dropped. This isn't safe for successive
5450 // rounds because they will permute elements within both vectors.
5451 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5452 EltStride == NumElems/2)
5455 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5464 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5465 // them in a MMX register. This is better than doing a stack convert.
5466 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5467 DebugLoc dl = Op.getDebugLoc();
5468 EVT ResVT = Op.getValueType();
5470 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5471 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5473 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5474 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5475 InVec = Op.getOperand(1);
5476 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5477 unsigned NumElts = ResVT.getVectorNumElements();
5478 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5479 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5480 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5482 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5483 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5484 Mask[0] = 0; Mask[1] = 2;
5485 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5487 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5490 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5491 // to create 256-bit vectors from two other 128-bit ones.
5492 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5493 DebugLoc dl = Op.getDebugLoc();
5494 EVT ResVT = Op.getValueType();
5496 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5498 SDValue V1 = Op.getOperand(0);
5499 SDValue V2 = Op.getOperand(1);
5500 unsigned NumElems = ResVT.getVectorNumElements();
5502 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5503 DAG.getConstant(0, MVT::i32), DAG, dl);
5504 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5509 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5510 EVT ResVT = Op.getValueType();
5512 assert(Op.getNumOperands() == 2);
5513 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5514 "Unsupported CONCAT_VECTORS for value type");
5516 // We support concatenate two MMX registers and place them in a MMX register.
5517 // This is better than doing a stack convert.
5518 if (ResVT.is128BitVector())
5519 return LowerMMXCONCAT_VECTORS(Op, DAG);
5521 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5522 // from two other 128-bit ones.
5523 return LowerAVXCONCAT_VECTORS(Op, DAG);
5526 // v8i16 shuffles - Prefer shuffles in the following order:
5527 // 1. [all] pshuflw, pshufhw, optional move
5528 // 2. [ssse3] 1 x pshufb
5529 // 3. [ssse3] 2 x pshufb + 1 x por
5530 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5532 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5533 SelectionDAG &DAG) const {
5534 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5535 SDValue V1 = SVOp->getOperand(0);
5536 SDValue V2 = SVOp->getOperand(1);
5537 DebugLoc dl = SVOp->getDebugLoc();
5538 SmallVector<int, 8> MaskVals;
5540 // Determine if more than 1 of the words in each of the low and high quadwords
5541 // of the result come from the same quadword of one of the two inputs. Undef
5542 // mask values count as coming from any quadword, for better codegen.
5543 unsigned LoQuad[] = { 0, 0, 0, 0 };
5544 unsigned HiQuad[] = { 0, 0, 0, 0 };
5545 BitVector InputQuads(4);
5546 for (unsigned i = 0; i < 8; ++i) {
5547 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5548 int EltIdx = SVOp->getMaskElt(i);
5549 MaskVals.push_back(EltIdx);
5558 InputQuads.set(EltIdx / 4);
5561 int BestLoQuad = -1;
5562 unsigned MaxQuad = 1;
5563 for (unsigned i = 0; i < 4; ++i) {
5564 if (LoQuad[i] > MaxQuad) {
5566 MaxQuad = LoQuad[i];
5570 int BestHiQuad = -1;
5572 for (unsigned i = 0; i < 4; ++i) {
5573 if (HiQuad[i] > MaxQuad) {
5575 MaxQuad = HiQuad[i];
5579 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5580 // of the two input vectors, shuffle them into one input vector so only a
5581 // single pshufb instruction is necessary. If There are more than 2 input
5582 // quads, disable the next transformation since it does not help SSSE3.
5583 bool V1Used = InputQuads[0] || InputQuads[1];
5584 bool V2Used = InputQuads[2] || InputQuads[3];
5585 if (Subtarget->hasSSSE3orAVX()) {
5586 if (InputQuads.count() == 2 && V1Used && V2Used) {
5587 BestLoQuad = InputQuads.find_first();
5588 BestHiQuad = InputQuads.find_next(BestLoQuad);
5590 if (InputQuads.count() > 2) {
5596 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5597 // the shuffle mask. If a quad is scored as -1, that means that it contains
5598 // words from all 4 input quadwords.
5600 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5601 SmallVector<int, 8> MaskV;
5602 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5603 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5604 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5605 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5606 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5607 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5609 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5610 // source words for the shuffle, to aid later transformations.
5611 bool AllWordsInNewV = true;
5612 bool InOrder[2] = { true, true };
5613 for (unsigned i = 0; i != 8; ++i) {
5614 int idx = MaskVals[i];
5616 InOrder[i/4] = false;
5617 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5619 AllWordsInNewV = false;
5623 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5624 if (AllWordsInNewV) {
5625 for (int i = 0; i != 8; ++i) {
5626 int idx = MaskVals[i];
5629 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5630 if ((idx != i) && idx < 4)
5632 if ((idx != i) && idx > 3)
5641 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5642 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5643 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5644 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5645 unsigned TargetMask = 0;
5646 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5647 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5648 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5649 X86::getShufflePSHUFLWImmediate(NewV.getNode());
5650 V1 = NewV.getOperand(0);
5651 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5655 // If we have SSSE3, and all words of the result are from 1 input vector,
5656 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5657 // is present, fall back to case 4.
5658 if (Subtarget->hasSSSE3orAVX()) {
5659 SmallVector<SDValue,16> pshufbMask;
5661 // If we have elements from both input vectors, set the high bit of the
5662 // shuffle mask element to zero out elements that come from V2 in the V1
5663 // mask, and elements that come from V1 in the V2 mask, so that the two
5664 // results can be OR'd together.
5665 bool TwoInputs = V1Used && V2Used;
5666 for (unsigned i = 0; i != 8; ++i) {
5667 int EltIdx = MaskVals[i] * 2;
5668 if (TwoInputs && (EltIdx >= 16)) {
5669 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5670 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5673 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5674 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5676 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5677 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5678 DAG.getNode(ISD::BUILD_VECTOR, dl,
5679 MVT::v16i8, &pshufbMask[0], 16));
5681 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5683 // Calculate the shuffle mask for the second input, shuffle it, and
5684 // OR it with the first shuffled input.
5686 for (unsigned i = 0; i != 8; ++i) {
5687 int EltIdx = MaskVals[i] * 2;
5689 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5690 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5693 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5694 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5696 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5697 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5698 DAG.getNode(ISD::BUILD_VECTOR, dl,
5699 MVT::v16i8, &pshufbMask[0], 16));
5700 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5701 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5704 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5705 // and update MaskVals with new element order.
5706 BitVector InOrder(8);
5707 if (BestLoQuad >= 0) {
5708 SmallVector<int, 8> MaskV;
5709 for (int i = 0; i != 4; ++i) {
5710 int idx = MaskVals[i];
5712 MaskV.push_back(-1);
5714 } else if ((idx / 4) == BestLoQuad) {
5715 MaskV.push_back(idx & 3);
5718 MaskV.push_back(-1);
5721 for (unsigned i = 4; i != 8; ++i)
5723 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5726 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5727 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5729 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5733 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5734 // and update MaskVals with the new element order.
5735 if (BestHiQuad >= 0) {
5736 SmallVector<int, 8> MaskV;
5737 for (unsigned i = 0; i != 4; ++i)
5739 for (unsigned i = 4; i != 8; ++i) {
5740 int idx = MaskVals[i];
5742 MaskV.push_back(-1);
5744 } else if ((idx / 4) == BestHiQuad) {
5745 MaskV.push_back((idx & 3) + 4);
5748 MaskV.push_back(-1);
5751 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5754 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3orAVX())
5755 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5757 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5761 // In case BestHi & BestLo were both -1, which means each quadword has a word
5762 // from each of the four input quadwords, calculate the InOrder bitvector now
5763 // before falling through to the insert/extract cleanup.
5764 if (BestLoQuad == -1 && BestHiQuad == -1) {
5766 for (int i = 0; i != 8; ++i)
5767 if (MaskVals[i] < 0 || MaskVals[i] == i)
5771 // The other elements are put in the right place using pextrw and pinsrw.
5772 for (unsigned i = 0; i != 8; ++i) {
5775 int EltIdx = MaskVals[i];
5778 SDValue ExtOp = (EltIdx < 8)
5779 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5780 DAG.getIntPtrConstant(EltIdx))
5781 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5782 DAG.getIntPtrConstant(EltIdx - 8));
5783 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5784 DAG.getIntPtrConstant(i));
5789 // v16i8 shuffles - Prefer shuffles in the following order:
5790 // 1. [ssse3] 1 x pshufb
5791 // 2. [ssse3] 2 x pshufb + 1 x por
5792 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5794 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5796 const X86TargetLowering &TLI) {
5797 SDValue V1 = SVOp->getOperand(0);
5798 SDValue V2 = SVOp->getOperand(1);
5799 DebugLoc dl = SVOp->getDebugLoc();
5800 SmallVector<int, 16> MaskVals;
5801 SVOp->getMask(MaskVals);
5803 // If we have SSSE3, case 1 is generated when all result bytes come from
5804 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5805 // present, fall back to case 3.
5806 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5809 for (unsigned i = 0; i < 16; ++i) {
5810 int EltIdx = MaskVals[i];
5819 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5820 if (TLI.getSubtarget()->hasSSSE3orAVX()) {
5821 SmallVector<SDValue,16> pshufbMask;
5823 // If all result elements are from one input vector, then only translate
5824 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5826 // Otherwise, we have elements from both input vectors, and must zero out
5827 // elements that come from V2 in the first mask, and V1 in the second mask
5828 // so that we can OR them together.
5829 bool TwoInputs = !(V1Only || V2Only);
5830 for (unsigned i = 0; i != 16; ++i) {
5831 int EltIdx = MaskVals[i];
5832 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5833 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5836 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5838 // If all the elements are from V2, assign it to V1 and return after
5839 // building the first pshufb.
5842 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5843 DAG.getNode(ISD::BUILD_VECTOR, dl,
5844 MVT::v16i8, &pshufbMask[0], 16));
5848 // Calculate the shuffle mask for the second input, shuffle it, and
5849 // OR it with the first shuffled input.
5851 for (unsigned i = 0; i != 16; ++i) {
5852 int EltIdx = MaskVals[i];
5854 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5857 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5859 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5860 DAG.getNode(ISD::BUILD_VECTOR, dl,
5861 MVT::v16i8, &pshufbMask[0], 16));
5862 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5865 // No SSSE3 - Calculate in place words and then fix all out of place words
5866 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5867 // the 16 different words that comprise the two doublequadword input vectors.
5868 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5869 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5870 SDValue NewV = V2Only ? V2 : V1;
5871 for (int i = 0; i != 8; ++i) {
5872 int Elt0 = MaskVals[i*2];
5873 int Elt1 = MaskVals[i*2+1];
5875 // This word of the result is all undef, skip it.
5876 if (Elt0 < 0 && Elt1 < 0)
5879 // This word of the result is already in the correct place, skip it.
5880 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5882 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5885 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5886 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5889 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5890 // using a single extract together, load it and store it.
5891 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5892 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5893 DAG.getIntPtrConstant(Elt1 / 2));
5894 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5895 DAG.getIntPtrConstant(i));
5899 // If Elt1 is defined, extract it from the appropriate source. If the
5900 // source byte is not also odd, shift the extracted word left 8 bits
5901 // otherwise clear the bottom 8 bits if we need to do an or.
5903 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5904 DAG.getIntPtrConstant(Elt1 / 2));
5905 if ((Elt1 & 1) == 0)
5906 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5908 TLI.getShiftAmountTy(InsElt.getValueType())));
5910 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5911 DAG.getConstant(0xFF00, MVT::i16));
5913 // If Elt0 is defined, extract it from the appropriate source. If the
5914 // source byte is not also even, shift the extracted word right 8 bits. If
5915 // Elt1 was also defined, OR the extracted values together before
5916 // inserting them in the result.
5918 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5919 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5920 if ((Elt0 & 1) != 0)
5921 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5923 TLI.getShiftAmountTy(InsElt0.getValueType())));
5925 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5926 DAG.getConstant(0x00FF, MVT::i16));
5927 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5930 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5931 DAG.getIntPtrConstant(i));
5933 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5936 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5937 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5938 /// done when every pair / quad of shuffle mask elements point to elements in
5939 /// the right sequence. e.g.
5940 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5942 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5943 SelectionDAG &DAG, DebugLoc dl) {
5944 EVT VT = SVOp->getValueType(0);
5945 SDValue V1 = SVOp->getOperand(0);
5946 SDValue V2 = SVOp->getOperand(1);
5947 unsigned NumElems = VT.getVectorNumElements();
5948 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5950 switch (VT.getSimpleVT().SimpleTy) {
5951 default: assert(false && "Unexpected!");
5952 case MVT::v4f32: NewVT = MVT::v2f64; break;
5953 case MVT::v4i32: NewVT = MVT::v2i64; break;
5954 case MVT::v8i16: NewVT = MVT::v4i32; break;
5955 case MVT::v16i8: NewVT = MVT::v4i32; break;
5958 int Scale = NumElems / NewWidth;
5959 SmallVector<int, 8> MaskVec;
5960 for (unsigned i = 0; i < NumElems; i += Scale) {
5962 for (int j = 0; j < Scale; ++j) {
5963 int EltIdx = SVOp->getMaskElt(i+j);
5967 StartIdx = EltIdx - (EltIdx % Scale);
5968 if (EltIdx != StartIdx + j)
5972 MaskVec.push_back(-1);
5974 MaskVec.push_back(StartIdx / Scale);
5977 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5978 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5979 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5982 /// getVZextMovL - Return a zero-extending vector move low node.
5984 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5985 SDValue SrcOp, SelectionDAG &DAG,
5986 const X86Subtarget *Subtarget, DebugLoc dl) {
5987 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5988 LoadSDNode *LD = NULL;
5989 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5990 LD = dyn_cast<LoadSDNode>(SrcOp);
5992 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5994 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5995 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5996 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5997 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5998 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6000 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6001 return DAG.getNode(ISD::BITCAST, dl, VT,
6002 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6003 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6011 return DAG.getNode(ISD::BITCAST, dl, VT,
6012 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6013 DAG.getNode(ISD::BITCAST, dl,
6017 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
6018 /// shuffle node referes to only one lane in the sources.
6019 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
6020 EVT VT = SVOp->getValueType(0);
6021 int NumElems = VT.getVectorNumElements();
6022 int HalfSize = NumElems/2;
6023 SmallVector<int, 16> M;
6025 bool MatchA = false, MatchB = false;
6027 for (int l = 0; l < NumElems*2; l += HalfSize) {
6028 if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
6034 for (int l = 0; l < NumElems*2; l += HalfSize) {
6035 if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
6041 return MatchA && MatchB;
6044 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6045 /// which could not be matched by any known target speficic shuffle
6047 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6048 if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
6049 // If each half of a vector shuffle node referes to only one lane in the
6050 // source vectors, extract each used 128-bit lane and shuffle them using
6051 // 128-bit shuffles. Then, concatenate the results. Otherwise leave
6052 // the work to the legalizer.
6053 DebugLoc dl = SVOp->getDebugLoc();
6054 EVT VT = SVOp->getValueType(0);
6055 int NumElems = VT.getVectorNumElements();
6056 int HalfSize = NumElems/2;
6058 // Extract the reference for each half
6059 int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
6060 int FstVecOpNum = 0, SndVecOpNum = 0;
6061 for (int i = 0; i < HalfSize; ++i) {
6062 int Elt = SVOp->getMaskElt(i);
6063 if (SVOp->getMaskElt(i) < 0)
6065 FstVecOpNum = Elt/NumElems;
6066 FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6069 for (int i = HalfSize; i < NumElems; ++i) {
6070 int Elt = SVOp->getMaskElt(i);
6071 if (SVOp->getMaskElt(i) < 0)
6073 SndVecOpNum = Elt/NumElems;
6074 SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6078 // Extract the subvectors
6079 SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
6080 DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
6081 SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
6082 DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
6084 // Generate 128-bit shuffles
6085 SmallVector<int, 16> MaskV1, MaskV2;
6086 for (int i = 0; i < HalfSize; ++i) {
6087 int Elt = SVOp->getMaskElt(i);
6088 MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6090 for (int i = HalfSize; i < NumElems; ++i) {
6091 int Elt = SVOp->getMaskElt(i);
6092 MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6095 EVT NVT = V1.getValueType();
6096 V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
6097 V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
6099 // Concatenate the result back
6100 SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6101 DAG.getConstant(0, MVT::i32), DAG, dl);
6102 return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6109 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6110 /// 4 elements, and match them with several different shuffle types.
6112 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6113 SDValue V1 = SVOp->getOperand(0);
6114 SDValue V2 = SVOp->getOperand(1);
6115 DebugLoc dl = SVOp->getDebugLoc();
6116 EVT VT = SVOp->getValueType(0);
6118 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6120 SmallVector<std::pair<int, int>, 8> Locs;
6122 SmallVector<int, 8> Mask1(4U, -1);
6123 SmallVector<int, 8> PermMask;
6124 SVOp->getMask(PermMask);
6128 for (unsigned i = 0; i != 4; ++i) {
6129 int Idx = PermMask[i];
6131 Locs[i] = std::make_pair(-1, -1);
6133 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6135 Locs[i] = std::make_pair(0, NumLo);
6139 Locs[i] = std::make_pair(1, NumHi);
6141 Mask1[2+NumHi] = Idx;
6147 if (NumLo <= 2 && NumHi <= 2) {
6148 // If no more than two elements come from either vector. This can be
6149 // implemented with two shuffles. First shuffle gather the elements.
6150 // The second shuffle, which takes the first shuffle as both of its
6151 // vector operands, put the elements into the right order.
6152 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6154 SmallVector<int, 8> Mask2(4U, -1);
6156 for (unsigned i = 0; i != 4; ++i) {
6157 if (Locs[i].first == -1)
6160 unsigned Idx = (i < 2) ? 0 : 4;
6161 Idx += Locs[i].first * 2 + Locs[i].second;
6166 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6167 } else if (NumLo == 3 || NumHi == 3) {
6168 // Otherwise, we must have three elements from one vector, call it X, and
6169 // one element from the other, call it Y. First, use a shufps to build an
6170 // intermediate vector with the one element from Y and the element from X
6171 // that will be in the same half in the final destination (the indexes don't
6172 // matter). Then, use a shufps to build the final vector, taking the half
6173 // containing the element from Y from the intermediate, and the other half
6176 // Normalize it so the 3 elements come from V1.
6177 CommuteVectorShuffleMask(PermMask, VT);
6181 // Find the element from V2.
6183 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6184 int Val = PermMask[HiIndex];
6191 Mask1[0] = PermMask[HiIndex];
6193 Mask1[2] = PermMask[HiIndex^1];
6195 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6198 Mask1[0] = PermMask[0];
6199 Mask1[1] = PermMask[1];
6200 Mask1[2] = HiIndex & 1 ? 6 : 4;
6201 Mask1[3] = HiIndex & 1 ? 4 : 6;
6202 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6204 Mask1[0] = HiIndex & 1 ? 2 : 0;
6205 Mask1[1] = HiIndex & 1 ? 0 : 2;
6206 Mask1[2] = PermMask[2];
6207 Mask1[3] = PermMask[3];
6212 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6216 // Break it into (shuffle shuffle_hi, shuffle_lo).
6219 SmallVector<int,8> LoMask(4U, -1);
6220 SmallVector<int,8> HiMask(4U, -1);
6222 SmallVector<int,8> *MaskPtr = &LoMask;
6223 unsigned MaskIdx = 0;
6226 for (unsigned i = 0; i != 4; ++i) {
6233 int Idx = PermMask[i];
6235 Locs[i] = std::make_pair(-1, -1);
6236 } else if (Idx < 4) {
6237 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6238 (*MaskPtr)[LoIdx] = Idx;
6241 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6242 (*MaskPtr)[HiIdx] = Idx;
6247 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6248 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6249 SmallVector<int, 8> MaskOps;
6250 for (unsigned i = 0; i != 4; ++i) {
6251 if (Locs[i].first == -1) {
6252 MaskOps.push_back(-1);
6254 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6255 MaskOps.push_back(Idx);
6258 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6261 static bool MayFoldVectorLoad(SDValue V) {
6262 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6263 V = V.getOperand(0);
6264 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6265 V = V.getOperand(0);
6266 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6267 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6268 // BUILD_VECTOR (load), undef
6269 V = V.getOperand(0);
6275 // FIXME: the version above should always be used. Since there's
6276 // a bug where several vector shuffles can't be folded because the
6277 // DAG is not updated during lowering and a node claims to have two
6278 // uses while it only has one, use this version, and let isel match
6279 // another instruction if the load really happens to have more than
6280 // one use. Remove this version after this bug get fixed.
6281 // rdar://8434668, PR8156
6282 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6283 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6284 V = V.getOperand(0);
6285 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6286 V = V.getOperand(0);
6287 if (ISD::isNormalLoad(V.getNode()))
6292 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6293 /// a vector extract, and if both can be later optimized into a single load.
6294 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6295 /// here because otherwise a target specific shuffle node is going to be
6296 /// emitted for this shuffle, and the optimization not done.
6297 /// FIXME: This is probably not the best approach, but fix the problem
6298 /// until the right path is decided.
6300 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6301 const TargetLowering &TLI) {
6302 EVT VT = V.getValueType();
6303 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6305 // Be sure that the vector shuffle is present in a pattern like this:
6306 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6310 SDNode *N = *V.getNode()->use_begin();
6311 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6314 SDValue EltNo = N->getOperand(1);
6315 if (!isa<ConstantSDNode>(EltNo))
6318 // If the bit convert changed the number of elements, it is unsafe
6319 // to examine the mask.
6320 bool HasShuffleIntoBitcast = false;
6321 if (V.getOpcode() == ISD::BITCAST) {
6322 EVT SrcVT = V.getOperand(0).getValueType();
6323 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6325 V = V.getOperand(0);
6326 HasShuffleIntoBitcast = true;
6329 // Select the input vector, guarding against out of range extract vector.
6330 unsigned NumElems = VT.getVectorNumElements();
6331 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6332 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6333 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6335 // Skip one more bit_convert if necessary
6336 if (V.getOpcode() == ISD::BITCAST)
6337 V = V.getOperand(0);
6339 if (ISD::isNormalLoad(V.getNode())) {
6340 // Is the original load suitable?
6341 LoadSDNode *LN0 = cast<LoadSDNode>(V);
6343 // FIXME: avoid the multi-use bug that is preventing lots of
6344 // of foldings to be detected, this is still wrong of course, but
6345 // give the temporary desired behavior, and if it happens that
6346 // the load has real more uses, during isel it will not fold, and
6347 // will generate poor code.
6348 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6351 if (!HasShuffleIntoBitcast)
6354 // If there's a bitcast before the shuffle, check if the load type and
6355 // alignment is valid.
6356 unsigned Align = LN0->getAlignment();
6358 TLI.getTargetData()->getABITypeAlignment(
6359 VT.getTypeForEVT(*DAG.getContext()));
6361 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6369 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6370 EVT VT = Op.getValueType();
6372 // Canonizalize to v2f64.
6373 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6374 return DAG.getNode(ISD::BITCAST, dl, VT,
6375 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6380 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6382 SDValue V1 = Op.getOperand(0);
6383 SDValue V2 = Op.getOperand(1);
6384 EVT VT = Op.getValueType();
6386 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6388 if (HasXMMInt && VT == MVT::v2f64)
6389 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6391 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6392 return DAG.getNode(ISD::BITCAST, dl, VT,
6393 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6394 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6395 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6399 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6400 SDValue V1 = Op.getOperand(0);
6401 SDValue V2 = Op.getOperand(1);
6402 EVT VT = Op.getValueType();
6404 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6405 "unsupported shuffle type");
6407 if (V2.getOpcode() == ISD::UNDEF)
6411 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6414 static inline unsigned getSHUFPOpcode(EVT VT) {
6415 switch(VT.getSimpleVT().SimpleTy) {
6416 case MVT::v8i32: // Use fp unit for int unpack.
6418 case MVT::v4i32: // Use fp unit for int unpack.
6419 case MVT::v4f32: return X86ISD::SHUFPS;
6420 case MVT::v4i64: // Use fp unit for int unpack.
6422 case MVT::v2i64: // Use fp unit for int unpack.
6423 case MVT::v2f64: return X86ISD::SHUFPD;
6425 llvm_unreachable("Unknown type for shufp*");
6431 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6432 SDValue V1 = Op.getOperand(0);
6433 SDValue V2 = Op.getOperand(1);
6434 EVT VT = Op.getValueType();
6435 unsigned NumElems = VT.getVectorNumElements();
6437 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6438 // operand of these instructions is only memory, so check if there's a
6439 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6441 bool CanFoldLoad = false;
6443 // Trivial case, when V2 comes from a load.
6444 if (MayFoldVectorLoad(V2))
6447 // When V1 is a load, it can be folded later into a store in isel, example:
6448 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6450 // (MOVLPSmr addr:$src1, VR128:$src2)
6451 // So, recognize this potential and also use MOVLPS or MOVLPD
6452 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6455 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6457 if (HasXMMInt && NumElems == 2)
6458 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6461 // If we don't care about the second element, procede to use movss.
6462 if (SVOp->getMaskElt(1) != -1)
6463 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6466 // movl and movlp will both match v2i64, but v2i64 is never matched by
6467 // movl earlier because we make it strict to avoid messing with the movlp load
6468 // folding logic (see the code above getMOVLP call). Match it here then,
6469 // this is horrible, but will stay like this until we move all shuffle
6470 // matching to x86 specific nodes. Note that for the 1st condition all
6471 // types are matched with movsd.
6473 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6474 // as to remove this logic from here, as much as possible
6475 if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6476 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6477 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6480 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6482 // Invert the operand order and use SHUFPS to match it.
6483 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6484 X86::getShuffleSHUFImmediate(SVOp), DAG);
6487 static inline unsigned getUNPCKLOpcode(EVT VT, bool HasAVX2) {
6488 switch(VT.getSimpleVT().SimpleTy) {
6494 case MVT::v2i64: return X86ISD::PUNPCKL;
6497 if (HasAVX2) return X86ISD::PUNPCKL;
6498 // else use fp unit for int unpack.
6502 case MVT::v2f64: return X86ISD::UNPCKLP;
6504 llvm_unreachable("Unknown type for unpckl");
6509 static inline unsigned getUNPCKHOpcode(EVT VT, bool HasAVX2) {
6510 switch(VT.getSimpleVT().SimpleTy) {
6516 case MVT::v2i64: return X86ISD::PUNPCKH;
6519 if (HasAVX2) return X86ISD::PUNPCKH;
6520 // else use fp unit for int unpack.
6524 case MVT::v2f64: return X86ISD::UNPCKHP;
6526 llvm_unreachable("Unknown type for unpckh");
6531 static inline unsigned getVPERMILOpcode(EVT VT) {
6532 switch(VT.getSimpleVT().SimpleTy) {
6536 case MVT::v8f32: return X86ISD::VPERMILPS;
6540 case MVT::v4f64: return X86ISD::VPERMILPD;
6542 llvm_unreachable("Unknown type for vpermil");
6547 static inline unsigned getVPERM2X128Opcode(EVT VT, bool HasAVX2) {
6548 switch(VT.getSimpleVT().SimpleTy) {
6553 if (HasAVX2) return X86ISD::VPERM2I128;
6554 // else use fp unit for int vperm
6556 case MVT::v4f64: return X86ISD::VPERM2F128;
6558 llvm_unreachable("Unknown type for vpermil");
6564 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6565 const TargetLowering &TLI,
6566 const X86Subtarget *Subtarget) {
6567 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6568 EVT VT = Op.getValueType();
6569 DebugLoc dl = Op.getDebugLoc();
6570 SDValue V1 = Op.getOperand(0);
6571 SDValue V2 = Op.getOperand(1);
6573 if (isZeroShuffle(SVOp))
6574 return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6576 // Handle splat operations
6577 if (SVOp->isSplat()) {
6578 unsigned NumElem = VT.getVectorNumElements();
6579 int Size = VT.getSizeInBits();
6580 // Special case, this is the only place now where it's allowed to return
6581 // a vector_shuffle operation without using a target specific node, because
6582 // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6583 // this be moved to DAGCombine instead?
6584 if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6587 // Use vbroadcast whenever the splat comes from a foldable load
6588 SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
6589 if (Subtarget->hasAVX() && LD.getNode())
6590 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6592 // Handle splats by matching through known shuffle masks
6593 if ((Size == 128 && NumElem <= 4) ||
6594 (Size == 256 && NumElem < 8))
6597 // All remaning splats are promoted to target supported vector shuffles.
6598 return PromoteSplat(SVOp, DAG);
6601 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6603 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6604 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6605 if (NewOp.getNode())
6606 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6607 } else if ((VT == MVT::v4i32 ||
6608 (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6609 // FIXME: Figure out a cleaner way to do this.
6610 // Try to make use of movq to zero out the top part.
6611 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6612 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6613 if (NewOp.getNode()) {
6614 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6615 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6616 DAG, Subtarget, dl);
6618 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6619 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6620 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6621 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6622 DAG, Subtarget, dl);
6629 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6630 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6631 SDValue V1 = Op.getOperand(0);
6632 SDValue V2 = Op.getOperand(1);
6633 EVT VT = Op.getValueType();
6634 DebugLoc dl = Op.getDebugLoc();
6635 unsigned NumElems = VT.getVectorNumElements();
6636 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6637 bool V1IsSplat = false;
6638 bool V2IsSplat = false;
6639 bool HasXMMInt = Subtarget->hasXMMInt();
6640 bool HasAVX2 = Subtarget->hasAVX2();
6641 MachineFunction &MF = DAG.getMachineFunction();
6642 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6644 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6646 assert(V1.getOpcode() != ISD::UNDEF && "Op 1 of shuffle should not be undef");
6648 // Vector shuffle lowering takes 3 steps:
6650 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6651 // narrowing and commutation of operands should be handled.
6652 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6654 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6655 // so the shuffle can be broken into other shuffles and the legalizer can
6656 // try the lowering again.
6658 // The general idea is that no vector_shuffle operation should be left to
6659 // be matched during isel, all of them must be converted to a target specific
6662 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6663 // narrowing and commutation of operands should be handled. The actual code
6664 // doesn't include all of those, work in progress...
6665 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6666 if (NewOp.getNode())
6669 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6670 // unpckh_undef). Only use pshufd if speed is more important than size.
6671 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6672 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V1,
6674 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6675 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6678 if (X86::isMOVDDUPMask(SVOp) && Subtarget->hasSSE3orAVX() &&
6679 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6680 return getMOVDDup(Op, dl, V1, DAG);
6682 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6683 return getMOVHighToLow(Op, dl, DAG);
6685 // Use to match splats
6686 if (HasXMMInt && X86::isUNPCKHMask(SVOp, HasAVX2) && V2IsUndef &&
6687 (VT == MVT::v2f64 || VT == MVT::v2i64))
6688 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6691 if (X86::isPSHUFDMask(SVOp)) {
6692 // The actual implementation will match the mask in the if above and then
6693 // during isel it can match several different instructions, not only pshufd
6694 // as its name says, sad but true, emulate the behavior for now...
6695 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6696 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6698 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6700 if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6701 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6703 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6707 // Check if this can be converted into a logical shift.
6708 bool isLeft = false;
6711 bool isShift = HasXMMInt && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6712 if (isShift && ShVal.hasOneUse()) {
6713 // If the shifted value has multiple uses, it may be cheaper to use
6714 // v_set0 + movlhps or movhlps, etc.
6715 EVT EltVT = VT.getVectorElementType();
6716 ShAmt *= EltVT.getSizeInBits();
6717 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6720 if (X86::isMOVLMask(SVOp)) {
6721 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6722 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6723 if (!X86::isMOVLPMask(SVOp)) {
6724 if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6725 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6727 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6728 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6732 // FIXME: fold these into legal mask.
6733 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp, HasAVX2))
6734 return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6736 if (X86::isMOVHLPSMask(SVOp))
6737 return getMOVHighToLow(Op, dl, DAG);
6739 if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6740 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6742 if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6743 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6745 if (X86::isMOVLPMask(SVOp))
6746 return getMOVLP(Op, dl, DAG, HasXMMInt);
6748 if (ShouldXformToMOVHLPS(SVOp) ||
6749 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6750 return CommuteVectorShuffle(SVOp, DAG);
6753 // No better options. Use a vshl / vsrl.
6754 EVT EltVT = VT.getVectorElementType();
6755 ShAmt *= EltVT.getSizeInBits();
6756 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6759 bool Commuted = false;
6760 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6761 // 1,1,1,1 -> v8i16 though.
6762 V1IsSplat = isSplatVector(V1.getNode());
6763 V2IsSplat = isSplatVector(V2.getNode());
6765 // Canonicalize the splat or undef, if present, to be on the RHS.
6766 if (V1IsSplat && !V2IsSplat) {
6767 Op = CommuteVectorShuffle(SVOp, DAG);
6768 SVOp = cast<ShuffleVectorSDNode>(Op);
6769 V1 = SVOp->getOperand(0);
6770 V2 = SVOp->getOperand(1);
6771 std::swap(V1IsSplat, V2IsSplat);
6775 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6776 // Shuffling low element of v1 into undef, just return v1.
6779 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6780 // the instruction selector will not match, so get a canonical MOVL with
6781 // swapped operands to undo the commute.
6782 return getMOVL(DAG, dl, VT, V2, V1);
6785 if (X86::isUNPCKLMask(SVOp, HasAVX2))
6786 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V2,
6789 if (X86::isUNPCKHMask(SVOp, HasAVX2))
6790 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V2,
6794 // Normalize mask so all entries that point to V2 points to its first
6795 // element then try to match unpck{h|l} again. If match, return a
6796 // new vector_shuffle with the corrected mask.
6797 SDValue NewMask = NormalizeMask(SVOp, DAG);
6798 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6799 if (NSVOp != SVOp) {
6800 if (X86::isUNPCKLMask(NSVOp, HasAVX2, true)) {
6802 } else if (X86::isUNPCKHMask(NSVOp, HasAVX2, true)) {
6809 // Commute is back and try unpck* again.
6810 // FIXME: this seems wrong.
6811 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6812 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6814 if (X86::isUNPCKLMask(NewSVOp, HasAVX2))
6815 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V2, V1,
6818 if (X86::isUNPCKHMask(NewSVOp, HasAVX2))
6819 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V2, V1,
6823 // Normalize the node to match x86 shuffle ops if needed
6824 if (!V2IsUndef && (isCommutedSHUFP(SVOp) ||
6825 isCommutedVSHUFPY(SVOp, Subtarget->hasAVX())))
6826 return CommuteVectorShuffle(SVOp, DAG);
6828 // The checks below are all present in isShuffleMaskLegal, but they are
6829 // inlined here right now to enable us to directly emit target specific
6830 // nodes, and remove one by one until they don't return Op anymore.
6831 SmallVector<int, 16> M;
6834 if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()))
6835 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6836 X86::getShufflePALIGNRImmediate(SVOp),
6839 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6840 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6841 if (VT == MVT::v2f64)
6842 return getTargetShuffleNode(X86ISD::UNPCKLP, dl, VT, V1, V1, DAG);
6843 if (VT == MVT::v2i64)
6844 return getTargetShuffleNode(X86ISD::PUNPCKL, dl, VT, V1, V1, DAG);
6847 if (isPSHUFHWMask(M, VT))
6848 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6849 X86::getShufflePSHUFHWImmediate(SVOp),
6852 if (isPSHUFLWMask(M, VT))
6853 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6854 X86::getShufflePSHUFLWImmediate(SVOp),
6857 if (isSHUFPMask(M, VT))
6858 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6859 X86::getShuffleSHUFImmediate(SVOp), DAG);
6861 if (X86::isUNPCKL_v_undef_Mask(SVOp))
6862 return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V1,
6864 if (X86::isUNPCKH_v_undef_Mask(SVOp))
6865 return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6868 //===--------------------------------------------------------------------===//
6869 // Generate target specific nodes for 128 or 256-bit shuffles only
6870 // supported in the AVX instruction set.
6873 // Handle VMOVDDUPY permutations
6874 if (isMOVDDUPYMask(SVOp, Subtarget))
6875 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6877 // Handle VPERMILPS/D* permutations
6878 if (isVPERMILPMask(M, VT, Subtarget->hasAVX()))
6879 return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6880 getShuffleVPERMILPImmediate(SVOp), DAG);
6882 // Handle VPERM2F128/VPERM2I128 permutations
6883 if (isVPERM2X128Mask(M, VT, Subtarget->hasAVX()))
6884 return getTargetShuffleNode(getVPERM2X128Opcode(VT, HasAVX2), dl, VT, V1,
6885 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6887 // Handle VSHUFPS/DY permutations
6888 if (isVSHUFPYMask(M, VT, Subtarget->hasAVX()))
6889 return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6890 getShuffleVSHUFPYImmediate(SVOp), DAG);
6892 //===--------------------------------------------------------------------===//
6893 // Since no target specific shuffle was selected for this generic one,
6894 // lower it into other known shuffles. FIXME: this isn't true yet, but
6895 // this is the plan.
6898 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6899 if (VT == MVT::v8i16) {
6900 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6901 if (NewOp.getNode())
6905 if (VT == MVT::v16i8) {
6906 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6907 if (NewOp.getNode())
6911 // Handle all 128-bit wide vectors with 4 elements, and match them with
6912 // several different shuffle types.
6913 if (NumElems == 4 && VT.getSizeInBits() == 128)
6914 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6916 // Handle general 256-bit shuffles
6917 if (VT.is256BitVector())
6918 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6924 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6925 SelectionDAG &DAG) const {
6926 EVT VT = Op.getValueType();
6927 DebugLoc dl = Op.getDebugLoc();
6929 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6932 if (VT.getSizeInBits() == 8) {
6933 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6934 Op.getOperand(0), Op.getOperand(1));
6935 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6936 DAG.getValueType(VT));
6937 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6938 } else if (VT.getSizeInBits() == 16) {
6939 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6940 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6942 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6943 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6944 DAG.getNode(ISD::BITCAST, dl,
6948 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6949 Op.getOperand(0), Op.getOperand(1));
6950 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6951 DAG.getValueType(VT));
6952 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6953 } else if (VT == MVT::f32) {
6954 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6955 // the result back to FR32 register. It's only worth matching if the
6956 // result has a single use which is a store or a bitcast to i32. And in
6957 // the case of a store, it's not worth it if the index is a constant 0,
6958 // because a MOVSSmr can be used instead, which is smaller and faster.
6959 if (!Op.hasOneUse())
6961 SDNode *User = *Op.getNode()->use_begin();
6962 if ((User->getOpcode() != ISD::STORE ||
6963 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6964 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6965 (User->getOpcode() != ISD::BITCAST ||
6966 User->getValueType(0) != MVT::i32))
6968 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6969 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6972 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6973 } else if (VT == MVT::i32 || VT == MVT::i64) {
6974 // ExtractPS/pextrq works with constant index.
6975 if (isa<ConstantSDNode>(Op.getOperand(1)))
6983 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6984 SelectionDAG &DAG) const {
6985 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6988 SDValue Vec = Op.getOperand(0);
6989 EVT VecVT = Vec.getValueType();
6991 // If this is a 256-bit vector result, first extract the 128-bit vector and
6992 // then extract the element from the 128-bit vector.
6993 if (VecVT.getSizeInBits() == 256) {
6994 DebugLoc dl = Op.getNode()->getDebugLoc();
6995 unsigned NumElems = VecVT.getVectorNumElements();
6996 SDValue Idx = Op.getOperand(1);
6997 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6999 // Get the 128-bit vector.
7000 bool Upper = IdxVal >= NumElems/2;
7001 Vec = Extract128BitVector(Vec,
7002 DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
7004 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7005 Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
7008 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
7010 if (Subtarget->hasSSE41orAVX()) {
7011 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7016 EVT VT = Op.getValueType();
7017 DebugLoc dl = Op.getDebugLoc();
7018 // TODO: handle v16i8.
7019 if (VT.getSizeInBits() == 16) {
7020 SDValue Vec = Op.getOperand(0);
7021 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7023 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7024 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7025 DAG.getNode(ISD::BITCAST, dl,
7028 // Transform it so it match pextrw which produces a 32-bit result.
7029 EVT EltVT = MVT::i32;
7030 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7031 Op.getOperand(0), Op.getOperand(1));
7032 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7033 DAG.getValueType(VT));
7034 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7035 } else if (VT.getSizeInBits() == 32) {
7036 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7040 // SHUFPS the element to the lowest double word, then movss.
7041 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7042 EVT VVT = Op.getOperand(0).getValueType();
7043 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7044 DAG.getUNDEF(VVT), Mask);
7045 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7046 DAG.getIntPtrConstant(0));
7047 } else if (VT.getSizeInBits() == 64) {
7048 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7049 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7050 // to match extract_elt for f64.
7051 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7055 // UNPCKHPD the element to the lowest double word, then movsd.
7056 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7057 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7058 int Mask[2] = { 1, -1 };
7059 EVT VVT = Op.getOperand(0).getValueType();
7060 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7061 DAG.getUNDEF(VVT), Mask);
7062 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7063 DAG.getIntPtrConstant(0));
7070 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7071 SelectionDAG &DAG) const {
7072 EVT VT = Op.getValueType();
7073 EVT EltVT = VT.getVectorElementType();
7074 DebugLoc dl = Op.getDebugLoc();
7076 SDValue N0 = Op.getOperand(0);
7077 SDValue N1 = Op.getOperand(1);
7078 SDValue N2 = Op.getOperand(2);
7080 if (VT.getSizeInBits() == 256)
7083 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7084 isa<ConstantSDNode>(N2)) {
7086 if (VT == MVT::v8i16)
7087 Opc = X86ISD::PINSRW;
7088 else if (VT == MVT::v16i8)
7089 Opc = X86ISD::PINSRB;
7091 Opc = X86ISD::PINSRB;
7093 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7095 if (N1.getValueType() != MVT::i32)
7096 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7097 if (N2.getValueType() != MVT::i32)
7098 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7099 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7100 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7101 // Bits [7:6] of the constant are the source select. This will always be
7102 // zero here. The DAG Combiner may combine an extract_elt index into these
7103 // bits. For example (insert (extract, 3), 2) could be matched by putting
7104 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7105 // Bits [5:4] of the constant are the destination select. This is the
7106 // value of the incoming immediate.
7107 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7108 // combine either bitwise AND or insert of float 0.0 to set these bits.
7109 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7110 // Create this as a scalar to vector..
7111 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7112 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7113 } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) &&
7114 isa<ConstantSDNode>(N2)) {
7115 // PINSR* works with constant index.
7122 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7123 EVT VT = Op.getValueType();
7124 EVT EltVT = VT.getVectorElementType();
7126 DebugLoc dl = Op.getDebugLoc();
7127 SDValue N0 = Op.getOperand(0);
7128 SDValue N1 = Op.getOperand(1);
7129 SDValue N2 = Op.getOperand(2);
7131 // If this is a 256-bit vector result, first extract the 128-bit vector,
7132 // insert the element into the extracted half and then place it back.
7133 if (VT.getSizeInBits() == 256) {
7134 if (!isa<ConstantSDNode>(N2))
7137 // Get the desired 128-bit vector half.
7138 unsigned NumElems = VT.getVectorNumElements();
7139 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7140 bool Upper = IdxVal >= NumElems/2;
7141 SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7142 SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7144 // Insert the element into the desired half.
7145 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7146 N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7148 // Insert the changed part back to the 256-bit vector
7149 return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7152 if (Subtarget->hasSSE41orAVX())
7153 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7155 if (EltVT == MVT::i8)
7158 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7159 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7160 // as its second argument.
7161 if (N1.getValueType() != MVT::i32)
7162 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7163 if (N2.getValueType() != MVT::i32)
7164 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7165 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7171 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7172 LLVMContext *Context = DAG.getContext();
7173 DebugLoc dl = Op.getDebugLoc();
7174 EVT OpVT = Op.getValueType();
7176 // If this is a 256-bit vector result, first insert into a 128-bit
7177 // vector and then insert into the 256-bit vector.
7178 if (OpVT.getSizeInBits() > 128) {
7179 // Insert into a 128-bit vector.
7180 EVT VT128 = EVT::getVectorVT(*Context,
7181 OpVT.getVectorElementType(),
7182 OpVT.getVectorNumElements() / 2);
7184 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7186 // Insert the 128-bit vector.
7187 return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7188 DAG.getConstant(0, MVT::i32),
7192 if (Op.getValueType() == MVT::v1i64 &&
7193 Op.getOperand(0).getValueType() == MVT::i64)
7194 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7196 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7197 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7198 "Expected an SSE type!");
7199 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7200 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7203 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7204 // a simple subregister reference or explicit instructions to grab
7205 // upper bits of a vector.
7207 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7208 if (Subtarget->hasAVX()) {
7209 DebugLoc dl = Op.getNode()->getDebugLoc();
7210 SDValue Vec = Op.getNode()->getOperand(0);
7211 SDValue Idx = Op.getNode()->getOperand(1);
7213 if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7214 && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7215 return Extract128BitVector(Vec, Idx, DAG, dl);
7221 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7222 // simple superregister reference or explicit instructions to insert
7223 // the upper bits of a vector.
7225 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7226 if (Subtarget->hasAVX()) {
7227 DebugLoc dl = Op.getNode()->getDebugLoc();
7228 SDValue Vec = Op.getNode()->getOperand(0);
7229 SDValue SubVec = Op.getNode()->getOperand(1);
7230 SDValue Idx = Op.getNode()->getOperand(2);
7232 if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7233 && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7234 return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7240 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7241 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7242 // one of the above mentioned nodes. It has to be wrapped because otherwise
7243 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7244 // be used to form addressing mode. These wrapped nodes will be selected
7247 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7248 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7250 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7252 unsigned char OpFlag = 0;
7253 unsigned WrapperKind = X86ISD::Wrapper;
7254 CodeModel::Model M = getTargetMachine().getCodeModel();
7256 if (Subtarget->isPICStyleRIPRel() &&
7257 (M == CodeModel::Small || M == CodeModel::Kernel))
7258 WrapperKind = X86ISD::WrapperRIP;
7259 else if (Subtarget->isPICStyleGOT())
7260 OpFlag = X86II::MO_GOTOFF;
7261 else if (Subtarget->isPICStyleStubPIC())
7262 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7264 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7266 CP->getOffset(), OpFlag);
7267 DebugLoc DL = CP->getDebugLoc();
7268 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7269 // With PIC, the address is actually $g + Offset.
7271 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7272 DAG.getNode(X86ISD::GlobalBaseReg,
7273 DebugLoc(), getPointerTy()),
7280 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7281 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7283 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7285 unsigned char OpFlag = 0;
7286 unsigned WrapperKind = X86ISD::Wrapper;
7287 CodeModel::Model M = getTargetMachine().getCodeModel();
7289 if (Subtarget->isPICStyleRIPRel() &&
7290 (M == CodeModel::Small || M == CodeModel::Kernel))
7291 WrapperKind = X86ISD::WrapperRIP;
7292 else if (Subtarget->isPICStyleGOT())
7293 OpFlag = X86II::MO_GOTOFF;
7294 else if (Subtarget->isPICStyleStubPIC())
7295 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7297 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7299 DebugLoc DL = JT->getDebugLoc();
7300 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7302 // With PIC, the address is actually $g + Offset.
7304 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7305 DAG.getNode(X86ISD::GlobalBaseReg,
7306 DebugLoc(), getPointerTy()),
7313 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7314 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7316 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7318 unsigned char OpFlag = 0;
7319 unsigned WrapperKind = X86ISD::Wrapper;
7320 CodeModel::Model M = getTargetMachine().getCodeModel();
7322 if (Subtarget->isPICStyleRIPRel() &&
7323 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7324 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7325 OpFlag = X86II::MO_GOTPCREL;
7326 WrapperKind = X86ISD::WrapperRIP;
7327 } else if (Subtarget->isPICStyleGOT()) {
7328 OpFlag = X86II::MO_GOT;
7329 } else if (Subtarget->isPICStyleStubPIC()) {
7330 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7331 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7332 OpFlag = X86II::MO_DARWIN_NONLAZY;
7335 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7337 DebugLoc DL = Op.getDebugLoc();
7338 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7341 // With PIC, the address is actually $g + Offset.
7342 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7343 !Subtarget->is64Bit()) {
7344 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7345 DAG.getNode(X86ISD::GlobalBaseReg,
7346 DebugLoc(), getPointerTy()),
7350 // For symbols that require a load from a stub to get the address, emit the
7352 if (isGlobalStubReference(OpFlag))
7353 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7354 MachinePointerInfo::getGOT(), false, false, false, 0);
7360 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7361 // Create the TargetBlockAddressAddress node.
7362 unsigned char OpFlags =
7363 Subtarget->ClassifyBlockAddressReference();
7364 CodeModel::Model M = getTargetMachine().getCodeModel();
7365 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7366 DebugLoc dl = Op.getDebugLoc();
7367 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7368 /*isTarget=*/true, OpFlags);
7370 if (Subtarget->isPICStyleRIPRel() &&
7371 (M == CodeModel::Small || M == CodeModel::Kernel))
7372 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7374 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7376 // With PIC, the address is actually $g + Offset.
7377 if (isGlobalRelativeToPICBase(OpFlags)) {
7378 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7379 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7387 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7389 SelectionDAG &DAG) const {
7390 // Create the TargetGlobalAddress node, folding in the constant
7391 // offset if it is legal.
7392 unsigned char OpFlags =
7393 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7394 CodeModel::Model M = getTargetMachine().getCodeModel();
7396 if (OpFlags == X86II::MO_NO_FLAG &&
7397 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7398 // A direct static reference to a global.
7399 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7402 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7405 if (Subtarget->isPICStyleRIPRel() &&
7406 (M == CodeModel::Small || M == CodeModel::Kernel))
7407 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7409 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7411 // With PIC, the address is actually $g + Offset.
7412 if (isGlobalRelativeToPICBase(OpFlags)) {
7413 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7414 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7418 // For globals that require a load from a stub to get the address, emit the
7420 if (isGlobalStubReference(OpFlags))
7421 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7422 MachinePointerInfo::getGOT(), false, false, false, 0);
7424 // If there was a non-zero offset that we didn't fold, create an explicit
7427 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7428 DAG.getConstant(Offset, getPointerTy()));
7434 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7435 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7436 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7437 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7441 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7442 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7443 unsigned char OperandFlags) {
7444 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7445 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7446 DebugLoc dl = GA->getDebugLoc();
7447 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7448 GA->getValueType(0),
7452 SDValue Ops[] = { Chain, TGA, *InFlag };
7453 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7455 SDValue Ops[] = { Chain, TGA };
7456 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7459 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7460 MFI->setAdjustsStack(true);
7462 SDValue Flag = Chain.getValue(1);
7463 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7466 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7468 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7471 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7472 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7473 DAG.getNode(X86ISD::GlobalBaseReg,
7474 DebugLoc(), PtrVT), InFlag);
7475 InFlag = Chain.getValue(1);
7477 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7480 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7482 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7484 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7485 X86::RAX, X86II::MO_TLSGD);
7488 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7489 // "local exec" model.
7490 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7491 const EVT PtrVT, TLSModel::Model model,
7493 DebugLoc dl = GA->getDebugLoc();
7495 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7496 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7497 is64Bit ? 257 : 256));
7499 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7500 DAG.getIntPtrConstant(0),
7501 MachinePointerInfo(Ptr),
7502 false, false, false, 0);
7504 unsigned char OperandFlags = 0;
7505 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7507 unsigned WrapperKind = X86ISD::Wrapper;
7508 if (model == TLSModel::LocalExec) {
7509 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7510 } else if (is64Bit) {
7511 assert(model == TLSModel::InitialExec);
7512 OperandFlags = X86II::MO_GOTTPOFF;
7513 WrapperKind = X86ISD::WrapperRIP;
7515 assert(model == TLSModel::InitialExec);
7516 OperandFlags = X86II::MO_INDNTPOFF;
7519 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7521 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7522 GA->getValueType(0),
7523 GA->getOffset(), OperandFlags);
7524 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7526 if (model == TLSModel::InitialExec)
7527 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7528 MachinePointerInfo::getGOT(), false, false, false, 0);
7530 // The address of the thread local variable is the add of the thread
7531 // pointer with the offset of the variable.
7532 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7536 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7538 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7539 const GlobalValue *GV = GA->getGlobal();
7541 if (Subtarget->isTargetELF()) {
7542 // TODO: implement the "local dynamic" model
7543 // TODO: implement the "initial exec"model for pic executables
7545 // If GV is an alias then use the aliasee for determining
7546 // thread-localness.
7547 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7548 GV = GA->resolveAliasedGlobal(false);
7550 TLSModel::Model model
7551 = getTLSModel(GV, getTargetMachine().getRelocationModel());
7554 case TLSModel::GeneralDynamic:
7555 case TLSModel::LocalDynamic: // not implemented
7556 if (Subtarget->is64Bit())
7557 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7558 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7560 case TLSModel::InitialExec:
7561 case TLSModel::LocalExec:
7562 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7563 Subtarget->is64Bit());
7565 } else if (Subtarget->isTargetDarwin()) {
7566 // Darwin only has one model of TLS. Lower to that.
7567 unsigned char OpFlag = 0;
7568 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7569 X86ISD::WrapperRIP : X86ISD::Wrapper;
7571 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7573 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7574 !Subtarget->is64Bit();
7576 OpFlag = X86II::MO_TLVP_PIC_BASE;
7578 OpFlag = X86II::MO_TLVP;
7579 DebugLoc DL = Op.getDebugLoc();
7580 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7581 GA->getValueType(0),
7582 GA->getOffset(), OpFlag);
7583 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7585 // With PIC32, the address is actually $g + Offset.
7587 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7588 DAG.getNode(X86ISD::GlobalBaseReg,
7589 DebugLoc(), getPointerTy()),
7592 // Lowering the machine isd will make sure everything is in the right
7594 SDValue Chain = DAG.getEntryNode();
7595 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7596 SDValue Args[] = { Chain, Offset };
7597 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7599 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7600 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7601 MFI->setAdjustsStack(true);
7603 // And our return value (tls address) is in the standard call return value
7605 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7606 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7611 "TLS not implemented for this target.");
7613 llvm_unreachable("Unreachable");
7618 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7619 /// take a 2 x i32 value to shift plus a shift amount.
7620 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7621 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7622 EVT VT = Op.getValueType();
7623 unsigned VTBits = VT.getSizeInBits();
7624 DebugLoc dl = Op.getDebugLoc();
7625 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7626 SDValue ShOpLo = Op.getOperand(0);
7627 SDValue ShOpHi = Op.getOperand(1);
7628 SDValue ShAmt = Op.getOperand(2);
7629 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7630 DAG.getConstant(VTBits - 1, MVT::i8))
7631 : DAG.getConstant(0, VT);
7634 if (Op.getOpcode() == ISD::SHL_PARTS) {
7635 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7636 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7638 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7639 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7642 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7643 DAG.getConstant(VTBits, MVT::i8));
7644 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7645 AndNode, DAG.getConstant(0, MVT::i8));
7648 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7649 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7650 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7652 if (Op.getOpcode() == ISD::SHL_PARTS) {
7653 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7654 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7656 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7657 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7660 SDValue Ops[2] = { Lo, Hi };
7661 return DAG.getMergeValues(Ops, 2, dl);
7664 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7665 SelectionDAG &DAG) const {
7666 EVT SrcVT = Op.getOperand(0).getValueType();
7668 if (SrcVT.isVector())
7671 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7672 "Unknown SINT_TO_FP to lower!");
7674 // These are really Legal; return the operand so the caller accepts it as
7676 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7678 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7679 Subtarget->is64Bit()) {
7683 DebugLoc dl = Op.getDebugLoc();
7684 unsigned Size = SrcVT.getSizeInBits()/8;
7685 MachineFunction &MF = DAG.getMachineFunction();
7686 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7687 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7688 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7690 MachinePointerInfo::getFixedStack(SSFI),
7692 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7695 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7697 SelectionDAG &DAG) const {
7699 DebugLoc DL = Op.getDebugLoc();
7701 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7703 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7705 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7707 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7709 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7710 MachineMemOperand *MMO;
7712 int SSFI = FI->getIndex();
7714 DAG.getMachineFunction()
7715 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7716 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7718 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7719 StackSlot = StackSlot.getOperand(1);
7721 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7722 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7724 Tys, Ops, array_lengthof(Ops),
7728 Chain = Result.getValue(1);
7729 SDValue InFlag = Result.getValue(2);
7731 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7732 // shouldn't be necessary except that RFP cannot be live across
7733 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7734 MachineFunction &MF = DAG.getMachineFunction();
7735 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7736 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7737 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7738 Tys = DAG.getVTList(MVT::Other);
7740 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7742 MachineMemOperand *MMO =
7743 DAG.getMachineFunction()
7744 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7745 MachineMemOperand::MOStore, SSFISize, SSFISize);
7747 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7748 Ops, array_lengthof(Ops),
7749 Op.getValueType(), MMO);
7750 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7751 MachinePointerInfo::getFixedStack(SSFI),
7752 false, false, false, 0);
7758 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7759 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7760 SelectionDAG &DAG) const {
7761 // This algorithm is not obvious. Here it is in C code, more or less:
7763 double uint64_to_double( uint32_t hi, uint32_t lo ) {
7764 static const __m128i exp = { 0x4330000045300000ULL, 0 };
7765 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7767 // Copy ints to xmm registers.
7768 __m128i xh = _mm_cvtsi32_si128( hi );
7769 __m128i xl = _mm_cvtsi32_si128( lo );
7771 // Combine into low half of a single xmm register.
7772 __m128i x = _mm_unpacklo_epi32( xh, xl );
7776 // Merge in appropriate exponents to give the integer bits the right
7778 x = _mm_unpacklo_epi32( x, exp );
7780 // Subtract away the biases to deal with the IEEE-754 double precision
7782 d = _mm_sub_pd( (__m128d) x, bias );
7784 // All conversions up to here are exact. The correctly rounded result is
7785 // calculated using the current rounding mode using the following
7787 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7788 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
7789 // store doesn't really need to be here (except
7790 // maybe to zero the other double)
7795 DebugLoc dl = Op.getDebugLoc();
7796 LLVMContext *Context = DAG.getContext();
7798 // Build some magic constants.
7799 std::vector<Constant*> CV0;
7800 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7801 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7802 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7803 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7804 Constant *C0 = ConstantVector::get(CV0);
7805 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7807 std::vector<Constant*> CV1;
7809 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7811 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7812 Constant *C1 = ConstantVector::get(CV1);
7813 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7815 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7816 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7818 DAG.getIntPtrConstant(1)));
7819 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7820 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7822 DAG.getIntPtrConstant(0)));
7823 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7824 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7825 MachinePointerInfo::getConstantPool(),
7826 false, false, false, 16);
7827 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7828 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7829 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7830 MachinePointerInfo::getConstantPool(),
7831 false, false, false, 16);
7832 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7834 // Add the halves; easiest way is to swap them into another reg first.
7835 int ShufMask[2] = { 1, -1 };
7836 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7837 DAG.getUNDEF(MVT::v2f64), ShufMask);
7838 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7839 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7840 DAG.getIntPtrConstant(0));
7843 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7844 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7845 SelectionDAG &DAG) const {
7846 DebugLoc dl = Op.getDebugLoc();
7847 // FP constant to bias correct the final result.
7848 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7851 // Load the 32-bit value into an XMM register.
7852 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7855 // Zero out the upper parts of the register.
7856 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7859 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7860 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7861 DAG.getIntPtrConstant(0));
7863 // Or the load with the bias.
7864 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7865 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7866 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7868 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7869 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7870 MVT::v2f64, Bias)));
7871 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7872 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7873 DAG.getIntPtrConstant(0));
7875 // Subtract the bias.
7876 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7878 // Handle final rounding.
7879 EVT DestVT = Op.getValueType();
7881 if (DestVT.bitsLT(MVT::f64)) {
7882 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7883 DAG.getIntPtrConstant(0));
7884 } else if (DestVT.bitsGT(MVT::f64)) {
7885 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7888 // Handle final rounding.
7892 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7893 SelectionDAG &DAG) const {
7894 SDValue N0 = Op.getOperand(0);
7895 DebugLoc dl = Op.getDebugLoc();
7897 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7898 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7899 // the optimization here.
7900 if (DAG.SignBitIsZero(N0))
7901 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7903 EVT SrcVT = N0.getValueType();
7904 EVT DstVT = Op.getValueType();
7905 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7906 return LowerUINT_TO_FP_i64(Op, DAG);
7907 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7908 return LowerUINT_TO_FP_i32(Op, DAG);
7910 // Make a 64-bit buffer, and use it to build an FILD.
7911 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7912 if (SrcVT == MVT::i32) {
7913 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7914 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7915 getPointerTy(), StackSlot, WordOff);
7916 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7917 StackSlot, MachinePointerInfo(),
7919 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7920 OffsetSlot, MachinePointerInfo(),
7922 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7926 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7927 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7928 StackSlot, MachinePointerInfo(),
7930 // For i64 source, we need to add the appropriate power of 2 if the input
7931 // was negative. This is the same as the optimization in
7932 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7933 // we must be careful to do the computation in x87 extended precision, not
7934 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7935 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7936 MachineMemOperand *MMO =
7937 DAG.getMachineFunction()
7938 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7939 MachineMemOperand::MOLoad, 8, 8);
7941 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7942 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7943 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7946 APInt FF(32, 0x5F800000ULL);
7948 // Check whether the sign bit is set.
7949 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7950 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7953 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7954 SDValue FudgePtr = DAG.getConstantPool(
7955 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7958 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7959 SDValue Zero = DAG.getIntPtrConstant(0);
7960 SDValue Four = DAG.getIntPtrConstant(4);
7961 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7963 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7965 // Load the value out, extending it from f32 to f80.
7966 // FIXME: Avoid the extend by constructing the right constant pool?
7967 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7968 FudgePtr, MachinePointerInfo::getConstantPool(),
7969 MVT::f32, false, false, 4);
7970 // Extend everything to 80 bits to force it to be done on x87.
7971 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7972 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7975 std::pair<SDValue,SDValue> X86TargetLowering::
7976 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7977 DebugLoc DL = Op.getDebugLoc();
7979 EVT DstTy = Op.getValueType();
7982 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7986 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7987 DstTy.getSimpleVT() >= MVT::i16 &&
7988 "Unknown FP_TO_SINT to lower!");
7990 // These are really Legal.
7991 if (DstTy == MVT::i32 &&
7992 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7993 return std::make_pair(SDValue(), SDValue());
7994 if (Subtarget->is64Bit() &&
7995 DstTy == MVT::i64 &&
7996 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7997 return std::make_pair(SDValue(), SDValue());
7999 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
8001 MachineFunction &MF = DAG.getMachineFunction();
8002 unsigned MemSize = DstTy.getSizeInBits()/8;
8003 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8004 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8009 switch (DstTy.getSimpleVT().SimpleTy) {
8010 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8011 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8012 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8013 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8016 SDValue Chain = DAG.getEntryNode();
8017 SDValue Value = Op.getOperand(0);
8018 EVT TheVT = Op.getOperand(0).getValueType();
8019 if (isScalarFPTypeInSSEReg(TheVT)) {
8020 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8021 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8022 MachinePointerInfo::getFixedStack(SSFI),
8024 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8026 Chain, StackSlot, DAG.getValueType(TheVT)
8029 MachineMemOperand *MMO =
8030 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8031 MachineMemOperand::MOLoad, MemSize, MemSize);
8032 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8034 Chain = Value.getValue(1);
8035 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8036 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8039 MachineMemOperand *MMO =
8040 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8041 MachineMemOperand::MOStore, MemSize, MemSize);
8043 // Build the FP_TO_INT*_IN_MEM
8044 SDValue Ops[] = { Chain, Value, StackSlot };
8045 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8046 Ops, 3, DstTy, MMO);
8048 return std::make_pair(FIST, StackSlot);
8051 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8052 SelectionDAG &DAG) const {
8053 if (Op.getValueType().isVector())
8056 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
8057 SDValue FIST = Vals.first, StackSlot = Vals.second;
8058 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8059 if (FIST.getNode() == 0) return Op;
8062 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8063 FIST, StackSlot, MachinePointerInfo(),
8064 false, false, false, 0);
8067 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8068 SelectionDAG &DAG) const {
8069 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
8070 SDValue FIST = Vals.first, StackSlot = Vals.second;
8071 assert(FIST.getNode() && "Unexpected failure");
8074 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8075 FIST, StackSlot, MachinePointerInfo(),
8076 false, false, false, 0);
8079 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8080 SelectionDAG &DAG) const {
8081 LLVMContext *Context = DAG.getContext();
8082 DebugLoc dl = Op.getDebugLoc();
8083 EVT VT = Op.getValueType();
8086 EltVT = VT.getVectorElementType();
8087 std::vector<Constant*> CV;
8088 if (EltVT == MVT::f64) {
8089 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8093 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8099 Constant *C = ConstantVector::get(CV);
8100 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8101 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8102 MachinePointerInfo::getConstantPool(),
8103 false, false, false, 16);
8104 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8107 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8108 LLVMContext *Context = DAG.getContext();
8109 DebugLoc dl = Op.getDebugLoc();
8110 EVT VT = Op.getValueType();
8113 EltVT = VT.getVectorElementType();
8114 std::vector<Constant*> CV;
8115 if (EltVT == MVT::f64) {
8116 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8120 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8126 Constant *C = ConstantVector::get(CV);
8127 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8128 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8129 MachinePointerInfo::getConstantPool(),
8130 false, false, false, 16);
8131 if (VT.isVector()) {
8132 return DAG.getNode(ISD::BITCAST, dl, VT,
8133 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8134 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8136 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8138 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8142 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8143 LLVMContext *Context = DAG.getContext();
8144 SDValue Op0 = Op.getOperand(0);
8145 SDValue Op1 = Op.getOperand(1);
8146 DebugLoc dl = Op.getDebugLoc();
8147 EVT VT = Op.getValueType();
8148 EVT SrcVT = Op1.getValueType();
8150 // If second operand is smaller, extend it first.
8151 if (SrcVT.bitsLT(VT)) {
8152 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8155 // And if it is bigger, shrink it first.
8156 if (SrcVT.bitsGT(VT)) {
8157 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8161 // At this point the operands and the result should have the same
8162 // type, and that won't be f80 since that is not custom lowered.
8164 // First get the sign bit of second operand.
8165 std::vector<Constant*> CV;
8166 if (SrcVT == MVT::f64) {
8167 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8168 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8170 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8171 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8172 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8173 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8175 Constant *C = ConstantVector::get(CV);
8176 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8177 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8178 MachinePointerInfo::getConstantPool(),
8179 false, false, false, 16);
8180 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8182 // Shift sign bit right or left if the two operands have different types.
8183 if (SrcVT.bitsGT(VT)) {
8184 // Op0 is MVT::f32, Op1 is MVT::f64.
8185 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8186 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8187 DAG.getConstant(32, MVT::i32));
8188 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8189 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8190 DAG.getIntPtrConstant(0));
8193 // Clear first operand sign bit.
8195 if (VT == MVT::f64) {
8196 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8197 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8199 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8200 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8201 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8202 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8204 C = ConstantVector::get(CV);
8205 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8206 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8207 MachinePointerInfo::getConstantPool(),
8208 false, false, false, 16);
8209 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8211 // Or the value with the sign bit.
8212 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8215 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8216 SDValue N0 = Op.getOperand(0);
8217 DebugLoc dl = Op.getDebugLoc();
8218 EVT VT = Op.getValueType();
8220 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8221 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8222 DAG.getConstant(1, VT));
8223 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8226 /// Emit nodes that will be selected as "test Op0,Op0", or something
8228 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8229 SelectionDAG &DAG) const {
8230 DebugLoc dl = Op.getDebugLoc();
8232 // CF and OF aren't always set the way we want. Determine which
8233 // of these we need.
8234 bool NeedCF = false;
8235 bool NeedOF = false;
8238 case X86::COND_A: case X86::COND_AE:
8239 case X86::COND_B: case X86::COND_BE:
8242 case X86::COND_G: case X86::COND_GE:
8243 case X86::COND_L: case X86::COND_LE:
8244 case X86::COND_O: case X86::COND_NO:
8249 // See if we can use the EFLAGS value from the operand instead of
8250 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8251 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8252 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8253 // Emit a CMP with 0, which is the TEST pattern.
8254 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8255 DAG.getConstant(0, Op.getValueType()));
8257 unsigned Opcode = 0;
8258 unsigned NumOperands = 0;
8259 switch (Op.getNode()->getOpcode()) {
8261 // Due to an isel shortcoming, be conservative if this add is likely to be
8262 // selected as part of a load-modify-store instruction. When the root node
8263 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8264 // uses of other nodes in the match, such as the ADD in this case. This
8265 // leads to the ADD being left around and reselected, with the result being
8266 // two adds in the output. Alas, even if none our users are stores, that
8267 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8268 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8269 // climbing the DAG back to the root, and it doesn't seem to be worth the
8271 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8272 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8273 if (UI->getOpcode() != ISD::CopyToReg &&
8274 UI->getOpcode() != ISD::SETCC &&
8275 UI->getOpcode() != ISD::STORE)
8278 if (ConstantSDNode *C =
8279 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8280 // An add of one will be selected as an INC.
8281 if (C->getAPIntValue() == 1) {
8282 Opcode = X86ISD::INC;
8287 // An add of negative one (subtract of one) will be selected as a DEC.
8288 if (C->getAPIntValue().isAllOnesValue()) {
8289 Opcode = X86ISD::DEC;
8295 // Otherwise use a regular EFLAGS-setting add.
8296 Opcode = X86ISD::ADD;
8300 // If the primary and result isn't used, don't bother using X86ISD::AND,
8301 // because a TEST instruction will be better.
8302 bool NonFlagUse = false;
8303 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8304 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8306 unsigned UOpNo = UI.getOperandNo();
8307 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8308 // Look pass truncate.
8309 UOpNo = User->use_begin().getOperandNo();
8310 User = *User->use_begin();
8313 if (User->getOpcode() != ISD::BRCOND &&
8314 User->getOpcode() != ISD::SETCC &&
8315 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8328 // Due to the ISEL shortcoming noted above, be conservative if this op is
8329 // likely to be selected as part of a load-modify-store instruction.
8330 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8331 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8332 if (UI->getOpcode() == ISD::STORE)
8335 // Otherwise use a regular EFLAGS-setting instruction.
8336 switch (Op.getNode()->getOpcode()) {
8337 default: llvm_unreachable("unexpected operator!");
8338 case ISD::SUB: Opcode = X86ISD::SUB; break;
8339 case ISD::OR: Opcode = X86ISD::OR; break;
8340 case ISD::XOR: Opcode = X86ISD::XOR; break;
8341 case ISD::AND: Opcode = X86ISD::AND; break;
8353 return SDValue(Op.getNode(), 1);
8360 // Emit a CMP with 0, which is the TEST pattern.
8361 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8362 DAG.getConstant(0, Op.getValueType()));
8364 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8365 SmallVector<SDValue, 4> Ops;
8366 for (unsigned i = 0; i != NumOperands; ++i)
8367 Ops.push_back(Op.getOperand(i));
8369 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8370 DAG.ReplaceAllUsesWith(Op, New);
8371 return SDValue(New.getNode(), 1);
8374 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8376 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8377 SelectionDAG &DAG) const {
8378 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8379 if (C->getAPIntValue() == 0)
8380 return EmitTest(Op0, X86CC, DAG);
8382 DebugLoc dl = Op0.getDebugLoc();
8383 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8386 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8387 /// if it's possible.
8388 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8389 DebugLoc dl, SelectionDAG &DAG) const {
8390 SDValue Op0 = And.getOperand(0);
8391 SDValue Op1 = And.getOperand(1);
8392 if (Op0.getOpcode() == ISD::TRUNCATE)
8393 Op0 = Op0.getOperand(0);
8394 if (Op1.getOpcode() == ISD::TRUNCATE)
8395 Op1 = Op1.getOperand(0);
8398 if (Op1.getOpcode() == ISD::SHL)
8399 std::swap(Op0, Op1);
8400 if (Op0.getOpcode() == ISD::SHL) {
8401 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8402 if (And00C->getZExtValue() == 1) {
8403 // If we looked past a truncate, check that it's only truncating away
8405 unsigned BitWidth = Op0.getValueSizeInBits();
8406 unsigned AndBitWidth = And.getValueSizeInBits();
8407 if (BitWidth > AndBitWidth) {
8408 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8409 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8410 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8414 RHS = Op0.getOperand(1);
8416 } else if (Op1.getOpcode() == ISD::Constant) {
8417 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8418 uint64_t AndRHSVal = AndRHS->getZExtValue();
8419 SDValue AndLHS = Op0;
8421 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8422 LHS = AndLHS.getOperand(0);
8423 RHS = AndLHS.getOperand(1);
8426 // Use BT if the immediate can't be encoded in a TEST instruction.
8427 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8429 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8433 if (LHS.getNode()) {
8434 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8435 // instruction. Since the shift amount is in-range-or-undefined, we know
8436 // that doing a bittest on the i32 value is ok. We extend to i32 because
8437 // the encoding for the i16 version is larger than the i32 version.
8438 // Also promote i16 to i32 for performance / code size reason.
8439 if (LHS.getValueType() == MVT::i8 ||
8440 LHS.getValueType() == MVT::i16)
8441 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8443 // If the operand types disagree, extend the shift amount to match. Since
8444 // BT ignores high bits (like shifts) we can use anyextend.
8445 if (LHS.getValueType() != RHS.getValueType())
8446 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8448 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8449 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8450 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8451 DAG.getConstant(Cond, MVT::i8), BT);
8457 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8459 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8461 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8462 SDValue Op0 = Op.getOperand(0);
8463 SDValue Op1 = Op.getOperand(1);
8464 DebugLoc dl = Op.getDebugLoc();
8465 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8467 // Optimize to BT if possible.
8468 // Lower (X & (1 << N)) == 0 to BT(X, N).
8469 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8470 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8471 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8472 Op1.getOpcode() == ISD::Constant &&
8473 cast<ConstantSDNode>(Op1)->isNullValue() &&
8474 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8475 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8476 if (NewSetCC.getNode())
8480 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8482 if (Op1.getOpcode() == ISD::Constant &&
8483 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8484 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8485 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8487 // If the input is a setcc, then reuse the input setcc or use a new one with
8488 // the inverted condition.
8489 if (Op0.getOpcode() == X86ISD::SETCC) {
8490 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8491 bool Invert = (CC == ISD::SETNE) ^
8492 cast<ConstantSDNode>(Op1)->isNullValue();
8493 if (!Invert) return Op0;
8495 CCode = X86::GetOppositeBranchCondition(CCode);
8496 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8497 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8501 bool isFP = Op1.getValueType().isFloatingPoint();
8502 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8503 if (X86CC == X86::COND_INVALID)
8506 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8507 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8508 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8511 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8512 // ones, and then concatenate the result back.
8513 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8514 EVT VT = Op.getValueType();
8516 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8517 "Unsupported value type for operation");
8519 int NumElems = VT.getVectorNumElements();
8520 DebugLoc dl = Op.getDebugLoc();
8521 SDValue CC = Op.getOperand(2);
8522 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8523 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8525 // Extract the LHS vectors
8526 SDValue LHS = Op.getOperand(0);
8527 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8528 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8530 // Extract the RHS vectors
8531 SDValue RHS = Op.getOperand(1);
8532 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8533 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8535 // Issue the operation on the smaller types and concatenate the result back
8536 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8537 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8538 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8539 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8540 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8544 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8546 SDValue Op0 = Op.getOperand(0);
8547 SDValue Op1 = Op.getOperand(1);
8548 SDValue CC = Op.getOperand(2);
8549 EVT VT = Op.getValueType();
8550 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8551 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8552 DebugLoc dl = Op.getDebugLoc();
8556 EVT EltVT = Op0.getValueType().getVectorElementType();
8557 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8559 unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8562 // SSE Condition code mapping:
8571 switch (SetCCOpcode) {
8574 case ISD::SETEQ: SSECC = 0; break;
8576 case ISD::SETGT: Swap = true; // Fallthrough
8578 case ISD::SETOLT: SSECC = 1; break;
8580 case ISD::SETGE: Swap = true; // Fallthrough
8582 case ISD::SETOLE: SSECC = 2; break;
8583 case ISD::SETUO: SSECC = 3; break;
8585 case ISD::SETNE: SSECC = 4; break;
8586 case ISD::SETULE: Swap = true;
8587 case ISD::SETUGE: SSECC = 5; break;
8588 case ISD::SETULT: Swap = true;
8589 case ISD::SETUGT: SSECC = 6; break;
8590 case ISD::SETO: SSECC = 7; break;
8593 std::swap(Op0, Op1);
8595 // In the two special cases we can't handle, emit two comparisons.
8597 if (SetCCOpcode == ISD::SETUEQ) {
8599 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8600 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8601 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8602 } else if (SetCCOpcode == ISD::SETONE) {
8604 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8605 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8606 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8608 llvm_unreachable("Illegal FP comparison");
8610 // Handle all other FP comparisons here.
8611 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8614 // Break 256-bit integer vector compare into smaller ones.
8615 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8616 return Lower256IntVSETCC(Op, DAG);
8618 // We are handling one of the integer comparisons here. Since SSE only has
8619 // GT and EQ comparisons for integer, swapping operands and multiple
8620 // operations may be required for some comparisons.
8621 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8622 bool Swap = false, Invert = false, FlipSigns = false;
8624 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8626 case MVT::i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8627 case MVT::i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8628 case MVT::i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8629 case MVT::i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8632 switch (SetCCOpcode) {
8634 case ISD::SETNE: Invert = true;
8635 case ISD::SETEQ: Opc = EQOpc; break;
8636 case ISD::SETLT: Swap = true;
8637 case ISD::SETGT: Opc = GTOpc; break;
8638 case ISD::SETGE: Swap = true;
8639 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
8640 case ISD::SETULT: Swap = true;
8641 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8642 case ISD::SETUGE: Swap = true;
8643 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8646 std::swap(Op0, Op1);
8648 // Check that the operation in question is available (most are plain SSE2,
8649 // but PCMPGTQ and PCMPEQQ have different requirements).
8650 if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42orAVX())
8652 if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41orAVX())
8655 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8656 // bits of the inputs before performing those operations.
8658 EVT EltVT = VT.getVectorElementType();
8659 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8661 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8662 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8664 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8665 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8668 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8670 // If the logical-not of the result is required, perform that now.
8672 Result = DAG.getNOT(dl, Result, VT);
8677 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8678 static bool isX86LogicalCmp(SDValue Op) {
8679 unsigned Opc = Op.getNode()->getOpcode();
8680 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8682 if (Op.getResNo() == 1 &&
8683 (Opc == X86ISD::ADD ||
8684 Opc == X86ISD::SUB ||
8685 Opc == X86ISD::ADC ||
8686 Opc == X86ISD::SBB ||
8687 Opc == X86ISD::SMUL ||
8688 Opc == X86ISD::UMUL ||
8689 Opc == X86ISD::INC ||
8690 Opc == X86ISD::DEC ||
8691 Opc == X86ISD::OR ||
8692 Opc == X86ISD::XOR ||
8693 Opc == X86ISD::AND))
8696 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8702 static bool isZero(SDValue V) {
8703 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8704 return C && C->isNullValue();
8707 static bool isAllOnes(SDValue V) {
8708 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8709 return C && C->isAllOnesValue();
8712 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8713 bool addTest = true;
8714 SDValue Cond = Op.getOperand(0);
8715 SDValue Op1 = Op.getOperand(1);
8716 SDValue Op2 = Op.getOperand(2);
8717 DebugLoc DL = Op.getDebugLoc();
8720 if (Cond.getOpcode() == ISD::SETCC) {
8721 SDValue NewCond = LowerSETCC(Cond, DAG);
8722 if (NewCond.getNode())
8726 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8727 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8728 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8729 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8730 if (Cond.getOpcode() == X86ISD::SETCC &&
8731 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8732 isZero(Cond.getOperand(1).getOperand(1))) {
8733 SDValue Cmp = Cond.getOperand(1);
8735 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8737 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8738 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8739 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8741 SDValue CmpOp0 = Cmp.getOperand(0);
8742 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8743 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8745 SDValue Res = // Res = 0 or -1.
8746 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8747 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8749 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8750 Res = DAG.getNOT(DL, Res, Res.getValueType());
8752 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8753 if (N2C == 0 || !N2C->isNullValue())
8754 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8759 // Look past (and (setcc_carry (cmp ...)), 1).
8760 if (Cond.getOpcode() == ISD::AND &&
8761 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8762 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8763 if (C && C->getAPIntValue() == 1)
8764 Cond = Cond.getOperand(0);
8767 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8768 // setting operand in place of the X86ISD::SETCC.
8769 unsigned CondOpcode = Cond.getOpcode();
8770 if (CondOpcode == X86ISD::SETCC ||
8771 CondOpcode == X86ISD::SETCC_CARRY) {
8772 CC = Cond.getOperand(0);
8774 SDValue Cmp = Cond.getOperand(1);
8775 unsigned Opc = Cmp.getOpcode();
8776 EVT VT = Op.getValueType();
8778 bool IllegalFPCMov = false;
8779 if (VT.isFloatingPoint() && !VT.isVector() &&
8780 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8781 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8783 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8784 Opc == X86ISD::BT) { // FIXME
8788 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8789 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8790 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8791 Cond.getOperand(0).getValueType() != MVT::i8)) {
8792 SDValue LHS = Cond.getOperand(0);
8793 SDValue RHS = Cond.getOperand(1);
8797 switch (CondOpcode) {
8798 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8799 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8800 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8801 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8802 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8803 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8804 default: llvm_unreachable("unexpected overflowing operator");
8806 if (CondOpcode == ISD::UMULO)
8807 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8810 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8812 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8814 if (CondOpcode == ISD::UMULO)
8815 Cond = X86Op.getValue(2);
8817 Cond = X86Op.getValue(1);
8819 CC = DAG.getConstant(X86Cond, MVT::i8);
8824 // Look pass the truncate.
8825 if (Cond.getOpcode() == ISD::TRUNCATE)
8826 Cond = Cond.getOperand(0);
8828 // We know the result of AND is compared against zero. Try to match
8830 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8831 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8832 if (NewSetCC.getNode()) {
8833 CC = NewSetCC.getOperand(0);
8834 Cond = NewSetCC.getOperand(1);
8841 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8842 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8845 // a < b ? -1 : 0 -> RES = ~setcc_carry
8846 // a < b ? 0 : -1 -> RES = setcc_carry
8847 // a >= b ? -1 : 0 -> RES = setcc_carry
8848 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8849 if (Cond.getOpcode() == X86ISD::CMP) {
8850 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8852 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8853 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8854 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8855 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8856 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8857 return DAG.getNOT(DL, Res, Res.getValueType());
8862 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8863 // condition is true.
8864 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8865 SDValue Ops[] = { Op2, Op1, CC, Cond };
8866 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8869 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8870 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8871 // from the AND / OR.
8872 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8873 Opc = Op.getOpcode();
8874 if (Opc != ISD::OR && Opc != ISD::AND)
8876 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8877 Op.getOperand(0).hasOneUse() &&
8878 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8879 Op.getOperand(1).hasOneUse());
8882 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8883 // 1 and that the SETCC node has a single use.
8884 static bool isXor1OfSetCC(SDValue Op) {
8885 if (Op.getOpcode() != ISD::XOR)
8887 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8888 if (N1C && N1C->getAPIntValue() == 1) {
8889 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8890 Op.getOperand(0).hasOneUse();
8895 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8896 bool addTest = true;
8897 SDValue Chain = Op.getOperand(0);
8898 SDValue Cond = Op.getOperand(1);
8899 SDValue Dest = Op.getOperand(2);
8900 DebugLoc dl = Op.getDebugLoc();
8902 bool Inverted = false;
8904 if (Cond.getOpcode() == ISD::SETCC) {
8905 // Check for setcc([su]{add,sub,mul}o == 0).
8906 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8907 isa<ConstantSDNode>(Cond.getOperand(1)) &&
8908 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8909 Cond.getOperand(0).getResNo() == 1 &&
8910 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8911 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8912 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8913 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8914 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8915 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8917 Cond = Cond.getOperand(0);
8919 SDValue NewCond = LowerSETCC(Cond, DAG);
8920 if (NewCond.getNode())
8925 // FIXME: LowerXALUO doesn't handle these!!
8926 else if (Cond.getOpcode() == X86ISD::ADD ||
8927 Cond.getOpcode() == X86ISD::SUB ||
8928 Cond.getOpcode() == X86ISD::SMUL ||
8929 Cond.getOpcode() == X86ISD::UMUL)
8930 Cond = LowerXALUO(Cond, DAG);
8933 // Look pass (and (setcc_carry (cmp ...)), 1).
8934 if (Cond.getOpcode() == ISD::AND &&
8935 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8936 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8937 if (C && C->getAPIntValue() == 1)
8938 Cond = Cond.getOperand(0);
8941 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8942 // setting operand in place of the X86ISD::SETCC.
8943 unsigned CondOpcode = Cond.getOpcode();
8944 if (CondOpcode == X86ISD::SETCC ||
8945 CondOpcode == X86ISD::SETCC_CARRY) {
8946 CC = Cond.getOperand(0);
8948 SDValue Cmp = Cond.getOperand(1);
8949 unsigned Opc = Cmp.getOpcode();
8950 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8951 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8955 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8959 // These can only come from an arithmetic instruction with overflow,
8960 // e.g. SADDO, UADDO.
8961 Cond = Cond.getNode()->getOperand(1);
8967 CondOpcode = Cond.getOpcode();
8968 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8969 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8970 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8971 Cond.getOperand(0).getValueType() != MVT::i8)) {
8972 SDValue LHS = Cond.getOperand(0);
8973 SDValue RHS = Cond.getOperand(1);
8977 switch (CondOpcode) {
8978 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8979 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8980 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8981 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8982 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8983 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8984 default: llvm_unreachable("unexpected overflowing operator");
8987 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8988 if (CondOpcode == ISD::UMULO)
8989 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8992 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8994 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8996 if (CondOpcode == ISD::UMULO)
8997 Cond = X86Op.getValue(2);
8999 Cond = X86Op.getValue(1);
9001 CC = DAG.getConstant(X86Cond, MVT::i8);
9005 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9006 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9007 if (CondOpc == ISD::OR) {
9008 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9009 // two branches instead of an explicit OR instruction with a
9011 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9012 isX86LogicalCmp(Cmp)) {
9013 CC = Cond.getOperand(0).getOperand(0);
9014 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9015 Chain, Dest, CC, Cmp);
9016 CC = Cond.getOperand(1).getOperand(0);
9020 } else { // ISD::AND
9021 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9022 // two branches instead of an explicit AND instruction with a
9023 // separate test. However, we only do this if this block doesn't
9024 // have a fall-through edge, because this requires an explicit
9025 // jmp when the condition is false.
9026 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9027 isX86LogicalCmp(Cmp) &&
9028 Op.getNode()->hasOneUse()) {
9029 X86::CondCode CCode =
9030 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9031 CCode = X86::GetOppositeBranchCondition(CCode);
9032 CC = DAG.getConstant(CCode, MVT::i8);
9033 SDNode *User = *Op.getNode()->use_begin();
9034 // Look for an unconditional branch following this conditional branch.
9035 // We need this because we need to reverse the successors in order
9036 // to implement FCMP_OEQ.
9037 if (User->getOpcode() == ISD::BR) {
9038 SDValue FalseBB = User->getOperand(1);
9040 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9041 assert(NewBR == User);
9045 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9046 Chain, Dest, CC, Cmp);
9047 X86::CondCode CCode =
9048 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9049 CCode = X86::GetOppositeBranchCondition(CCode);
9050 CC = DAG.getConstant(CCode, MVT::i8);
9056 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9057 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9058 // It should be transformed during dag combiner except when the condition
9059 // is set by a arithmetics with overflow node.
9060 X86::CondCode CCode =
9061 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9062 CCode = X86::GetOppositeBranchCondition(CCode);
9063 CC = DAG.getConstant(CCode, MVT::i8);
9064 Cond = Cond.getOperand(0).getOperand(1);
9066 } else if (Cond.getOpcode() == ISD::SETCC &&
9067 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9068 // For FCMP_OEQ, we can emit
9069 // two branches instead of an explicit AND instruction with a
9070 // separate test. However, we only do this if this block doesn't
9071 // have a fall-through edge, because this requires an explicit
9072 // jmp when the condition is false.
9073 if (Op.getNode()->hasOneUse()) {
9074 SDNode *User = *Op.getNode()->use_begin();
9075 // Look for an unconditional branch following this conditional branch.
9076 // We need this because we need to reverse the successors in order
9077 // to implement FCMP_OEQ.
9078 if (User->getOpcode() == ISD::BR) {
9079 SDValue FalseBB = User->getOperand(1);
9081 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9082 assert(NewBR == User);
9086 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9087 Cond.getOperand(0), Cond.getOperand(1));
9088 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9089 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9090 Chain, Dest, CC, Cmp);
9091 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9096 } else if (Cond.getOpcode() == ISD::SETCC &&
9097 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9098 // For FCMP_UNE, we can emit
9099 // two branches instead of an explicit AND instruction with a
9100 // separate test. However, we only do this if this block doesn't
9101 // have a fall-through edge, because this requires an explicit
9102 // jmp when the condition is false.
9103 if (Op.getNode()->hasOneUse()) {
9104 SDNode *User = *Op.getNode()->use_begin();
9105 // Look for an unconditional branch following this conditional branch.
9106 // We need this because we need to reverse the successors in order
9107 // to implement FCMP_UNE.
9108 if (User->getOpcode() == ISD::BR) {
9109 SDValue FalseBB = User->getOperand(1);
9111 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9112 assert(NewBR == User);
9115 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9116 Cond.getOperand(0), Cond.getOperand(1));
9117 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9118 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9119 Chain, Dest, CC, Cmp);
9120 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9130 // Look pass the truncate.
9131 if (Cond.getOpcode() == ISD::TRUNCATE)
9132 Cond = Cond.getOperand(0);
9134 // We know the result of AND is compared against zero. Try to match
9136 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9137 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9138 if (NewSetCC.getNode()) {
9139 CC = NewSetCC.getOperand(0);
9140 Cond = NewSetCC.getOperand(1);
9147 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9148 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9150 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9151 Chain, Dest, CC, Cond);
9155 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9156 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9157 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9158 // that the guard pages used by the OS virtual memory manager are allocated in
9159 // correct sequence.
9161 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9162 SelectionDAG &DAG) const {
9163 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9164 EnableSegmentedStacks) &&
9165 "This should be used only on Windows targets or when segmented stacks "
9167 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9168 DebugLoc dl = Op.getDebugLoc();
9171 SDValue Chain = Op.getOperand(0);
9172 SDValue Size = Op.getOperand(1);
9173 // FIXME: Ensure alignment here
9175 bool Is64Bit = Subtarget->is64Bit();
9176 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9178 if (EnableSegmentedStacks) {
9179 MachineFunction &MF = DAG.getMachineFunction();
9180 MachineRegisterInfo &MRI = MF.getRegInfo();
9183 // The 64 bit implementation of segmented stacks needs to clobber both r10
9184 // r11. This makes it impossible to use it along with nested parameters.
9185 const Function *F = MF.getFunction();
9187 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9189 if (I->hasNestAttr())
9190 report_fatal_error("Cannot use segmented stacks with functions that "
9191 "have nested arguments.");
9194 const TargetRegisterClass *AddrRegClass =
9195 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9196 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9197 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9198 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9199 DAG.getRegister(Vreg, SPTy));
9200 SDValue Ops1[2] = { Value, Chain };
9201 return DAG.getMergeValues(Ops1, 2, dl);
9204 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9206 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9207 Flag = Chain.getValue(1);
9208 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9210 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9211 Flag = Chain.getValue(1);
9213 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9215 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9216 return DAG.getMergeValues(Ops1, 2, dl);
9220 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9221 MachineFunction &MF = DAG.getMachineFunction();
9222 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9224 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9225 DebugLoc DL = Op.getDebugLoc();
9227 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9228 // vastart just stores the address of the VarArgsFrameIndex slot into the
9229 // memory location argument.
9230 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9232 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9233 MachinePointerInfo(SV), false, false, 0);
9237 // gp_offset (0 - 6 * 8)
9238 // fp_offset (48 - 48 + 8 * 16)
9239 // overflow_arg_area (point to parameters coming in memory).
9241 SmallVector<SDValue, 8> MemOps;
9242 SDValue FIN = Op.getOperand(1);
9244 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9245 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9247 FIN, MachinePointerInfo(SV), false, false, 0);
9248 MemOps.push_back(Store);
9251 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9252 FIN, DAG.getIntPtrConstant(4));
9253 Store = DAG.getStore(Op.getOperand(0), DL,
9254 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9256 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9257 MemOps.push_back(Store);
9259 // Store ptr to overflow_arg_area
9260 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9261 FIN, DAG.getIntPtrConstant(4));
9262 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9264 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9265 MachinePointerInfo(SV, 8),
9267 MemOps.push_back(Store);
9269 // Store ptr to reg_save_area.
9270 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9271 FIN, DAG.getIntPtrConstant(8));
9272 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9274 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9275 MachinePointerInfo(SV, 16), false, false, 0);
9276 MemOps.push_back(Store);
9277 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9278 &MemOps[0], MemOps.size());
9281 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9282 assert(Subtarget->is64Bit() &&
9283 "LowerVAARG only handles 64-bit va_arg!");
9284 assert((Subtarget->isTargetLinux() ||
9285 Subtarget->isTargetDarwin()) &&
9286 "Unhandled target in LowerVAARG");
9287 assert(Op.getNode()->getNumOperands() == 4);
9288 SDValue Chain = Op.getOperand(0);
9289 SDValue SrcPtr = Op.getOperand(1);
9290 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9291 unsigned Align = Op.getConstantOperandVal(3);
9292 DebugLoc dl = Op.getDebugLoc();
9294 EVT ArgVT = Op.getNode()->getValueType(0);
9295 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9296 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9299 // Decide which area this value should be read from.
9300 // TODO: Implement the AMD64 ABI in its entirety. This simple
9301 // selection mechanism works only for the basic types.
9302 if (ArgVT == MVT::f80) {
9303 llvm_unreachable("va_arg for f80 not yet implemented");
9304 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9305 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9306 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9307 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9309 llvm_unreachable("Unhandled argument type in LowerVAARG");
9313 // Sanity Check: Make sure using fp_offset makes sense.
9314 assert(!UseSoftFloat &&
9315 !(DAG.getMachineFunction()
9316 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9317 Subtarget->hasXMM());
9320 // Insert VAARG_64 node into the DAG
9321 // VAARG_64 returns two values: Variable Argument Address, Chain
9322 SmallVector<SDValue, 11> InstOps;
9323 InstOps.push_back(Chain);
9324 InstOps.push_back(SrcPtr);
9325 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9326 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9327 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9328 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9329 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9330 VTs, &InstOps[0], InstOps.size(),
9332 MachinePointerInfo(SV),
9337 Chain = VAARG.getValue(1);
9339 // Load the next argument and return it
9340 return DAG.getLoad(ArgVT, dl,
9343 MachinePointerInfo(),
9344 false, false, false, 0);
9347 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9348 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9349 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9350 SDValue Chain = Op.getOperand(0);
9351 SDValue DstPtr = Op.getOperand(1);
9352 SDValue SrcPtr = Op.getOperand(2);
9353 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9354 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9355 DebugLoc DL = Op.getDebugLoc();
9357 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9358 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9360 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9364 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9365 DebugLoc dl = Op.getDebugLoc();
9366 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9368 default: return SDValue(); // Don't custom lower most intrinsics.
9369 // Comparison intrinsics.
9370 case Intrinsic::x86_sse_comieq_ss:
9371 case Intrinsic::x86_sse_comilt_ss:
9372 case Intrinsic::x86_sse_comile_ss:
9373 case Intrinsic::x86_sse_comigt_ss:
9374 case Intrinsic::x86_sse_comige_ss:
9375 case Intrinsic::x86_sse_comineq_ss:
9376 case Intrinsic::x86_sse_ucomieq_ss:
9377 case Intrinsic::x86_sse_ucomilt_ss:
9378 case Intrinsic::x86_sse_ucomile_ss:
9379 case Intrinsic::x86_sse_ucomigt_ss:
9380 case Intrinsic::x86_sse_ucomige_ss:
9381 case Intrinsic::x86_sse_ucomineq_ss:
9382 case Intrinsic::x86_sse2_comieq_sd:
9383 case Intrinsic::x86_sse2_comilt_sd:
9384 case Intrinsic::x86_sse2_comile_sd:
9385 case Intrinsic::x86_sse2_comigt_sd:
9386 case Intrinsic::x86_sse2_comige_sd:
9387 case Intrinsic::x86_sse2_comineq_sd:
9388 case Intrinsic::x86_sse2_ucomieq_sd:
9389 case Intrinsic::x86_sse2_ucomilt_sd:
9390 case Intrinsic::x86_sse2_ucomile_sd:
9391 case Intrinsic::x86_sse2_ucomigt_sd:
9392 case Intrinsic::x86_sse2_ucomige_sd:
9393 case Intrinsic::x86_sse2_ucomineq_sd: {
9395 ISD::CondCode CC = ISD::SETCC_INVALID;
9398 case Intrinsic::x86_sse_comieq_ss:
9399 case Intrinsic::x86_sse2_comieq_sd:
9403 case Intrinsic::x86_sse_comilt_ss:
9404 case Intrinsic::x86_sse2_comilt_sd:
9408 case Intrinsic::x86_sse_comile_ss:
9409 case Intrinsic::x86_sse2_comile_sd:
9413 case Intrinsic::x86_sse_comigt_ss:
9414 case Intrinsic::x86_sse2_comigt_sd:
9418 case Intrinsic::x86_sse_comige_ss:
9419 case Intrinsic::x86_sse2_comige_sd:
9423 case Intrinsic::x86_sse_comineq_ss:
9424 case Intrinsic::x86_sse2_comineq_sd:
9428 case Intrinsic::x86_sse_ucomieq_ss:
9429 case Intrinsic::x86_sse2_ucomieq_sd:
9430 Opc = X86ISD::UCOMI;
9433 case Intrinsic::x86_sse_ucomilt_ss:
9434 case Intrinsic::x86_sse2_ucomilt_sd:
9435 Opc = X86ISD::UCOMI;
9438 case Intrinsic::x86_sse_ucomile_ss:
9439 case Intrinsic::x86_sse2_ucomile_sd:
9440 Opc = X86ISD::UCOMI;
9443 case Intrinsic::x86_sse_ucomigt_ss:
9444 case Intrinsic::x86_sse2_ucomigt_sd:
9445 Opc = X86ISD::UCOMI;
9448 case Intrinsic::x86_sse_ucomige_ss:
9449 case Intrinsic::x86_sse2_ucomige_sd:
9450 Opc = X86ISD::UCOMI;
9453 case Intrinsic::x86_sse_ucomineq_ss:
9454 case Intrinsic::x86_sse2_ucomineq_sd:
9455 Opc = X86ISD::UCOMI;
9460 SDValue LHS = Op.getOperand(1);
9461 SDValue RHS = Op.getOperand(2);
9462 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9463 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9464 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9465 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9466 DAG.getConstant(X86CC, MVT::i8), Cond);
9467 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9469 // Arithmetic intrinsics.
9470 case Intrinsic::x86_sse3_hadd_ps:
9471 case Intrinsic::x86_sse3_hadd_pd:
9472 case Intrinsic::x86_avx_hadd_ps_256:
9473 case Intrinsic::x86_avx_hadd_pd_256:
9474 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9475 Op.getOperand(1), Op.getOperand(2));
9476 case Intrinsic::x86_sse3_hsub_ps:
9477 case Intrinsic::x86_sse3_hsub_pd:
9478 case Intrinsic::x86_avx_hsub_ps_256:
9479 case Intrinsic::x86_avx_hsub_pd_256:
9480 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9481 Op.getOperand(1), Op.getOperand(2));
9482 case Intrinsic::x86_avx2_psllv_d:
9483 case Intrinsic::x86_avx2_psllv_q:
9484 case Intrinsic::x86_avx2_psllv_d_256:
9485 case Intrinsic::x86_avx2_psllv_q_256:
9486 return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9487 Op.getOperand(1), Op.getOperand(2));
9488 case Intrinsic::x86_avx2_psrlv_d:
9489 case Intrinsic::x86_avx2_psrlv_q:
9490 case Intrinsic::x86_avx2_psrlv_d_256:
9491 case Intrinsic::x86_avx2_psrlv_q_256:
9492 return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9493 Op.getOperand(1), Op.getOperand(2));
9494 case Intrinsic::x86_avx2_psrav_d:
9495 case Intrinsic::x86_avx2_psrav_d_256:
9496 return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9497 Op.getOperand(1), Op.getOperand(2));
9499 // ptest and testp intrinsics. The intrinsic these come from are designed to
9500 // return an integer value, not just an instruction so lower it to the ptest
9501 // or testp pattern and a setcc for the result.
9502 case Intrinsic::x86_sse41_ptestz:
9503 case Intrinsic::x86_sse41_ptestc:
9504 case Intrinsic::x86_sse41_ptestnzc:
9505 case Intrinsic::x86_avx_ptestz_256:
9506 case Intrinsic::x86_avx_ptestc_256:
9507 case Intrinsic::x86_avx_ptestnzc_256:
9508 case Intrinsic::x86_avx_vtestz_ps:
9509 case Intrinsic::x86_avx_vtestc_ps:
9510 case Intrinsic::x86_avx_vtestnzc_ps:
9511 case Intrinsic::x86_avx_vtestz_pd:
9512 case Intrinsic::x86_avx_vtestc_pd:
9513 case Intrinsic::x86_avx_vtestnzc_pd:
9514 case Intrinsic::x86_avx_vtestz_ps_256:
9515 case Intrinsic::x86_avx_vtestc_ps_256:
9516 case Intrinsic::x86_avx_vtestnzc_ps_256:
9517 case Intrinsic::x86_avx_vtestz_pd_256:
9518 case Intrinsic::x86_avx_vtestc_pd_256:
9519 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9520 bool IsTestPacked = false;
9523 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9524 case Intrinsic::x86_avx_vtestz_ps:
9525 case Intrinsic::x86_avx_vtestz_pd:
9526 case Intrinsic::x86_avx_vtestz_ps_256:
9527 case Intrinsic::x86_avx_vtestz_pd_256:
9528 IsTestPacked = true; // Fallthrough
9529 case Intrinsic::x86_sse41_ptestz:
9530 case Intrinsic::x86_avx_ptestz_256:
9532 X86CC = X86::COND_E;
9534 case Intrinsic::x86_avx_vtestc_ps:
9535 case Intrinsic::x86_avx_vtestc_pd:
9536 case Intrinsic::x86_avx_vtestc_ps_256:
9537 case Intrinsic::x86_avx_vtestc_pd_256:
9538 IsTestPacked = true; // Fallthrough
9539 case Intrinsic::x86_sse41_ptestc:
9540 case Intrinsic::x86_avx_ptestc_256:
9542 X86CC = X86::COND_B;
9544 case Intrinsic::x86_avx_vtestnzc_ps:
9545 case Intrinsic::x86_avx_vtestnzc_pd:
9546 case Intrinsic::x86_avx_vtestnzc_ps_256:
9547 case Intrinsic::x86_avx_vtestnzc_pd_256:
9548 IsTestPacked = true; // Fallthrough
9549 case Intrinsic::x86_sse41_ptestnzc:
9550 case Intrinsic::x86_avx_ptestnzc_256:
9552 X86CC = X86::COND_A;
9556 SDValue LHS = Op.getOperand(1);
9557 SDValue RHS = Op.getOperand(2);
9558 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9559 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9560 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9561 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9562 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9565 // Fix vector shift instructions where the last operand is a non-immediate
9567 case Intrinsic::x86_avx2_pslli_w:
9568 case Intrinsic::x86_avx2_pslli_d:
9569 case Intrinsic::x86_avx2_pslli_q:
9570 case Intrinsic::x86_avx2_psrli_w:
9571 case Intrinsic::x86_avx2_psrli_d:
9572 case Intrinsic::x86_avx2_psrli_q:
9573 case Intrinsic::x86_avx2_psrai_w:
9574 case Intrinsic::x86_avx2_psrai_d:
9575 case Intrinsic::x86_sse2_pslli_w:
9576 case Intrinsic::x86_sse2_pslli_d:
9577 case Intrinsic::x86_sse2_pslli_q:
9578 case Intrinsic::x86_sse2_psrli_w:
9579 case Intrinsic::x86_sse2_psrli_d:
9580 case Intrinsic::x86_sse2_psrli_q:
9581 case Intrinsic::x86_sse2_psrai_w:
9582 case Intrinsic::x86_sse2_psrai_d:
9583 case Intrinsic::x86_mmx_pslli_w:
9584 case Intrinsic::x86_mmx_pslli_d:
9585 case Intrinsic::x86_mmx_pslli_q:
9586 case Intrinsic::x86_mmx_psrli_w:
9587 case Intrinsic::x86_mmx_psrli_d:
9588 case Intrinsic::x86_mmx_psrli_q:
9589 case Intrinsic::x86_mmx_psrai_w:
9590 case Intrinsic::x86_mmx_psrai_d: {
9591 SDValue ShAmt = Op.getOperand(2);
9592 if (isa<ConstantSDNode>(ShAmt))
9595 unsigned NewIntNo = 0;
9596 EVT ShAmtVT = MVT::v4i32;
9598 case Intrinsic::x86_sse2_pslli_w:
9599 NewIntNo = Intrinsic::x86_sse2_psll_w;
9601 case Intrinsic::x86_sse2_pslli_d:
9602 NewIntNo = Intrinsic::x86_sse2_psll_d;
9604 case Intrinsic::x86_sse2_pslli_q:
9605 NewIntNo = Intrinsic::x86_sse2_psll_q;
9607 case Intrinsic::x86_sse2_psrli_w:
9608 NewIntNo = Intrinsic::x86_sse2_psrl_w;
9610 case Intrinsic::x86_sse2_psrli_d:
9611 NewIntNo = Intrinsic::x86_sse2_psrl_d;
9613 case Intrinsic::x86_sse2_psrli_q:
9614 NewIntNo = Intrinsic::x86_sse2_psrl_q;
9616 case Intrinsic::x86_sse2_psrai_w:
9617 NewIntNo = Intrinsic::x86_sse2_psra_w;
9619 case Intrinsic::x86_sse2_psrai_d:
9620 NewIntNo = Intrinsic::x86_sse2_psra_d;
9622 case Intrinsic::x86_avx2_pslli_w:
9623 NewIntNo = Intrinsic::x86_avx2_psll_w;
9625 case Intrinsic::x86_avx2_pslli_d:
9626 NewIntNo = Intrinsic::x86_avx2_psll_d;
9628 case Intrinsic::x86_avx2_pslli_q:
9629 NewIntNo = Intrinsic::x86_avx2_psll_q;
9631 case Intrinsic::x86_avx2_psrli_w:
9632 NewIntNo = Intrinsic::x86_avx2_psrl_w;
9634 case Intrinsic::x86_avx2_psrli_d:
9635 NewIntNo = Intrinsic::x86_avx2_psrl_d;
9637 case Intrinsic::x86_avx2_psrli_q:
9638 NewIntNo = Intrinsic::x86_avx2_psrl_q;
9640 case Intrinsic::x86_avx2_psrai_w:
9641 NewIntNo = Intrinsic::x86_avx2_psra_w;
9643 case Intrinsic::x86_avx2_psrai_d:
9644 NewIntNo = Intrinsic::x86_avx2_psra_d;
9647 ShAmtVT = MVT::v2i32;
9649 case Intrinsic::x86_mmx_pslli_w:
9650 NewIntNo = Intrinsic::x86_mmx_psll_w;
9652 case Intrinsic::x86_mmx_pslli_d:
9653 NewIntNo = Intrinsic::x86_mmx_psll_d;
9655 case Intrinsic::x86_mmx_pslli_q:
9656 NewIntNo = Intrinsic::x86_mmx_psll_q;
9658 case Intrinsic::x86_mmx_psrli_w:
9659 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9661 case Intrinsic::x86_mmx_psrli_d:
9662 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9664 case Intrinsic::x86_mmx_psrli_q:
9665 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9667 case Intrinsic::x86_mmx_psrai_w:
9668 NewIntNo = Intrinsic::x86_mmx_psra_w;
9670 case Intrinsic::x86_mmx_psrai_d:
9671 NewIntNo = Intrinsic::x86_mmx_psra_d;
9673 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9679 // The vector shift intrinsics with scalars uses 32b shift amounts but
9680 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9684 ShOps[1] = DAG.getConstant(0, MVT::i32);
9685 if (ShAmtVT == MVT::v4i32) {
9686 ShOps[2] = DAG.getUNDEF(MVT::i32);
9687 ShOps[3] = DAG.getUNDEF(MVT::i32);
9688 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9690 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9691 // FIXME this must be lowered to get rid of the invalid type.
9694 EVT VT = Op.getValueType();
9695 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9696 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9697 DAG.getConstant(NewIntNo, MVT::i32),
9698 Op.getOperand(1), ShAmt);
9703 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9704 SelectionDAG &DAG) const {
9705 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9706 MFI->setReturnAddressIsTaken(true);
9708 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9709 DebugLoc dl = Op.getDebugLoc();
9712 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9714 DAG.getConstant(TD->getPointerSize(),
9715 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9716 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9717 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9719 MachinePointerInfo(), false, false, false, 0);
9722 // Just load the return address.
9723 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9724 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9725 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9728 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9729 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9730 MFI->setFrameAddressIsTaken(true);
9732 EVT VT = Op.getValueType();
9733 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9734 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9735 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9736 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9738 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9739 MachinePointerInfo(),
9740 false, false, false, 0);
9744 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9745 SelectionDAG &DAG) const {
9746 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9749 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9750 MachineFunction &MF = DAG.getMachineFunction();
9751 SDValue Chain = Op.getOperand(0);
9752 SDValue Offset = Op.getOperand(1);
9753 SDValue Handler = Op.getOperand(2);
9754 DebugLoc dl = Op.getDebugLoc();
9756 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9757 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9759 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9761 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9762 DAG.getIntPtrConstant(TD->getPointerSize()));
9763 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9764 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9766 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9767 MF.getRegInfo().addLiveOut(StoreAddrReg);
9769 return DAG.getNode(X86ISD::EH_RETURN, dl,
9771 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9774 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9775 SelectionDAG &DAG) const {
9776 return Op.getOperand(0);
9779 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9780 SelectionDAG &DAG) const {
9781 SDValue Root = Op.getOperand(0);
9782 SDValue Trmp = Op.getOperand(1); // trampoline
9783 SDValue FPtr = Op.getOperand(2); // nested function
9784 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9785 DebugLoc dl = Op.getDebugLoc();
9787 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9789 if (Subtarget->is64Bit()) {
9790 SDValue OutChains[6];
9792 // Large code-model.
9793 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
9794 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9796 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9797 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9799 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9801 // Load the pointer to the nested function into R11.
9802 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9803 SDValue Addr = Trmp;
9804 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9805 Addr, MachinePointerInfo(TrmpAddr),
9808 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9809 DAG.getConstant(2, MVT::i64));
9810 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9811 MachinePointerInfo(TrmpAddr, 2),
9814 // Load the 'nest' parameter value into R10.
9815 // R10 is specified in X86CallingConv.td
9816 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9817 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9818 DAG.getConstant(10, MVT::i64));
9819 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9820 Addr, MachinePointerInfo(TrmpAddr, 10),
9823 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9824 DAG.getConstant(12, MVT::i64));
9825 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9826 MachinePointerInfo(TrmpAddr, 12),
9829 // Jump to the nested function.
9830 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9831 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9832 DAG.getConstant(20, MVT::i64));
9833 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9834 Addr, MachinePointerInfo(TrmpAddr, 20),
9837 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9838 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9839 DAG.getConstant(22, MVT::i64));
9840 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9841 MachinePointerInfo(TrmpAddr, 22),
9844 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9846 const Function *Func =
9847 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9848 CallingConv::ID CC = Func->getCallingConv();
9853 llvm_unreachable("Unsupported calling convention");
9854 case CallingConv::C:
9855 case CallingConv::X86_StdCall: {
9856 // Pass 'nest' parameter in ECX.
9857 // Must be kept in sync with X86CallingConv.td
9860 // Check that ECX wasn't needed by an 'inreg' parameter.
9861 FunctionType *FTy = Func->getFunctionType();
9862 const AttrListPtr &Attrs = Func->getAttributes();
9864 if (!Attrs.isEmpty() && !Func->isVarArg()) {
9865 unsigned InRegCount = 0;
9868 for (FunctionType::param_iterator I = FTy->param_begin(),
9869 E = FTy->param_end(); I != E; ++I, ++Idx)
9870 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9871 // FIXME: should only count parameters that are lowered to integers.
9872 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9874 if (InRegCount > 2) {
9875 report_fatal_error("Nest register in use - reduce number of inreg"
9881 case CallingConv::X86_FastCall:
9882 case CallingConv::X86_ThisCall:
9883 case CallingConv::Fast:
9884 // Pass 'nest' parameter in EAX.
9885 // Must be kept in sync with X86CallingConv.td
9890 SDValue OutChains[4];
9893 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9894 DAG.getConstant(10, MVT::i32));
9895 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9897 // This is storing the opcode for MOV32ri.
9898 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9899 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9900 OutChains[0] = DAG.getStore(Root, dl,
9901 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9902 Trmp, MachinePointerInfo(TrmpAddr),
9905 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9906 DAG.getConstant(1, MVT::i32));
9907 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9908 MachinePointerInfo(TrmpAddr, 1),
9911 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9912 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9913 DAG.getConstant(5, MVT::i32));
9914 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9915 MachinePointerInfo(TrmpAddr, 5),
9918 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9919 DAG.getConstant(6, MVT::i32));
9920 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9921 MachinePointerInfo(TrmpAddr, 6),
9924 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9928 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9929 SelectionDAG &DAG) const {
9931 The rounding mode is in bits 11:10 of FPSR, and has the following
9938 FLT_ROUNDS, on the other hand, expects the following:
9945 To perform the conversion, we do:
9946 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9949 MachineFunction &MF = DAG.getMachineFunction();
9950 const TargetMachine &TM = MF.getTarget();
9951 const TargetFrameLowering &TFI = *TM.getFrameLowering();
9952 unsigned StackAlignment = TFI.getStackAlignment();
9953 EVT VT = Op.getValueType();
9954 DebugLoc DL = Op.getDebugLoc();
9956 // Save FP Control Word to stack slot
9957 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9958 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9961 MachineMemOperand *MMO =
9962 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9963 MachineMemOperand::MOStore, 2, 2);
9965 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9966 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9967 DAG.getVTList(MVT::Other),
9968 Ops, 2, MVT::i16, MMO);
9970 // Load FP Control Word from stack slot
9971 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9972 MachinePointerInfo(), false, false, false, 0);
9974 // Transform as necessary
9976 DAG.getNode(ISD::SRL, DL, MVT::i16,
9977 DAG.getNode(ISD::AND, DL, MVT::i16,
9978 CWD, DAG.getConstant(0x800, MVT::i16)),
9979 DAG.getConstant(11, MVT::i8));
9981 DAG.getNode(ISD::SRL, DL, MVT::i16,
9982 DAG.getNode(ISD::AND, DL, MVT::i16,
9983 CWD, DAG.getConstant(0x400, MVT::i16)),
9984 DAG.getConstant(9, MVT::i8));
9987 DAG.getNode(ISD::AND, DL, MVT::i16,
9988 DAG.getNode(ISD::ADD, DL, MVT::i16,
9989 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9990 DAG.getConstant(1, MVT::i16)),
9991 DAG.getConstant(3, MVT::i16));
9994 return DAG.getNode((VT.getSizeInBits() < 16 ?
9995 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9998 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9999 EVT VT = Op.getValueType();
10001 unsigned NumBits = VT.getSizeInBits();
10002 DebugLoc dl = Op.getDebugLoc();
10004 Op = Op.getOperand(0);
10005 if (VT == MVT::i8) {
10006 // Zero extend to i32 since there is not an i8 bsr.
10008 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10011 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10012 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10013 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10015 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10018 DAG.getConstant(NumBits+NumBits-1, OpVT),
10019 DAG.getConstant(X86::COND_E, MVT::i8),
10022 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10024 // Finally xor with NumBits-1.
10025 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10028 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10032 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10033 EVT VT = Op.getValueType();
10035 unsigned NumBits = VT.getSizeInBits();
10036 DebugLoc dl = Op.getDebugLoc();
10038 Op = Op.getOperand(0);
10039 if (VT == MVT::i8) {
10041 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10044 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10045 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10046 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10048 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10051 DAG.getConstant(NumBits, OpVT),
10052 DAG.getConstant(X86::COND_E, MVT::i8),
10055 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10058 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10062 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10063 // ones, and then concatenate the result back.
10064 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10065 EVT VT = Op.getValueType();
10067 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10068 "Unsupported value type for operation");
10070 int NumElems = VT.getVectorNumElements();
10071 DebugLoc dl = Op.getDebugLoc();
10072 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10073 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10075 // Extract the LHS vectors
10076 SDValue LHS = Op.getOperand(0);
10077 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10078 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10080 // Extract the RHS vectors
10081 SDValue RHS = Op.getOperand(1);
10082 SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
10083 SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
10085 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10086 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10088 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10089 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10090 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10093 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10094 assert(Op.getValueType().getSizeInBits() == 256 &&
10095 Op.getValueType().isInteger() &&
10096 "Only handle AVX 256-bit vector integer operation");
10097 return Lower256IntArith(Op, DAG);
10100 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10101 assert(Op.getValueType().getSizeInBits() == 256 &&
10102 Op.getValueType().isInteger() &&
10103 "Only handle AVX 256-bit vector integer operation");
10104 return Lower256IntArith(Op, DAG);
10107 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10108 EVT VT = Op.getValueType();
10110 // Decompose 256-bit ops into smaller 128-bit ops.
10111 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10112 return Lower256IntArith(Op, DAG);
10114 DebugLoc dl = Op.getDebugLoc();
10116 SDValue A = Op.getOperand(0);
10117 SDValue B = Op.getOperand(1);
10119 if (VT == MVT::v4i64) {
10120 assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
10122 // ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
10123 // ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
10124 // ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
10125 // ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
10126 // ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
10128 // AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
10129 // AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
10130 // return AloBlo + AloBhi + AhiBlo;
10132 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10133 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10134 A, DAG.getConstant(32, MVT::i32));
10135 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10136 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10137 B, DAG.getConstant(32, MVT::i32));
10138 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10139 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10141 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10142 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10144 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10145 DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10147 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10148 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10149 AloBhi, DAG.getConstant(32, MVT::i32));
10150 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10151 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10152 AhiBlo, DAG.getConstant(32, MVT::i32));
10153 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10154 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10158 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
10160 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
10161 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
10162 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
10163 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
10164 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
10166 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
10167 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
10168 // return AloBlo + AloBhi + AhiBlo;
10170 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10171 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10172 A, DAG.getConstant(32, MVT::i32));
10173 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10174 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10175 B, DAG.getConstant(32, MVT::i32));
10176 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10177 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10179 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10180 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10182 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10183 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10185 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10186 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10187 AloBhi, DAG.getConstant(32, MVT::i32));
10188 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10189 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10190 AhiBlo, DAG.getConstant(32, MVT::i32));
10191 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10192 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10196 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10198 EVT VT = Op.getValueType();
10199 DebugLoc dl = Op.getDebugLoc();
10200 SDValue R = Op.getOperand(0);
10201 SDValue Amt = Op.getOperand(1);
10202 LLVMContext *Context = DAG.getContext();
10204 if (!Subtarget->hasXMMInt())
10207 // Optimize shl/srl/sra with constant shift amount.
10208 if (isSplatVector(Amt.getNode())) {
10209 SDValue SclrAmt = Amt->getOperand(0);
10210 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10211 uint64_t ShiftAmt = C->getZExtValue();
10213 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10214 // Make a large shift.
10216 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10217 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10218 R, DAG.getConstant(ShiftAmt, MVT::i32));
10219 // Zero out the rightmost bits.
10220 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10222 return DAG.getNode(ISD::AND, dl, VT, SHL,
10223 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10226 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10227 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10228 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10229 R, DAG.getConstant(ShiftAmt, MVT::i32));
10231 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10232 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10233 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10234 R, DAG.getConstant(ShiftAmt, MVT::i32));
10236 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10237 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10238 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10239 R, DAG.getConstant(ShiftAmt, MVT::i32));
10241 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10242 // Make a large shift.
10244 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10245 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10246 R, DAG.getConstant(ShiftAmt, MVT::i32));
10247 // Zero out the leftmost bits.
10248 SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10250 return DAG.getNode(ISD::AND, dl, VT, SRL,
10251 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10254 if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10255 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10256 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10257 R, DAG.getConstant(ShiftAmt, MVT::i32));
10259 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10260 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10261 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10262 R, DAG.getConstant(ShiftAmt, MVT::i32));
10264 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10265 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10266 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10267 R, DAG.getConstant(ShiftAmt, MVT::i32));
10269 if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10270 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10271 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10272 R, DAG.getConstant(ShiftAmt, MVT::i32));
10274 if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10275 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10276 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10277 R, DAG.getConstant(ShiftAmt, MVT::i32));
10279 if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10280 if (ShiftAmt == 7) {
10281 // R s>> 7 === R s< 0
10282 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10283 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10286 // R s>> a === ((R u>> a) ^ m) - m
10287 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10288 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10290 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10291 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10292 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10296 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10297 if (Op.getOpcode() == ISD::SHL) {
10298 // Make a large shift.
10300 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10301 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
10302 R, DAG.getConstant(ShiftAmt, MVT::i32));
10303 // Zero out the rightmost bits.
10304 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10306 return DAG.getNode(ISD::AND, dl, VT, SHL,
10307 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10309 if (Op.getOpcode() == ISD::SRL) {
10310 // Make a large shift.
10312 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10313 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
10314 R, DAG.getConstant(ShiftAmt, MVT::i32));
10315 // Zero out the leftmost bits.
10316 SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10318 return DAG.getNode(ISD::AND, dl, VT, SRL,
10319 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10321 if (Op.getOpcode() == ISD::SRA) {
10322 if (ShiftAmt == 7) {
10323 // R s>> 7 === R s< 0
10324 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10325 return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10328 // R s>> a === ((R u>> a) ^ m) - m
10329 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10330 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10332 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10333 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10334 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10341 // Lower SHL with variable shift amount.
10342 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10343 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10344 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10345 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10347 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10349 std::vector<Constant*> CV(4, CI);
10350 Constant *C = ConstantVector::get(CV);
10351 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10352 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10353 MachinePointerInfo::getConstantPool(),
10354 false, false, false, 16);
10356 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10357 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10358 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10359 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10361 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10363 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10364 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10365 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10367 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
10368 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
10370 std::vector<Constant*> CVM1(16, CM1);
10371 std::vector<Constant*> CVM2(16, CM2);
10372 Constant *C = ConstantVector::get(CVM1);
10373 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10374 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10375 MachinePointerInfo::getConstantPool(),
10376 false, false, false, 16);
10378 // r = pblendv(r, psllw(r & (char16)15, 4), a);
10379 M = DAG.getNode(ISD::AND, dl, VT, R, M);
10380 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10381 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10382 DAG.getConstant(4, MVT::i32));
10383 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10385 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10387 C = ConstantVector::get(CVM2);
10388 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10389 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10390 MachinePointerInfo::getConstantPool(),
10391 false, false, false, 16);
10393 // r = pblendv(r, psllw(r & (char16)63, 2), a);
10394 M = DAG.getNode(ISD::AND, dl, VT, R, M);
10395 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10396 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10397 DAG.getConstant(2, MVT::i32));
10398 R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10400 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10402 // return pblendv(r, r+r, a);
10403 R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10404 R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10408 // Decompose 256-bit shifts into smaller 128-bit shifts.
10409 if (VT.getSizeInBits() == 256) {
10410 int NumElems = VT.getVectorNumElements();
10411 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10412 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10414 // Extract the two vectors
10415 SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10416 SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10419 // Recreate the shift amount vectors
10420 SDValue Amt1, Amt2;
10421 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10422 // Constant shift amount
10423 SmallVector<SDValue, 4> Amt1Csts;
10424 SmallVector<SDValue, 4> Amt2Csts;
10425 for (int i = 0; i < NumElems/2; ++i)
10426 Amt1Csts.push_back(Amt->getOperand(i));
10427 for (int i = NumElems/2; i < NumElems; ++i)
10428 Amt2Csts.push_back(Amt->getOperand(i));
10430 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10431 &Amt1Csts[0], NumElems/2);
10432 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10433 &Amt2Csts[0], NumElems/2);
10435 // Variable shift amount
10436 Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10437 Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10441 // Issue new vector shifts for the smaller types
10442 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10443 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10445 // Concatenate the result back
10446 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10452 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10453 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10454 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10455 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10456 // has only one use.
10457 SDNode *N = Op.getNode();
10458 SDValue LHS = N->getOperand(0);
10459 SDValue RHS = N->getOperand(1);
10460 unsigned BaseOp = 0;
10462 DebugLoc DL = Op.getDebugLoc();
10463 switch (Op.getOpcode()) {
10464 default: llvm_unreachable("Unknown ovf instruction!");
10466 // A subtract of one will be selected as a INC. Note that INC doesn't
10467 // set CF, so we can't do this for UADDO.
10468 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10470 BaseOp = X86ISD::INC;
10471 Cond = X86::COND_O;
10474 BaseOp = X86ISD::ADD;
10475 Cond = X86::COND_O;
10478 BaseOp = X86ISD::ADD;
10479 Cond = X86::COND_B;
10482 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10483 // set CF, so we can't do this for USUBO.
10484 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10486 BaseOp = X86ISD::DEC;
10487 Cond = X86::COND_O;
10490 BaseOp = X86ISD::SUB;
10491 Cond = X86::COND_O;
10494 BaseOp = X86ISD::SUB;
10495 Cond = X86::COND_B;
10498 BaseOp = X86ISD::SMUL;
10499 Cond = X86::COND_O;
10501 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10502 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10504 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10507 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10508 DAG.getConstant(X86::COND_O, MVT::i32),
10509 SDValue(Sum.getNode(), 2));
10511 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10515 // Also sets EFLAGS.
10516 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10517 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10520 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10521 DAG.getConstant(Cond, MVT::i32),
10522 SDValue(Sum.getNode(), 1));
10524 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10527 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10528 DebugLoc dl = Op.getDebugLoc();
10529 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10530 EVT VT = Op.getValueType();
10532 if (Subtarget->hasXMMInt() && VT.isVector()) {
10533 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10534 ExtraVT.getScalarType().getSizeInBits();
10535 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10537 unsigned SHLIntrinsicsID = 0;
10538 unsigned SRAIntrinsicsID = 0;
10539 switch (VT.getSimpleVT().SimpleTy) {
10543 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10544 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10547 SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10548 SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10552 if (!Subtarget->hasAVX())
10554 if (!Subtarget->hasAVX2()) {
10555 // needs to be split
10556 int NumElems = VT.getVectorNumElements();
10557 SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10558 SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10560 // Extract the LHS vectors
10561 SDValue LHS = Op.getOperand(0);
10562 SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10563 SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10565 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10566 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10568 EVT ExtraEltVT = ExtraVT.getVectorElementType();
10569 int ExtraNumElems = ExtraVT.getVectorNumElements();
10570 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10572 SDValue Extra = DAG.getValueType(ExtraVT);
10574 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10575 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10577 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10579 if (VT == MVT::v8i32) {
10580 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_d;
10581 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_d;
10583 SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_w;
10584 SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_w;
10588 SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10589 DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10590 Op.getOperand(0), ShAmt);
10592 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10593 DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10601 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10602 DebugLoc dl = Op.getDebugLoc();
10604 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10605 // There isn't any reason to disable it if the target processor supports it.
10606 if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10607 SDValue Chain = Op.getOperand(0);
10608 SDValue Zero = DAG.getConstant(0, MVT::i32);
10610 DAG.getRegister(X86::ESP, MVT::i32), // Base
10611 DAG.getTargetConstant(1, MVT::i8), // Scale
10612 DAG.getRegister(0, MVT::i32), // Index
10613 DAG.getTargetConstant(0, MVT::i32), // Disp
10614 DAG.getRegister(0, MVT::i32), // Segment.
10619 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10620 array_lengthof(Ops));
10621 return SDValue(Res, 0);
10624 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10626 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10628 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10629 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10630 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10631 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10633 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10634 if (!Op1 && !Op2 && !Op3 && Op4)
10635 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10637 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10638 if (Op1 && !Op2 && !Op3 && !Op4)
10639 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10641 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10643 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10646 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10647 SelectionDAG &DAG) const {
10648 DebugLoc dl = Op.getDebugLoc();
10649 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10650 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10651 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10652 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10654 // The only fence that needs an instruction is a sequentially-consistent
10655 // cross-thread fence.
10656 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10657 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10658 // no-sse2). There isn't any reason to disable it if the target processor
10660 if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10661 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10663 SDValue Chain = Op.getOperand(0);
10664 SDValue Zero = DAG.getConstant(0, MVT::i32);
10666 DAG.getRegister(X86::ESP, MVT::i32), // Base
10667 DAG.getTargetConstant(1, MVT::i8), // Scale
10668 DAG.getRegister(0, MVT::i32), // Index
10669 DAG.getTargetConstant(0, MVT::i32), // Disp
10670 DAG.getRegister(0, MVT::i32), // Segment.
10675 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10676 array_lengthof(Ops));
10677 return SDValue(Res, 0);
10680 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10681 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10685 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10686 EVT T = Op.getValueType();
10687 DebugLoc DL = Op.getDebugLoc();
10690 switch(T.getSimpleVT().SimpleTy) {
10692 assert(false && "Invalid value type!");
10693 case MVT::i8: Reg = X86::AL; size = 1; break;
10694 case MVT::i16: Reg = X86::AX; size = 2; break;
10695 case MVT::i32: Reg = X86::EAX; size = 4; break;
10697 assert(Subtarget->is64Bit() && "Node not type legal!");
10698 Reg = X86::RAX; size = 8;
10701 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10702 Op.getOperand(2), SDValue());
10703 SDValue Ops[] = { cpIn.getValue(0),
10706 DAG.getTargetConstant(size, MVT::i8),
10707 cpIn.getValue(1) };
10708 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10709 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10710 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10713 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10717 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10718 SelectionDAG &DAG) const {
10719 assert(Subtarget->is64Bit() && "Result not type legalized?");
10720 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10721 SDValue TheChain = Op.getOperand(0);
10722 DebugLoc dl = Op.getDebugLoc();
10723 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10724 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10725 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10727 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10728 DAG.getConstant(32, MVT::i8));
10730 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10733 return DAG.getMergeValues(Ops, 2, dl);
10736 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10737 SelectionDAG &DAG) const {
10738 EVT SrcVT = Op.getOperand(0).getValueType();
10739 EVT DstVT = Op.getValueType();
10740 assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10741 Subtarget->hasMMX() && "Unexpected custom BITCAST");
10742 assert((DstVT == MVT::i64 ||
10743 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10744 "Unexpected custom BITCAST");
10745 // i64 <=> MMX conversions are Legal.
10746 if (SrcVT==MVT::i64 && DstVT.isVector())
10748 if (DstVT==MVT::i64 && SrcVT.isVector())
10750 // MMX <=> MMX conversions are Legal.
10751 if (SrcVT.isVector() && DstVT.isVector())
10753 // All other conversions need to be expanded.
10757 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10758 SDNode *Node = Op.getNode();
10759 DebugLoc dl = Node->getDebugLoc();
10760 EVT T = Node->getValueType(0);
10761 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10762 DAG.getConstant(0, T), Node->getOperand(2));
10763 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10764 cast<AtomicSDNode>(Node)->getMemoryVT(),
10765 Node->getOperand(0),
10766 Node->getOperand(1), negOp,
10767 cast<AtomicSDNode>(Node)->getSrcValue(),
10768 cast<AtomicSDNode>(Node)->getAlignment(),
10769 cast<AtomicSDNode>(Node)->getOrdering(),
10770 cast<AtomicSDNode>(Node)->getSynchScope());
10773 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10774 SDNode *Node = Op.getNode();
10775 DebugLoc dl = Node->getDebugLoc();
10776 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10778 // Convert seq_cst store -> xchg
10779 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10780 // FIXME: On 32-bit, store -> fist or movq would be more efficient
10781 // (The only way to get a 16-byte store is cmpxchg16b)
10782 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10783 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10784 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10785 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10786 cast<AtomicSDNode>(Node)->getMemoryVT(),
10787 Node->getOperand(0),
10788 Node->getOperand(1), Node->getOperand(2),
10789 cast<AtomicSDNode>(Node)->getMemOperand(),
10790 cast<AtomicSDNode>(Node)->getOrdering(),
10791 cast<AtomicSDNode>(Node)->getSynchScope());
10792 return Swap.getValue(1);
10794 // Other atomic stores have a simple pattern.
10798 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10799 EVT VT = Op.getNode()->getValueType(0);
10801 // Let legalize expand this if it isn't a legal type yet.
10802 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10805 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10808 bool ExtraOp = false;
10809 switch (Op.getOpcode()) {
10810 default: assert(0 && "Invalid code");
10811 case ISD::ADDC: Opc = X86ISD::ADD; break;
10812 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10813 case ISD::SUBC: Opc = X86ISD::SUB; break;
10814 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10818 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10820 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10821 Op.getOperand(1), Op.getOperand(2));
10824 /// LowerOperation - Provide custom lowering hooks for some operations.
10826 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10827 switch (Op.getOpcode()) {
10828 default: llvm_unreachable("Should not custom lower this!");
10829 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10830 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10831 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10832 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10833 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10834 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
10835 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10836 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10837 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10838 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10839 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10840 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10841 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10842 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10843 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10844 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10845 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10846 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10847 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10848 case ISD::SHL_PARTS:
10849 case ISD::SRA_PARTS:
10850 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
10851 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
10852 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
10853 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
10854 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
10855 case ISD::FABS: return LowerFABS(Op, DAG);
10856 case ISD::FNEG: return LowerFNEG(Op, DAG);
10857 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10858 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
10859 case ISD::SETCC: return LowerSETCC(Op, DAG);
10860 case ISD::SELECT: return LowerSELECT(Op, DAG);
10861 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10862 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
10863 case ISD::VASTART: return LowerVASTART(Op, DAG);
10864 case ISD::VAARG: return LowerVAARG(Op, DAG);
10865 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
10866 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10867 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10868 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10869 case ISD::FRAME_TO_ARGS_OFFSET:
10870 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10871 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10872 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
10873 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
10874 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
10875 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
10876 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
10877 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
10878 case ISD::MUL: return LowerMUL(Op, DAG);
10881 case ISD::SHL: return LowerShift(Op, DAG);
10887 case ISD::UMULO: return LowerXALUO(Op, DAG);
10888 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
10889 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
10893 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10894 case ISD::ADD: return LowerADD(Op, DAG);
10895 case ISD::SUB: return LowerSUB(Op, DAG);
10899 static void ReplaceATOMIC_LOAD(SDNode *Node,
10900 SmallVectorImpl<SDValue> &Results,
10901 SelectionDAG &DAG) {
10902 DebugLoc dl = Node->getDebugLoc();
10903 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10905 // Convert wide load -> cmpxchg8b/cmpxchg16b
10906 // FIXME: On 32-bit, load -> fild or movq would be more efficient
10907 // (The only way to get a 16-byte load is cmpxchg16b)
10908 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10909 SDValue Zero = DAG.getConstant(0, VT);
10910 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10911 Node->getOperand(0),
10912 Node->getOperand(1), Zero, Zero,
10913 cast<AtomicSDNode>(Node)->getMemOperand(),
10914 cast<AtomicSDNode>(Node)->getOrdering(),
10915 cast<AtomicSDNode>(Node)->getSynchScope());
10916 Results.push_back(Swap.getValue(0));
10917 Results.push_back(Swap.getValue(1));
10920 void X86TargetLowering::
10921 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10922 SelectionDAG &DAG, unsigned NewOp) const {
10923 DebugLoc dl = Node->getDebugLoc();
10924 assert (Node->getValueType(0) == MVT::i64 &&
10925 "Only know how to expand i64 atomics");
10927 SDValue Chain = Node->getOperand(0);
10928 SDValue In1 = Node->getOperand(1);
10929 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10930 Node->getOperand(2), DAG.getIntPtrConstant(0));
10931 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10932 Node->getOperand(2), DAG.getIntPtrConstant(1));
10933 SDValue Ops[] = { Chain, In1, In2L, In2H };
10934 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10936 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10937 cast<MemSDNode>(Node)->getMemOperand());
10938 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10939 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10940 Results.push_back(Result.getValue(2));
10943 /// ReplaceNodeResults - Replace a node with an illegal result type
10944 /// with a new node built out of custom code.
10945 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10946 SmallVectorImpl<SDValue>&Results,
10947 SelectionDAG &DAG) const {
10948 DebugLoc dl = N->getDebugLoc();
10949 switch (N->getOpcode()) {
10951 assert(false && "Do not know how to custom type legalize this operation!");
10953 case ISD::SIGN_EXTEND_INREG:
10958 // We don't want to expand or promote these.
10960 case ISD::FP_TO_SINT: {
10961 std::pair<SDValue,SDValue> Vals =
10962 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10963 SDValue FIST = Vals.first, StackSlot = Vals.second;
10964 if (FIST.getNode() != 0) {
10965 EVT VT = N->getValueType(0);
10966 // Return a load from the stack slot.
10967 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10968 MachinePointerInfo(),
10969 false, false, false, 0));
10973 case ISD::READCYCLECOUNTER: {
10974 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10975 SDValue TheChain = N->getOperand(0);
10976 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10977 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10979 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10981 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10982 SDValue Ops[] = { eax, edx };
10983 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10984 Results.push_back(edx.getValue(1));
10987 case ISD::ATOMIC_CMP_SWAP: {
10988 EVT T = N->getValueType(0);
10989 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10990 bool Regs64bit = T == MVT::i128;
10991 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10992 SDValue cpInL, cpInH;
10993 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10994 DAG.getConstant(0, HalfT));
10995 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10996 DAG.getConstant(1, HalfT));
10997 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10998 Regs64bit ? X86::RAX : X86::EAX,
11000 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11001 Regs64bit ? X86::RDX : X86::EDX,
11002 cpInH, cpInL.getValue(1));
11003 SDValue swapInL, swapInH;
11004 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11005 DAG.getConstant(0, HalfT));
11006 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11007 DAG.getConstant(1, HalfT));
11008 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11009 Regs64bit ? X86::RBX : X86::EBX,
11010 swapInL, cpInH.getValue(1));
11011 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11012 Regs64bit ? X86::RCX : X86::ECX,
11013 swapInH, swapInL.getValue(1));
11014 SDValue Ops[] = { swapInH.getValue(0),
11016 swapInH.getValue(1) };
11017 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11018 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11019 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11020 X86ISD::LCMPXCHG8_DAG;
11021 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11023 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11024 Regs64bit ? X86::RAX : X86::EAX,
11025 HalfT, Result.getValue(1));
11026 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11027 Regs64bit ? X86::RDX : X86::EDX,
11028 HalfT, cpOutL.getValue(2));
11029 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11030 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11031 Results.push_back(cpOutH.getValue(1));
11034 case ISD::ATOMIC_LOAD_ADD:
11035 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11037 case ISD::ATOMIC_LOAD_AND:
11038 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11040 case ISD::ATOMIC_LOAD_NAND:
11041 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11043 case ISD::ATOMIC_LOAD_OR:
11044 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11046 case ISD::ATOMIC_LOAD_SUB:
11047 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11049 case ISD::ATOMIC_LOAD_XOR:
11050 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11052 case ISD::ATOMIC_SWAP:
11053 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11055 case ISD::ATOMIC_LOAD:
11056 ReplaceATOMIC_LOAD(N, Results, DAG);
11060 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11062 default: return NULL;
11063 case X86ISD::BSF: return "X86ISD::BSF";
11064 case X86ISD::BSR: return "X86ISD::BSR";
11065 case X86ISD::SHLD: return "X86ISD::SHLD";
11066 case X86ISD::SHRD: return "X86ISD::SHRD";
11067 case X86ISD::FAND: return "X86ISD::FAND";
11068 case X86ISD::FOR: return "X86ISD::FOR";
11069 case X86ISD::FXOR: return "X86ISD::FXOR";
11070 case X86ISD::FSRL: return "X86ISD::FSRL";
11071 case X86ISD::FILD: return "X86ISD::FILD";
11072 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11073 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11074 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11075 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11076 case X86ISD::FLD: return "X86ISD::FLD";
11077 case X86ISD::FST: return "X86ISD::FST";
11078 case X86ISD::CALL: return "X86ISD::CALL";
11079 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11080 case X86ISD::BT: return "X86ISD::BT";
11081 case X86ISD::CMP: return "X86ISD::CMP";
11082 case X86ISD::COMI: return "X86ISD::COMI";
11083 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11084 case X86ISD::SETCC: return "X86ISD::SETCC";
11085 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11086 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11087 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11088 case X86ISD::CMOV: return "X86ISD::CMOV";
11089 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11090 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11091 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11092 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11093 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11094 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11095 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11096 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11097 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11098 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11099 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11100 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11101 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11102 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11103 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11104 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11105 case X86ISD::FHADD: return "X86ISD::FHADD";
11106 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11107 case X86ISD::FMAX: return "X86ISD::FMAX";
11108 case X86ISD::FMIN: return "X86ISD::FMIN";
11109 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11110 case X86ISD::FRCP: return "X86ISD::FRCP";
11111 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11112 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11113 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11114 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11115 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11116 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11117 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11118 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11119 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11120 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11121 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11122 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11123 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11124 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11125 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11126 case X86ISD::VSHL: return "X86ISD::VSHL";
11127 case X86ISD::VSRL: return "X86ISD::VSRL";
11128 case X86ISD::CMPPD: return "X86ISD::CMPPD";
11129 case X86ISD::CMPPS: return "X86ISD::CMPPS";
11130 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
11131 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
11132 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
11133 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
11134 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
11135 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
11136 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
11137 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
11138 case X86ISD::ADD: return "X86ISD::ADD";
11139 case X86ISD::SUB: return "X86ISD::SUB";
11140 case X86ISD::ADC: return "X86ISD::ADC";
11141 case X86ISD::SBB: return "X86ISD::SBB";
11142 case X86ISD::SMUL: return "X86ISD::SMUL";
11143 case X86ISD::UMUL: return "X86ISD::UMUL";
11144 case X86ISD::INC: return "X86ISD::INC";
11145 case X86ISD::DEC: return "X86ISD::DEC";
11146 case X86ISD::OR: return "X86ISD::OR";
11147 case X86ISD::XOR: return "X86ISD::XOR";
11148 case X86ISD::AND: return "X86ISD::AND";
11149 case X86ISD::ANDN: return "X86ISD::ANDN";
11150 case X86ISD::BLSI: return "X86ISD::BLSI";
11151 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11152 case X86ISD::BLSR: return "X86ISD::BLSR";
11153 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11154 case X86ISD::PTEST: return "X86ISD::PTEST";
11155 case X86ISD::TESTP: return "X86ISD::TESTP";
11156 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11157 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11158 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11159 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
11160 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11161 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
11162 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
11163 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
11164 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11165 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11166 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11167 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
11168 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11169 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11170 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11171 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11172 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11173 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
11174 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
11175 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11176 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11177 case X86ISD::UNPCKLP: return "X86ISD::UNPCKLP";
11178 case X86ISD::UNPCKHP: return "X86ISD::UNPCKHP";
11179 case X86ISD::PUNPCKL: return "X86ISD::PUNPCKL";
11180 case X86ISD::PUNPCKH: return "X86ISD::PUNPCKH";
11181 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11182 case X86ISD::VPERMILPS: return "X86ISD::VPERMILPS";
11183 case X86ISD::VPERMILPD: return "X86ISD::VPERMILPD";
11184 case X86ISD::VPERM2F128: return "X86ISD::VPERM2F128";
11185 case X86ISD::VPERM2I128: return "X86ISD::VPERM2I128";
11186 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11187 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11188 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11189 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11190 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11194 // isLegalAddressingMode - Return true if the addressing mode represented
11195 // by AM is legal for this target, for a load/store of the specified type.
11196 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11198 // X86 supports extremely general addressing modes.
11199 CodeModel::Model M = getTargetMachine().getCodeModel();
11200 Reloc::Model R = getTargetMachine().getRelocationModel();
11202 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11203 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11208 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11210 // If a reference to this global requires an extra load, we can't fold it.
11211 if (isGlobalStubReference(GVFlags))
11214 // If BaseGV requires a register for the PIC base, we cannot also have a
11215 // BaseReg specified.
11216 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11219 // If lower 4G is not available, then we must use rip-relative addressing.
11220 if ((M != CodeModel::Small || R != Reloc::Static) &&
11221 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11225 switch (AM.Scale) {
11231 // These scales always work.
11236 // These scales are formed with basereg+scalereg. Only accept if there is
11241 default: // Other stuff never works.
11249 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11250 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11252 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11253 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11254 if (NumBits1 <= NumBits2)
11259 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11260 if (!VT1.isInteger() || !VT2.isInteger())
11262 unsigned NumBits1 = VT1.getSizeInBits();
11263 unsigned NumBits2 = VT2.getSizeInBits();
11264 if (NumBits1 <= NumBits2)
11269 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11270 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11271 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11274 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11275 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11276 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11279 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11280 // i16 instructions are longer (0x66 prefix) and potentially slower.
11281 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11284 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11285 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11286 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11287 /// are assumed to be legal.
11289 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11291 // Very little shuffling can be done for 64-bit vectors right now.
11292 if (VT.getSizeInBits() == 64)
11293 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX());
11295 // FIXME: pshufb, blends, shifts.
11296 return (VT.getVectorNumElements() == 2 ||
11297 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11298 isMOVLMask(M, VT) ||
11299 isSHUFPMask(M, VT) ||
11300 isPSHUFDMask(M, VT) ||
11301 isPSHUFHWMask(M, VT) ||
11302 isPSHUFLWMask(M, VT) ||
11303 isPALIGNRMask(M, VT, Subtarget->hasSSSE3orAVX()) ||
11304 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11305 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11306 isUNPCKL_v_undef_Mask(M, VT) ||
11307 isUNPCKH_v_undef_Mask(M, VT));
11311 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11313 unsigned NumElts = VT.getVectorNumElements();
11314 // FIXME: This collection of masks seems suspect.
11317 if (NumElts == 4 && VT.getSizeInBits() == 128) {
11318 return (isMOVLMask(Mask, VT) ||
11319 isCommutedMOVLMask(Mask, VT, true) ||
11320 isSHUFPMask(Mask, VT) ||
11321 isCommutedSHUFPMask(Mask, VT));
11326 //===----------------------------------------------------------------------===//
11327 // X86 Scheduler Hooks
11328 //===----------------------------------------------------------------------===//
11330 // private utility function
11331 MachineBasicBlock *
11332 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11333 MachineBasicBlock *MBB,
11340 TargetRegisterClass *RC,
11341 bool invSrc) const {
11342 // For the atomic bitwise operator, we generate
11345 // ld t1 = [bitinstr.addr]
11346 // op t2 = t1, [bitinstr.val]
11348 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11350 // fallthrough -->nextMBB
11351 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11352 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11353 MachineFunction::iterator MBBIter = MBB;
11356 /// First build the CFG
11357 MachineFunction *F = MBB->getParent();
11358 MachineBasicBlock *thisMBB = MBB;
11359 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11360 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11361 F->insert(MBBIter, newMBB);
11362 F->insert(MBBIter, nextMBB);
11364 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11365 nextMBB->splice(nextMBB->begin(), thisMBB,
11366 llvm::next(MachineBasicBlock::iterator(bInstr)),
11368 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11370 // Update thisMBB to fall through to newMBB
11371 thisMBB->addSuccessor(newMBB);
11373 // newMBB jumps to itself and fall through to nextMBB
11374 newMBB->addSuccessor(nextMBB);
11375 newMBB->addSuccessor(newMBB);
11377 // Insert instructions into newMBB based on incoming instruction
11378 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11379 "unexpected number of operands");
11380 DebugLoc dl = bInstr->getDebugLoc();
11381 MachineOperand& destOper = bInstr->getOperand(0);
11382 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11383 int numArgs = bInstr->getNumOperands() - 1;
11384 for (int i=0; i < numArgs; ++i)
11385 argOpers[i] = &bInstr->getOperand(i+1);
11387 // x86 address has 4 operands: base, index, scale, and displacement
11388 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11389 int valArgIndx = lastAddrIndx + 1;
11391 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11392 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11393 for (int i=0; i <= lastAddrIndx; ++i)
11394 (*MIB).addOperand(*argOpers[i]);
11396 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11398 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11403 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11404 assert((argOpers[valArgIndx]->isReg() ||
11405 argOpers[valArgIndx]->isImm()) &&
11406 "invalid operand");
11407 if (argOpers[valArgIndx]->isReg())
11408 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11410 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11412 (*MIB).addOperand(*argOpers[valArgIndx]);
11414 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11417 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11418 for (int i=0; i <= lastAddrIndx; ++i)
11419 (*MIB).addOperand(*argOpers[i]);
11421 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11422 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11423 bInstr->memoperands_end());
11425 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11426 MIB.addReg(EAXreg);
11429 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11431 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11435 // private utility function: 64 bit atomics on 32 bit host.
11436 MachineBasicBlock *
11437 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11438 MachineBasicBlock *MBB,
11443 bool invSrc) const {
11444 // For the atomic bitwise operator, we generate
11445 // thisMBB (instructions are in pairs, except cmpxchg8b)
11446 // ld t1,t2 = [bitinstr.addr]
11448 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11449 // op t5, t6 <- out1, out2, [bitinstr.val]
11450 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11451 // mov ECX, EBX <- t5, t6
11452 // mov EAX, EDX <- t1, t2
11453 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11454 // mov t3, t4 <- EAX, EDX
11456 // result in out1, out2
11457 // fallthrough -->nextMBB
11459 const TargetRegisterClass *RC = X86::GR32RegisterClass;
11460 const unsigned LoadOpc = X86::MOV32rm;
11461 const unsigned NotOpc = X86::NOT32r;
11462 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11463 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11464 MachineFunction::iterator MBBIter = MBB;
11467 /// First build the CFG
11468 MachineFunction *F = MBB->getParent();
11469 MachineBasicBlock *thisMBB = MBB;
11470 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11471 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11472 F->insert(MBBIter, newMBB);
11473 F->insert(MBBIter, nextMBB);
11475 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11476 nextMBB->splice(nextMBB->begin(), thisMBB,
11477 llvm::next(MachineBasicBlock::iterator(bInstr)),
11479 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11481 // Update thisMBB to fall through to newMBB
11482 thisMBB->addSuccessor(newMBB);
11484 // newMBB jumps to itself and fall through to nextMBB
11485 newMBB->addSuccessor(nextMBB);
11486 newMBB->addSuccessor(newMBB);
11488 DebugLoc dl = bInstr->getDebugLoc();
11489 // Insert instructions into newMBB based on incoming instruction
11490 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11491 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11492 "unexpected number of operands");
11493 MachineOperand& dest1Oper = bInstr->getOperand(0);
11494 MachineOperand& dest2Oper = bInstr->getOperand(1);
11495 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11496 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11497 argOpers[i] = &bInstr->getOperand(i+2);
11499 // We use some of the operands multiple times, so conservatively just
11500 // clear any kill flags that might be present.
11501 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11502 argOpers[i]->setIsKill(false);
11505 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11506 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11508 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11509 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11510 for (int i=0; i <= lastAddrIndx; ++i)
11511 (*MIB).addOperand(*argOpers[i]);
11512 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11513 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11514 // add 4 to displacement.
11515 for (int i=0; i <= lastAddrIndx-2; ++i)
11516 (*MIB).addOperand(*argOpers[i]);
11517 MachineOperand newOp3 = *(argOpers[3]);
11518 if (newOp3.isImm())
11519 newOp3.setImm(newOp3.getImm()+4);
11521 newOp3.setOffset(newOp3.getOffset()+4);
11522 (*MIB).addOperand(newOp3);
11523 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11525 // t3/4 are defined later, at the bottom of the loop
11526 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11527 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11528 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11529 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11530 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11531 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11533 // The subsequent operations should be using the destination registers of
11534 //the PHI instructions.
11536 t1 = F->getRegInfo().createVirtualRegister(RC);
11537 t2 = F->getRegInfo().createVirtualRegister(RC);
11538 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11539 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11541 t1 = dest1Oper.getReg();
11542 t2 = dest2Oper.getReg();
11545 int valArgIndx = lastAddrIndx + 1;
11546 assert((argOpers[valArgIndx]->isReg() ||
11547 argOpers[valArgIndx]->isImm()) &&
11548 "invalid operand");
11549 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11550 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11551 if (argOpers[valArgIndx]->isReg())
11552 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11554 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11555 if (regOpcL != X86::MOV32rr)
11557 (*MIB).addOperand(*argOpers[valArgIndx]);
11558 assert(argOpers[valArgIndx + 1]->isReg() ==
11559 argOpers[valArgIndx]->isReg());
11560 assert(argOpers[valArgIndx + 1]->isImm() ==
11561 argOpers[valArgIndx]->isImm());
11562 if (argOpers[valArgIndx + 1]->isReg())
11563 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11565 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11566 if (regOpcH != X86::MOV32rr)
11568 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11570 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11572 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11575 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11577 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11580 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11581 for (int i=0; i <= lastAddrIndx; ++i)
11582 (*MIB).addOperand(*argOpers[i]);
11584 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11585 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11586 bInstr->memoperands_end());
11588 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11589 MIB.addReg(X86::EAX);
11590 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11591 MIB.addReg(X86::EDX);
11594 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11596 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11600 // private utility function
11601 MachineBasicBlock *
11602 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11603 MachineBasicBlock *MBB,
11604 unsigned cmovOpc) const {
11605 // For the atomic min/max operator, we generate
11608 // ld t1 = [min/max.addr]
11609 // mov t2 = [min/max.val]
11611 // cmov[cond] t2 = t1
11613 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11615 // fallthrough -->nextMBB
11617 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11618 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11619 MachineFunction::iterator MBBIter = MBB;
11622 /// First build the CFG
11623 MachineFunction *F = MBB->getParent();
11624 MachineBasicBlock *thisMBB = MBB;
11625 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11626 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11627 F->insert(MBBIter, newMBB);
11628 F->insert(MBBIter, nextMBB);
11630 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11631 nextMBB->splice(nextMBB->begin(), thisMBB,
11632 llvm::next(MachineBasicBlock::iterator(mInstr)),
11634 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11636 // Update thisMBB to fall through to newMBB
11637 thisMBB->addSuccessor(newMBB);
11639 // newMBB jumps to newMBB and fall through to nextMBB
11640 newMBB->addSuccessor(nextMBB);
11641 newMBB->addSuccessor(newMBB);
11643 DebugLoc dl = mInstr->getDebugLoc();
11644 // Insert instructions into newMBB based on incoming instruction
11645 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11646 "unexpected number of operands");
11647 MachineOperand& destOper = mInstr->getOperand(0);
11648 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11649 int numArgs = mInstr->getNumOperands() - 1;
11650 for (int i=0; i < numArgs; ++i)
11651 argOpers[i] = &mInstr->getOperand(i+1);
11653 // x86 address has 4 operands: base, index, scale, and displacement
11654 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11655 int valArgIndx = lastAddrIndx + 1;
11657 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11658 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11659 for (int i=0; i <= lastAddrIndx; ++i)
11660 (*MIB).addOperand(*argOpers[i]);
11662 // We only support register and immediate values
11663 assert((argOpers[valArgIndx]->isReg() ||
11664 argOpers[valArgIndx]->isImm()) &&
11665 "invalid operand");
11667 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11668 if (argOpers[valArgIndx]->isReg())
11669 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11671 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11672 (*MIB).addOperand(*argOpers[valArgIndx]);
11674 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11677 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11682 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11683 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11687 // Cmp and exchange if none has modified the memory location
11688 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11689 for (int i=0; i <= lastAddrIndx; ++i)
11690 (*MIB).addOperand(*argOpers[i]);
11692 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11693 (*MIB).setMemRefs(mInstr->memoperands_begin(),
11694 mInstr->memoperands_end());
11696 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11697 MIB.addReg(X86::EAX);
11700 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11702 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
11706 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11707 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11708 // in the .td file.
11709 MachineBasicBlock *
11710 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11711 unsigned numArgs, bool memArg) const {
11712 assert(Subtarget->hasSSE42orAVX() &&
11713 "Target must have SSE4.2 or AVX features enabled");
11715 DebugLoc dl = MI->getDebugLoc();
11716 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11718 if (!Subtarget->hasAVX()) {
11720 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11722 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11725 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11727 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11730 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11731 for (unsigned i = 0; i < numArgs; ++i) {
11732 MachineOperand &Op = MI->getOperand(i+1);
11733 if (!(Op.isReg() && Op.isImplicit()))
11734 MIB.addOperand(Op);
11736 BuildMI(*BB, MI, dl,
11737 TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11738 MI->getOperand(0).getReg())
11739 .addReg(X86::XMM0);
11741 MI->eraseFromParent();
11745 MachineBasicBlock *
11746 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11747 DebugLoc dl = MI->getDebugLoc();
11748 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11750 // Address into RAX/EAX, other two args into ECX, EDX.
11751 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11752 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11753 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11754 for (int i = 0; i < X86::AddrNumOperands; ++i)
11755 MIB.addOperand(MI->getOperand(i));
11757 unsigned ValOps = X86::AddrNumOperands;
11758 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11759 .addReg(MI->getOperand(ValOps).getReg());
11760 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11761 .addReg(MI->getOperand(ValOps+1).getReg());
11763 // The instruction doesn't actually take any operands though.
11764 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11766 MI->eraseFromParent(); // The pseudo is gone now.
11770 MachineBasicBlock *
11771 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11772 DebugLoc dl = MI->getDebugLoc();
11773 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11775 // First arg in ECX, the second in EAX.
11776 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11777 .addReg(MI->getOperand(0).getReg());
11778 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11779 .addReg(MI->getOperand(1).getReg());
11781 // The instruction doesn't actually take any operands though.
11782 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11784 MI->eraseFromParent(); // The pseudo is gone now.
11788 MachineBasicBlock *
11789 X86TargetLowering::EmitVAARG64WithCustomInserter(
11791 MachineBasicBlock *MBB) const {
11792 // Emit va_arg instruction on X86-64.
11794 // Operands to this pseudo-instruction:
11795 // 0 ) Output : destination address (reg)
11796 // 1-5) Input : va_list address (addr, i64mem)
11797 // 6 ) ArgSize : Size (in bytes) of vararg type
11798 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11799 // 8 ) Align : Alignment of type
11800 // 9 ) EFLAGS (implicit-def)
11802 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11803 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11805 unsigned DestReg = MI->getOperand(0).getReg();
11806 MachineOperand &Base = MI->getOperand(1);
11807 MachineOperand &Scale = MI->getOperand(2);
11808 MachineOperand &Index = MI->getOperand(3);
11809 MachineOperand &Disp = MI->getOperand(4);
11810 MachineOperand &Segment = MI->getOperand(5);
11811 unsigned ArgSize = MI->getOperand(6).getImm();
11812 unsigned ArgMode = MI->getOperand(7).getImm();
11813 unsigned Align = MI->getOperand(8).getImm();
11815 // Memory Reference
11816 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11817 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11818 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11820 // Machine Information
11821 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11822 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11823 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11824 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11825 DebugLoc DL = MI->getDebugLoc();
11827 // struct va_list {
11830 // i64 overflow_area (address)
11831 // i64 reg_save_area (address)
11833 // sizeof(va_list) = 24
11834 // alignment(va_list) = 8
11836 unsigned TotalNumIntRegs = 6;
11837 unsigned TotalNumXMMRegs = 8;
11838 bool UseGPOffset = (ArgMode == 1);
11839 bool UseFPOffset = (ArgMode == 2);
11840 unsigned MaxOffset = TotalNumIntRegs * 8 +
11841 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11843 /* Align ArgSize to a multiple of 8 */
11844 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11845 bool NeedsAlign = (Align > 8);
11847 MachineBasicBlock *thisMBB = MBB;
11848 MachineBasicBlock *overflowMBB;
11849 MachineBasicBlock *offsetMBB;
11850 MachineBasicBlock *endMBB;
11852 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
11853 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
11854 unsigned OffsetReg = 0;
11856 if (!UseGPOffset && !UseFPOffset) {
11857 // If we only pull from the overflow region, we don't create a branch.
11858 // We don't need to alter control flow.
11859 OffsetDestReg = 0; // unused
11860 OverflowDestReg = DestReg;
11863 overflowMBB = thisMBB;
11866 // First emit code to check if gp_offset (or fp_offset) is below the bound.
11867 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11868 // If not, pull from overflow_area. (branch to overflowMBB)
11873 // offsetMBB overflowMBB
11878 // Registers for the PHI in endMBB
11879 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11880 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11882 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11883 MachineFunction *MF = MBB->getParent();
11884 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11885 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11886 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11888 MachineFunction::iterator MBBIter = MBB;
11891 // Insert the new basic blocks
11892 MF->insert(MBBIter, offsetMBB);
11893 MF->insert(MBBIter, overflowMBB);
11894 MF->insert(MBBIter, endMBB);
11896 // Transfer the remainder of MBB and its successor edges to endMBB.
11897 endMBB->splice(endMBB->begin(), thisMBB,
11898 llvm::next(MachineBasicBlock::iterator(MI)),
11900 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11902 // Make offsetMBB and overflowMBB successors of thisMBB
11903 thisMBB->addSuccessor(offsetMBB);
11904 thisMBB->addSuccessor(overflowMBB);
11906 // endMBB is a successor of both offsetMBB and overflowMBB
11907 offsetMBB->addSuccessor(endMBB);
11908 overflowMBB->addSuccessor(endMBB);
11910 // Load the offset value into a register
11911 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11912 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11916 .addDisp(Disp, UseFPOffset ? 4 : 0)
11917 .addOperand(Segment)
11918 .setMemRefs(MMOBegin, MMOEnd);
11920 // Check if there is enough room left to pull this argument.
11921 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11923 .addImm(MaxOffset + 8 - ArgSizeA8);
11925 // Branch to "overflowMBB" if offset >= max
11926 // Fall through to "offsetMBB" otherwise
11927 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11928 .addMBB(overflowMBB);
11931 // In offsetMBB, emit code to use the reg_save_area.
11933 assert(OffsetReg != 0);
11935 // Read the reg_save_area address.
11936 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11937 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11942 .addOperand(Segment)
11943 .setMemRefs(MMOBegin, MMOEnd);
11945 // Zero-extend the offset
11946 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11947 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11950 .addImm(X86::sub_32bit);
11952 // Add the offset to the reg_save_area to get the final address.
11953 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11954 .addReg(OffsetReg64)
11955 .addReg(RegSaveReg);
11957 // Compute the offset for the next argument
11958 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11959 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11961 .addImm(UseFPOffset ? 16 : 8);
11963 // Store it back into the va_list.
11964 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11968 .addDisp(Disp, UseFPOffset ? 4 : 0)
11969 .addOperand(Segment)
11970 .addReg(NextOffsetReg)
11971 .setMemRefs(MMOBegin, MMOEnd);
11974 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11979 // Emit code to use overflow area
11982 // Load the overflow_area address into a register.
11983 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11984 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11989 .addOperand(Segment)
11990 .setMemRefs(MMOBegin, MMOEnd);
11992 // If we need to align it, do so. Otherwise, just copy the address
11993 // to OverflowDestReg.
11995 // Align the overflow address
11996 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11997 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11999 // aligned_addr = (addr + (align-1)) & ~(align-1)
12000 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12001 .addReg(OverflowAddrReg)
12004 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12006 .addImm(~(uint64_t)(Align-1));
12008 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12009 .addReg(OverflowAddrReg);
12012 // Compute the next overflow address after this argument.
12013 // (the overflow address should be kept 8-byte aligned)
12014 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12015 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12016 .addReg(OverflowDestReg)
12017 .addImm(ArgSizeA8);
12019 // Store the new overflow address.
12020 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12025 .addOperand(Segment)
12026 .addReg(NextAddrReg)
12027 .setMemRefs(MMOBegin, MMOEnd);
12029 // If we branched, emit the PHI to the front of endMBB.
12031 BuildMI(*endMBB, endMBB->begin(), DL,
12032 TII->get(X86::PHI), DestReg)
12033 .addReg(OffsetDestReg).addMBB(offsetMBB)
12034 .addReg(OverflowDestReg).addMBB(overflowMBB);
12037 // Erase the pseudo instruction
12038 MI->eraseFromParent();
12043 MachineBasicBlock *
12044 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12046 MachineBasicBlock *MBB) const {
12047 // Emit code to save XMM registers to the stack. The ABI says that the
12048 // number of registers to save is given in %al, so it's theoretically
12049 // possible to do an indirect jump trick to avoid saving all of them,
12050 // however this code takes a simpler approach and just executes all
12051 // of the stores if %al is non-zero. It's less code, and it's probably
12052 // easier on the hardware branch predictor, and stores aren't all that
12053 // expensive anyway.
12055 // Create the new basic blocks. One block contains all the XMM stores,
12056 // and one block is the final destination regardless of whether any
12057 // stores were performed.
12058 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12059 MachineFunction *F = MBB->getParent();
12060 MachineFunction::iterator MBBIter = MBB;
12062 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12063 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12064 F->insert(MBBIter, XMMSaveMBB);
12065 F->insert(MBBIter, EndMBB);
12067 // Transfer the remainder of MBB and its successor edges to EndMBB.
12068 EndMBB->splice(EndMBB->begin(), MBB,
12069 llvm::next(MachineBasicBlock::iterator(MI)),
12071 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12073 // The original block will now fall through to the XMM save block.
12074 MBB->addSuccessor(XMMSaveMBB);
12075 // The XMMSaveMBB will fall through to the end block.
12076 XMMSaveMBB->addSuccessor(EndMBB);
12078 // Now add the instructions.
12079 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12080 DebugLoc DL = MI->getDebugLoc();
12082 unsigned CountReg = MI->getOperand(0).getReg();
12083 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12084 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12086 if (!Subtarget->isTargetWin64()) {
12087 // If %al is 0, branch around the XMM save block.
12088 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12089 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12090 MBB->addSuccessor(EndMBB);
12093 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12094 // In the XMM save block, save all the XMM argument registers.
12095 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12096 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12097 MachineMemOperand *MMO =
12098 F->getMachineMemOperand(
12099 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12100 MachineMemOperand::MOStore,
12101 /*Size=*/16, /*Align=*/16);
12102 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12103 .addFrameIndex(RegSaveFrameIndex)
12104 .addImm(/*Scale=*/1)
12105 .addReg(/*IndexReg=*/0)
12106 .addImm(/*Disp=*/Offset)
12107 .addReg(/*Segment=*/0)
12108 .addReg(MI->getOperand(i).getReg())
12109 .addMemOperand(MMO);
12112 MI->eraseFromParent(); // The pseudo instruction is gone now.
12117 MachineBasicBlock *
12118 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12119 MachineBasicBlock *BB) const {
12120 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12121 DebugLoc DL = MI->getDebugLoc();
12123 // To "insert" a SELECT_CC instruction, we actually have to insert the
12124 // diamond control-flow pattern. The incoming instruction knows the
12125 // destination vreg to set, the condition code register to branch on, the
12126 // true/false values to select between, and a branch opcode to use.
12127 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12128 MachineFunction::iterator It = BB;
12134 // cmpTY ccX, r1, r2
12136 // fallthrough --> copy0MBB
12137 MachineBasicBlock *thisMBB = BB;
12138 MachineFunction *F = BB->getParent();
12139 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12140 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12141 F->insert(It, copy0MBB);
12142 F->insert(It, sinkMBB);
12144 // If the EFLAGS register isn't dead in the terminator, then claim that it's
12145 // live into the sink and copy blocks.
12146 if (!MI->killsRegister(X86::EFLAGS)) {
12147 copy0MBB->addLiveIn(X86::EFLAGS);
12148 sinkMBB->addLiveIn(X86::EFLAGS);
12151 // Transfer the remainder of BB and its successor edges to sinkMBB.
12152 sinkMBB->splice(sinkMBB->begin(), BB,
12153 llvm::next(MachineBasicBlock::iterator(MI)),
12155 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12157 // Add the true and fallthrough blocks as its successors.
12158 BB->addSuccessor(copy0MBB);
12159 BB->addSuccessor(sinkMBB);
12161 // Create the conditional branch instruction.
12163 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12164 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12167 // %FalseValue = ...
12168 // # fallthrough to sinkMBB
12169 copy0MBB->addSuccessor(sinkMBB);
12172 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12174 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12175 TII->get(X86::PHI), MI->getOperand(0).getReg())
12176 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12177 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12179 MI->eraseFromParent(); // The pseudo instruction is gone now.
12183 MachineBasicBlock *
12184 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12185 bool Is64Bit) const {
12186 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12187 DebugLoc DL = MI->getDebugLoc();
12188 MachineFunction *MF = BB->getParent();
12189 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12191 assert(EnableSegmentedStacks);
12193 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12194 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12197 // ... [Till the alloca]
12198 // If stacklet is not large enough, jump to mallocMBB
12201 // Allocate by subtracting from RSP
12202 // Jump to continueMBB
12205 // Allocate by call to runtime
12209 // [rest of original BB]
12212 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12213 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12214 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12216 MachineRegisterInfo &MRI = MF->getRegInfo();
12217 const TargetRegisterClass *AddrRegClass =
12218 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12220 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12221 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12222 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12223 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12224 sizeVReg = MI->getOperand(1).getReg(),
12225 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12227 MachineFunction::iterator MBBIter = BB;
12230 MF->insert(MBBIter, bumpMBB);
12231 MF->insert(MBBIter, mallocMBB);
12232 MF->insert(MBBIter, continueMBB);
12234 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12235 (MachineBasicBlock::iterator(MI)), BB->end());
12236 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12238 // Add code to the main basic block to check if the stack limit has been hit,
12239 // and if so, jump to mallocMBB otherwise to bumpMBB.
12240 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12241 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12242 .addReg(tmpSPVReg).addReg(sizeVReg);
12243 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12244 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12245 .addReg(SPLimitVReg);
12246 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12248 // bumpMBB simply decreases the stack pointer, since we know the current
12249 // stacklet has enough space.
12250 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12251 .addReg(SPLimitVReg);
12252 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12253 .addReg(SPLimitVReg);
12254 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12256 // Calls into a routine in libgcc to allocate more space from the heap.
12258 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12260 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12261 .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12263 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12265 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12266 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12267 .addExternalSymbol("__morestack_allocate_stack_space");
12271 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12274 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12275 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12276 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12278 // Set up the CFG correctly.
12279 BB->addSuccessor(bumpMBB);
12280 BB->addSuccessor(mallocMBB);
12281 mallocMBB->addSuccessor(continueMBB);
12282 bumpMBB->addSuccessor(continueMBB);
12284 // Take care of the PHI nodes.
12285 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12286 MI->getOperand(0).getReg())
12287 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12288 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12290 // Delete the original pseudo instruction.
12291 MI->eraseFromParent();
12294 return continueMBB;
12297 MachineBasicBlock *
12298 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12299 MachineBasicBlock *BB) const {
12300 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12301 DebugLoc DL = MI->getDebugLoc();
12303 assert(!Subtarget->isTargetEnvMacho());
12305 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12306 // non-trivial part is impdef of ESP.
12308 if (Subtarget->isTargetWin64()) {
12309 if (Subtarget->isTargetCygMing()) {
12310 // ___chkstk(Mingw64):
12311 // Clobbers R10, R11, RAX and EFLAGS.
12313 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12314 .addExternalSymbol("___chkstk")
12315 .addReg(X86::RAX, RegState::Implicit)
12316 .addReg(X86::RSP, RegState::Implicit)
12317 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12318 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12319 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12321 // __chkstk(MSVCRT): does not update stack pointer.
12322 // Clobbers R10, R11 and EFLAGS.
12323 // FIXME: RAX(allocated size) might be reused and not killed.
12324 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12325 .addExternalSymbol("__chkstk")
12326 .addReg(X86::RAX, RegState::Implicit)
12327 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12328 // RAX has the offset to subtracted from RSP.
12329 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12334 const char *StackProbeSymbol =
12335 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12337 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12338 .addExternalSymbol(StackProbeSymbol)
12339 .addReg(X86::EAX, RegState::Implicit)
12340 .addReg(X86::ESP, RegState::Implicit)
12341 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12342 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12343 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12346 MI->eraseFromParent(); // The pseudo instruction is gone now.
12350 MachineBasicBlock *
12351 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12352 MachineBasicBlock *BB) const {
12353 // This is pretty easy. We're taking the value that we received from
12354 // our load from the relocation, sticking it in either RDI (x86-64)
12355 // or EAX and doing an indirect call. The return value will then
12356 // be in the normal return register.
12357 const X86InstrInfo *TII
12358 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12359 DebugLoc DL = MI->getDebugLoc();
12360 MachineFunction *F = BB->getParent();
12362 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12363 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12365 if (Subtarget->is64Bit()) {
12366 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12367 TII->get(X86::MOV64rm), X86::RDI)
12369 .addImm(0).addReg(0)
12370 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12371 MI->getOperand(3).getTargetFlags())
12373 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12374 addDirectMem(MIB, X86::RDI);
12375 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12376 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12377 TII->get(X86::MOV32rm), X86::EAX)
12379 .addImm(0).addReg(0)
12380 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12381 MI->getOperand(3).getTargetFlags())
12383 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12384 addDirectMem(MIB, X86::EAX);
12386 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12387 TII->get(X86::MOV32rm), X86::EAX)
12388 .addReg(TII->getGlobalBaseReg(F))
12389 .addImm(0).addReg(0)
12390 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12391 MI->getOperand(3).getTargetFlags())
12393 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12394 addDirectMem(MIB, X86::EAX);
12397 MI->eraseFromParent(); // The pseudo instruction is gone now.
12401 MachineBasicBlock *
12402 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12403 MachineBasicBlock *BB) const {
12404 switch (MI->getOpcode()) {
12405 default: assert(0 && "Unexpected instr type to insert");
12406 case X86::TAILJMPd64:
12407 case X86::TAILJMPr64:
12408 case X86::TAILJMPm64:
12409 assert(0 && "TAILJMP64 would not be touched here.");
12410 case X86::TCRETURNdi64:
12411 case X86::TCRETURNri64:
12412 case X86::TCRETURNmi64:
12413 // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12414 // On AMD64, additional defs should be added before register allocation.
12415 if (!Subtarget->isTargetWin64()) {
12416 MI->addRegisterDefined(X86::RSI);
12417 MI->addRegisterDefined(X86::RDI);
12418 MI->addRegisterDefined(X86::XMM6);
12419 MI->addRegisterDefined(X86::XMM7);
12420 MI->addRegisterDefined(X86::XMM8);
12421 MI->addRegisterDefined(X86::XMM9);
12422 MI->addRegisterDefined(X86::XMM10);
12423 MI->addRegisterDefined(X86::XMM11);
12424 MI->addRegisterDefined(X86::XMM12);
12425 MI->addRegisterDefined(X86::XMM13);
12426 MI->addRegisterDefined(X86::XMM14);
12427 MI->addRegisterDefined(X86::XMM15);
12430 case X86::WIN_ALLOCA:
12431 return EmitLoweredWinAlloca(MI, BB);
12432 case X86::SEG_ALLOCA_32:
12433 return EmitLoweredSegAlloca(MI, BB, false);
12434 case X86::SEG_ALLOCA_64:
12435 return EmitLoweredSegAlloca(MI, BB, true);
12436 case X86::TLSCall_32:
12437 case X86::TLSCall_64:
12438 return EmitLoweredTLSCall(MI, BB);
12439 case X86::CMOV_GR8:
12440 case X86::CMOV_FR32:
12441 case X86::CMOV_FR64:
12442 case X86::CMOV_V4F32:
12443 case X86::CMOV_V2F64:
12444 case X86::CMOV_V2I64:
12445 case X86::CMOV_V8F32:
12446 case X86::CMOV_V4F64:
12447 case X86::CMOV_V4I64:
12448 case X86::CMOV_GR16:
12449 case X86::CMOV_GR32:
12450 case X86::CMOV_RFP32:
12451 case X86::CMOV_RFP64:
12452 case X86::CMOV_RFP80:
12453 return EmitLoweredSelect(MI, BB);
12455 case X86::FP32_TO_INT16_IN_MEM:
12456 case X86::FP32_TO_INT32_IN_MEM:
12457 case X86::FP32_TO_INT64_IN_MEM:
12458 case X86::FP64_TO_INT16_IN_MEM:
12459 case X86::FP64_TO_INT32_IN_MEM:
12460 case X86::FP64_TO_INT64_IN_MEM:
12461 case X86::FP80_TO_INT16_IN_MEM:
12462 case X86::FP80_TO_INT32_IN_MEM:
12463 case X86::FP80_TO_INT64_IN_MEM: {
12464 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12465 DebugLoc DL = MI->getDebugLoc();
12467 // Change the floating point control register to use "round towards zero"
12468 // mode when truncating to an integer value.
12469 MachineFunction *F = BB->getParent();
12470 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12471 addFrameReference(BuildMI(*BB, MI, DL,
12472 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12474 // Load the old value of the high byte of the control word...
12476 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12477 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12480 // Set the high part to be round to zero...
12481 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12484 // Reload the modified control word now...
12485 addFrameReference(BuildMI(*BB, MI, DL,
12486 TII->get(X86::FLDCW16m)), CWFrameIdx);
12488 // Restore the memory image of control word to original value
12489 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12492 // Get the X86 opcode to use.
12494 switch (MI->getOpcode()) {
12495 default: llvm_unreachable("illegal opcode!");
12496 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12497 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12498 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12499 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12500 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12501 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12502 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12503 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12504 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12508 MachineOperand &Op = MI->getOperand(0);
12510 AM.BaseType = X86AddressMode::RegBase;
12511 AM.Base.Reg = Op.getReg();
12513 AM.BaseType = X86AddressMode::FrameIndexBase;
12514 AM.Base.FrameIndex = Op.getIndex();
12516 Op = MI->getOperand(1);
12518 AM.Scale = Op.getImm();
12519 Op = MI->getOperand(2);
12521 AM.IndexReg = Op.getImm();
12522 Op = MI->getOperand(3);
12523 if (Op.isGlobal()) {
12524 AM.GV = Op.getGlobal();
12526 AM.Disp = Op.getImm();
12528 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12529 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12531 // Reload the original control word now.
12532 addFrameReference(BuildMI(*BB, MI, DL,
12533 TII->get(X86::FLDCW16m)), CWFrameIdx);
12535 MI->eraseFromParent(); // The pseudo instruction is gone now.
12538 // String/text processing lowering.
12539 case X86::PCMPISTRM128REG:
12540 case X86::VPCMPISTRM128REG:
12541 return EmitPCMP(MI, BB, 3, false /* in-mem */);
12542 case X86::PCMPISTRM128MEM:
12543 case X86::VPCMPISTRM128MEM:
12544 return EmitPCMP(MI, BB, 3, true /* in-mem */);
12545 case X86::PCMPESTRM128REG:
12546 case X86::VPCMPESTRM128REG:
12547 return EmitPCMP(MI, BB, 5, false /* in mem */);
12548 case X86::PCMPESTRM128MEM:
12549 case X86::VPCMPESTRM128MEM:
12550 return EmitPCMP(MI, BB, 5, true /* in mem */);
12552 // Thread synchronization.
12554 return EmitMonitor(MI, BB);
12556 return EmitMwait(MI, BB);
12558 // Atomic Lowering.
12559 case X86::ATOMAND32:
12560 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12561 X86::AND32ri, X86::MOV32rm,
12563 X86::NOT32r, X86::EAX,
12564 X86::GR32RegisterClass);
12565 case X86::ATOMOR32:
12566 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12567 X86::OR32ri, X86::MOV32rm,
12569 X86::NOT32r, X86::EAX,
12570 X86::GR32RegisterClass);
12571 case X86::ATOMXOR32:
12572 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12573 X86::XOR32ri, X86::MOV32rm,
12575 X86::NOT32r, X86::EAX,
12576 X86::GR32RegisterClass);
12577 case X86::ATOMNAND32:
12578 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12579 X86::AND32ri, X86::MOV32rm,
12581 X86::NOT32r, X86::EAX,
12582 X86::GR32RegisterClass, true);
12583 case X86::ATOMMIN32:
12584 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12585 case X86::ATOMMAX32:
12586 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12587 case X86::ATOMUMIN32:
12588 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12589 case X86::ATOMUMAX32:
12590 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12592 case X86::ATOMAND16:
12593 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12594 X86::AND16ri, X86::MOV16rm,
12596 X86::NOT16r, X86::AX,
12597 X86::GR16RegisterClass);
12598 case X86::ATOMOR16:
12599 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12600 X86::OR16ri, X86::MOV16rm,
12602 X86::NOT16r, X86::AX,
12603 X86::GR16RegisterClass);
12604 case X86::ATOMXOR16:
12605 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12606 X86::XOR16ri, X86::MOV16rm,
12608 X86::NOT16r, X86::AX,
12609 X86::GR16RegisterClass);
12610 case X86::ATOMNAND16:
12611 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12612 X86::AND16ri, X86::MOV16rm,
12614 X86::NOT16r, X86::AX,
12615 X86::GR16RegisterClass, true);
12616 case X86::ATOMMIN16:
12617 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12618 case X86::ATOMMAX16:
12619 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12620 case X86::ATOMUMIN16:
12621 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12622 case X86::ATOMUMAX16:
12623 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12625 case X86::ATOMAND8:
12626 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12627 X86::AND8ri, X86::MOV8rm,
12629 X86::NOT8r, X86::AL,
12630 X86::GR8RegisterClass);
12632 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12633 X86::OR8ri, X86::MOV8rm,
12635 X86::NOT8r, X86::AL,
12636 X86::GR8RegisterClass);
12637 case X86::ATOMXOR8:
12638 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12639 X86::XOR8ri, X86::MOV8rm,
12641 X86::NOT8r, X86::AL,
12642 X86::GR8RegisterClass);
12643 case X86::ATOMNAND8:
12644 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12645 X86::AND8ri, X86::MOV8rm,
12647 X86::NOT8r, X86::AL,
12648 X86::GR8RegisterClass, true);
12649 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12650 // This group is for 64-bit host.
12651 case X86::ATOMAND64:
12652 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12653 X86::AND64ri32, X86::MOV64rm,
12655 X86::NOT64r, X86::RAX,
12656 X86::GR64RegisterClass);
12657 case X86::ATOMOR64:
12658 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12659 X86::OR64ri32, X86::MOV64rm,
12661 X86::NOT64r, X86::RAX,
12662 X86::GR64RegisterClass);
12663 case X86::ATOMXOR64:
12664 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12665 X86::XOR64ri32, X86::MOV64rm,
12667 X86::NOT64r, X86::RAX,
12668 X86::GR64RegisterClass);
12669 case X86::ATOMNAND64:
12670 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12671 X86::AND64ri32, X86::MOV64rm,
12673 X86::NOT64r, X86::RAX,
12674 X86::GR64RegisterClass, true);
12675 case X86::ATOMMIN64:
12676 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12677 case X86::ATOMMAX64:
12678 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12679 case X86::ATOMUMIN64:
12680 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12681 case X86::ATOMUMAX64:
12682 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12684 // This group does 64-bit operations on a 32-bit host.
12685 case X86::ATOMAND6432:
12686 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12687 X86::AND32rr, X86::AND32rr,
12688 X86::AND32ri, X86::AND32ri,
12690 case X86::ATOMOR6432:
12691 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12692 X86::OR32rr, X86::OR32rr,
12693 X86::OR32ri, X86::OR32ri,
12695 case X86::ATOMXOR6432:
12696 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12697 X86::XOR32rr, X86::XOR32rr,
12698 X86::XOR32ri, X86::XOR32ri,
12700 case X86::ATOMNAND6432:
12701 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12702 X86::AND32rr, X86::AND32rr,
12703 X86::AND32ri, X86::AND32ri,
12705 case X86::ATOMADD6432:
12706 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12707 X86::ADD32rr, X86::ADC32rr,
12708 X86::ADD32ri, X86::ADC32ri,
12710 case X86::ATOMSUB6432:
12711 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12712 X86::SUB32rr, X86::SBB32rr,
12713 X86::SUB32ri, X86::SBB32ri,
12715 case X86::ATOMSWAP6432:
12716 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12717 X86::MOV32rr, X86::MOV32rr,
12718 X86::MOV32ri, X86::MOV32ri,
12720 case X86::VASTART_SAVE_XMM_REGS:
12721 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12723 case X86::VAARG_64:
12724 return EmitVAARG64WithCustomInserter(MI, BB);
12728 //===----------------------------------------------------------------------===//
12729 // X86 Optimization Hooks
12730 //===----------------------------------------------------------------------===//
12732 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12736 const SelectionDAG &DAG,
12737 unsigned Depth) const {
12738 unsigned Opc = Op.getOpcode();
12739 assert((Opc >= ISD::BUILTIN_OP_END ||
12740 Opc == ISD::INTRINSIC_WO_CHAIN ||
12741 Opc == ISD::INTRINSIC_W_CHAIN ||
12742 Opc == ISD::INTRINSIC_VOID) &&
12743 "Should use MaskedValueIsZero if you don't know whether Op"
12744 " is a target node!");
12746 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
12760 // These nodes' second result is a boolean.
12761 if (Op.getResNo() == 0)
12764 case X86ISD::SETCC:
12765 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12766 Mask.getBitWidth() - 1);
12768 case ISD::INTRINSIC_WO_CHAIN: {
12769 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12770 unsigned NumLoBits = 0;
12773 case Intrinsic::x86_sse_movmsk_ps:
12774 case Intrinsic::x86_avx_movmsk_ps_256:
12775 case Intrinsic::x86_sse2_movmsk_pd:
12776 case Intrinsic::x86_avx_movmsk_pd_256:
12777 case Intrinsic::x86_mmx_pmovmskb:
12778 case Intrinsic::x86_sse2_pmovmskb_128: {
12779 // High bits of movmskp{s|d}, pmovmskb are known zero.
12781 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
12782 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
12783 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
12784 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
12785 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
12786 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
12788 KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12789 Mask.getBitWidth() - NumLoBits);
12798 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12799 unsigned Depth) const {
12800 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12801 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12802 return Op.getValueType().getScalarType().getSizeInBits();
12808 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12809 /// node is a GlobalAddress + offset.
12810 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12811 const GlobalValue* &GA,
12812 int64_t &Offset) const {
12813 if (N->getOpcode() == X86ISD::Wrapper) {
12814 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12815 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12816 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12820 return TargetLowering::isGAPlusOffset(N, GA, Offset);
12823 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12824 /// same as extracting the high 128-bit part of 256-bit vector and then
12825 /// inserting the result into the low part of a new 256-bit vector
12826 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12827 EVT VT = SVOp->getValueType(0);
12828 int NumElems = VT.getVectorNumElements();
12830 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12831 for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12832 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12833 SVOp->getMaskElt(j) >= 0)
12839 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12840 /// same as extracting the low 128-bit part of 256-bit vector and then
12841 /// inserting the result into the high part of a new 256-bit vector
12842 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12843 EVT VT = SVOp->getValueType(0);
12844 int NumElems = VT.getVectorNumElements();
12846 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12847 for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12848 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12849 SVOp->getMaskElt(j) >= 0)
12855 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12856 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12857 TargetLowering::DAGCombinerInfo &DCI) {
12858 DebugLoc dl = N->getDebugLoc();
12859 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12860 SDValue V1 = SVOp->getOperand(0);
12861 SDValue V2 = SVOp->getOperand(1);
12862 EVT VT = SVOp->getValueType(0);
12863 int NumElems = VT.getVectorNumElements();
12865 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12866 V2.getOpcode() == ISD::CONCAT_VECTORS) {
12870 // V UNDEF BUILD_VECTOR UNDEF
12872 // CONCAT_VECTOR CONCAT_VECTOR
12875 // RESULT: V + zero extended
12877 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12878 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12879 V1.getOperand(1).getOpcode() != ISD::UNDEF)
12882 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12885 // To match the shuffle mask, the first half of the mask should
12886 // be exactly the first vector, and all the rest a splat with the
12887 // first element of the second one.
12888 for (int i = 0; i < NumElems/2; ++i)
12889 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12890 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12893 // Emit a zeroed vector and insert the desired subvector on its
12895 SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12896 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12897 DAG.getConstant(0, MVT::i32), DAG, dl);
12898 return DCI.CombineTo(N, InsV);
12901 //===--------------------------------------------------------------------===//
12902 // Combine some shuffles into subvector extracts and inserts:
12905 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12906 if (isShuffleHigh128VectorInsertLow(SVOp)) {
12907 SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12909 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12910 V, DAG.getConstant(0, MVT::i32), DAG, dl);
12911 return DCI.CombineTo(N, InsV);
12914 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12915 if (isShuffleLow128VectorInsertHigh(SVOp)) {
12916 SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12917 SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12918 V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12919 return DCI.CombineTo(N, InsV);
12925 /// PerformShuffleCombine - Performs several different shuffle combines.
12926 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12927 TargetLowering::DAGCombinerInfo &DCI,
12928 const X86Subtarget *Subtarget) {
12929 DebugLoc dl = N->getDebugLoc();
12930 EVT VT = N->getValueType(0);
12932 // Don't create instructions with illegal types after legalize types has run.
12933 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12934 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12937 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12938 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12939 N->getOpcode() == ISD::VECTOR_SHUFFLE)
12940 return PerformShuffleCombine256(N, DAG, DCI);
12942 // Only handle 128 wide vector from here on.
12943 if (VT.getSizeInBits() != 128)
12946 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12947 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12948 // consecutive, non-overlapping, and in the right order.
12949 SmallVector<SDValue, 16> Elts;
12950 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12951 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12953 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12956 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12957 /// generation and convert it from being a bunch of shuffles and extracts
12958 /// to a simple store and scalar loads to extract the elements.
12959 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12960 const TargetLowering &TLI) {
12961 SDValue InputVector = N->getOperand(0);
12963 // Only operate on vectors of 4 elements, where the alternative shuffling
12964 // gets to be more expensive.
12965 if (InputVector.getValueType() != MVT::v4i32)
12968 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12969 // single use which is a sign-extend or zero-extend, and all elements are
12971 SmallVector<SDNode *, 4> Uses;
12972 unsigned ExtractedElements = 0;
12973 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12974 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12975 if (UI.getUse().getResNo() != InputVector.getResNo())
12978 SDNode *Extract = *UI;
12979 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12982 if (Extract->getValueType(0) != MVT::i32)
12984 if (!Extract->hasOneUse())
12986 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12987 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12989 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12992 // Record which element was extracted.
12993 ExtractedElements |=
12994 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12996 Uses.push_back(Extract);
12999 // If not all the elements were used, this may not be worthwhile.
13000 if (ExtractedElements != 15)
13003 // Ok, we've now decided to do the transformation.
13004 DebugLoc dl = InputVector.getDebugLoc();
13006 // Store the value to a temporary stack slot.
13007 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13008 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13009 MachinePointerInfo(), false, false, 0);
13011 // Replace each use (extract) with a load of the appropriate element.
13012 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13013 UE = Uses.end(); UI != UE; ++UI) {
13014 SDNode *Extract = *UI;
13016 // cOMpute the element's address.
13017 SDValue Idx = Extract->getOperand(1);
13019 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13020 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13021 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13023 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13024 StackPtr, OffsetVal);
13026 // Load the scalar.
13027 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13028 ScalarAddr, MachinePointerInfo(),
13029 false, false, false, 0);
13031 // Replace the exact with the load.
13032 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13035 // The replacement was made in place; don't return anything.
13039 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13041 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13042 const X86Subtarget *Subtarget) {
13043 DebugLoc DL = N->getDebugLoc();
13044 SDValue Cond = N->getOperand(0);
13045 // Get the LHS/RHS of the select.
13046 SDValue LHS = N->getOperand(1);
13047 SDValue RHS = N->getOperand(2);
13048 EVT VT = LHS.getValueType();
13050 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13051 // instructions match the semantics of the common C idiom x<y?x:y but not
13052 // x<=y?x:y, because of how they handle negative zero (which can be
13053 // ignored in unsafe-math mode).
13054 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13055 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13056 (Subtarget->hasXMMInt() ||
13057 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13058 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13060 unsigned Opcode = 0;
13061 // Check for x CC y ? x : y.
13062 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13063 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13067 // Converting this to a min would handle NaNs incorrectly, and swapping
13068 // the operands would cause it to handle comparisons between positive
13069 // and negative zero incorrectly.
13070 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13071 if (!UnsafeFPMath &&
13072 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13074 std::swap(LHS, RHS);
13076 Opcode = X86ISD::FMIN;
13079 // Converting this to a min would handle comparisons between positive
13080 // and negative zero incorrectly.
13081 if (!UnsafeFPMath &&
13082 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13084 Opcode = X86ISD::FMIN;
13087 // Converting this to a min would handle both negative zeros and NaNs
13088 // incorrectly, but we can swap the operands to fix both.
13089 std::swap(LHS, RHS);
13093 Opcode = X86ISD::FMIN;
13097 // Converting this to a max would handle comparisons between positive
13098 // and negative zero incorrectly.
13099 if (!UnsafeFPMath &&
13100 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13102 Opcode = X86ISD::FMAX;
13105 // Converting this to a max would handle NaNs incorrectly, and swapping
13106 // the operands would cause it to handle comparisons between positive
13107 // and negative zero incorrectly.
13108 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13109 if (!UnsafeFPMath &&
13110 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13112 std::swap(LHS, RHS);
13114 Opcode = X86ISD::FMAX;
13117 // Converting this to a max would handle both negative zeros and NaNs
13118 // incorrectly, but we can swap the operands to fix both.
13119 std::swap(LHS, RHS);
13123 Opcode = X86ISD::FMAX;
13126 // Check for x CC y ? y : x -- a min/max with reversed arms.
13127 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13128 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13132 // Converting this to a min would handle comparisons between positive
13133 // and negative zero incorrectly, and swapping the operands would
13134 // cause it to handle NaNs incorrectly.
13135 if (!UnsafeFPMath &&
13136 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13137 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13139 std::swap(LHS, RHS);
13141 Opcode = X86ISD::FMIN;
13144 // Converting this to a min would handle NaNs incorrectly.
13145 if (!UnsafeFPMath &&
13146 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13148 Opcode = X86ISD::FMIN;
13151 // Converting this to a min would handle both negative zeros and NaNs
13152 // incorrectly, but we can swap the operands to fix both.
13153 std::swap(LHS, RHS);
13157 Opcode = X86ISD::FMIN;
13161 // Converting this to a max would handle NaNs incorrectly.
13162 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13164 Opcode = X86ISD::FMAX;
13167 // Converting this to a max would handle comparisons between positive
13168 // and negative zero incorrectly, and swapping the operands would
13169 // cause it to handle NaNs incorrectly.
13170 if (!UnsafeFPMath &&
13171 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13172 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13174 std::swap(LHS, RHS);
13176 Opcode = X86ISD::FMAX;
13179 // Converting this to a max would handle both negative zeros and NaNs
13180 // incorrectly, but we can swap the operands to fix both.
13181 std::swap(LHS, RHS);
13185 Opcode = X86ISD::FMAX;
13191 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13194 // If this is a select between two integer constants, try to do some
13196 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13197 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13198 // Don't do this for crazy integer types.
13199 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13200 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13201 // so that TrueC (the true value) is larger than FalseC.
13202 bool NeedsCondInvert = false;
13204 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13205 // Efficiently invertible.
13206 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
13207 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
13208 isa<ConstantSDNode>(Cond.getOperand(1))))) {
13209 NeedsCondInvert = true;
13210 std::swap(TrueC, FalseC);
13213 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
13214 if (FalseC->getAPIntValue() == 0 &&
13215 TrueC->getAPIntValue().isPowerOf2()) {
13216 if (NeedsCondInvert) // Invert the condition if needed.
13217 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13218 DAG.getConstant(1, Cond.getValueType()));
13220 // Zero extend the condition if needed.
13221 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13223 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13224 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13225 DAG.getConstant(ShAmt, MVT::i8));
13228 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13229 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13230 if (NeedsCondInvert) // Invert the condition if needed.
13231 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13232 DAG.getConstant(1, Cond.getValueType()));
13234 // Zero extend the condition if needed.
13235 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13236 FalseC->getValueType(0), Cond);
13237 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13238 SDValue(FalseC, 0));
13241 // Optimize cases that will turn into an LEA instruction. This requires
13242 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13243 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13244 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13245 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13247 bool isFastMultiplier = false;
13249 switch ((unsigned char)Diff) {
13251 case 1: // result = add base, cond
13252 case 2: // result = lea base( , cond*2)
13253 case 3: // result = lea base(cond, cond*2)
13254 case 4: // result = lea base( , cond*4)
13255 case 5: // result = lea base(cond, cond*4)
13256 case 8: // result = lea base( , cond*8)
13257 case 9: // result = lea base(cond, cond*8)
13258 isFastMultiplier = true;
13263 if (isFastMultiplier) {
13264 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13265 if (NeedsCondInvert) // Invert the condition if needed.
13266 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13267 DAG.getConstant(1, Cond.getValueType()));
13269 // Zero extend the condition if needed.
13270 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13272 // Scale the condition by the difference.
13274 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13275 DAG.getConstant(Diff, Cond.getValueType()));
13277 // Add the base if non-zero.
13278 if (FalseC->getAPIntValue() != 0)
13279 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13280 SDValue(FalseC, 0));
13290 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13291 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13292 TargetLowering::DAGCombinerInfo &DCI) {
13293 DebugLoc DL = N->getDebugLoc();
13295 // If the flag operand isn't dead, don't touch this CMOV.
13296 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13299 SDValue FalseOp = N->getOperand(0);
13300 SDValue TrueOp = N->getOperand(1);
13301 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13302 SDValue Cond = N->getOperand(3);
13303 if (CC == X86::COND_E || CC == X86::COND_NE) {
13304 switch (Cond.getOpcode()) {
13308 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13309 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13310 return (CC == X86::COND_E) ? FalseOp : TrueOp;
13314 // If this is a select between two integer constants, try to do some
13315 // optimizations. Note that the operands are ordered the opposite of SELECT
13317 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13318 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13319 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13320 // larger than FalseC (the false value).
13321 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13322 CC = X86::GetOppositeBranchCondition(CC);
13323 std::swap(TrueC, FalseC);
13326 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
13327 // This is efficient for any integer data type (including i8/i16) and
13329 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13330 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13331 DAG.getConstant(CC, MVT::i8), Cond);
13333 // Zero extend the condition if needed.
13334 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13336 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13337 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13338 DAG.getConstant(ShAmt, MVT::i8));
13339 if (N->getNumValues() == 2) // Dead flag value?
13340 return DCI.CombineTo(N, Cond, SDValue());
13344 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
13345 // for any integer data type, including i8/i16.
13346 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13347 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13348 DAG.getConstant(CC, MVT::i8), Cond);
13350 // Zero extend the condition if needed.
13351 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13352 FalseC->getValueType(0), Cond);
13353 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13354 SDValue(FalseC, 0));
13356 if (N->getNumValues() == 2) // Dead flag value?
13357 return DCI.CombineTo(N, Cond, SDValue());
13361 // Optimize cases that will turn into an LEA instruction. This requires
13362 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13363 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13364 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13365 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13367 bool isFastMultiplier = false;
13369 switch ((unsigned char)Diff) {
13371 case 1: // result = add base, cond
13372 case 2: // result = lea base( , cond*2)
13373 case 3: // result = lea base(cond, cond*2)
13374 case 4: // result = lea base( , cond*4)
13375 case 5: // result = lea base(cond, cond*4)
13376 case 8: // result = lea base( , cond*8)
13377 case 9: // result = lea base(cond, cond*8)
13378 isFastMultiplier = true;
13383 if (isFastMultiplier) {
13384 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13385 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13386 DAG.getConstant(CC, MVT::i8), Cond);
13387 // Zero extend the condition if needed.
13388 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13390 // Scale the condition by the difference.
13392 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13393 DAG.getConstant(Diff, Cond.getValueType()));
13395 // Add the base if non-zero.
13396 if (FalseC->getAPIntValue() != 0)
13397 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13398 SDValue(FalseC, 0));
13399 if (N->getNumValues() == 2) // Dead flag value?
13400 return DCI.CombineTo(N, Cond, SDValue());
13410 /// PerformMulCombine - Optimize a single multiply with constant into two
13411 /// in order to implement it with two cheaper instructions, e.g.
13412 /// LEA + SHL, LEA + LEA.
13413 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13414 TargetLowering::DAGCombinerInfo &DCI) {
13415 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13418 EVT VT = N->getValueType(0);
13419 if (VT != MVT::i64)
13422 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13425 uint64_t MulAmt = C->getZExtValue();
13426 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13429 uint64_t MulAmt1 = 0;
13430 uint64_t MulAmt2 = 0;
13431 if ((MulAmt % 9) == 0) {
13433 MulAmt2 = MulAmt / 9;
13434 } else if ((MulAmt % 5) == 0) {
13436 MulAmt2 = MulAmt / 5;
13437 } else if ((MulAmt % 3) == 0) {
13439 MulAmt2 = MulAmt / 3;
13442 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13443 DebugLoc DL = N->getDebugLoc();
13445 if (isPowerOf2_64(MulAmt2) &&
13446 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13447 // If second multiplifer is pow2, issue it first. We want the multiply by
13448 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13450 std::swap(MulAmt1, MulAmt2);
13453 if (isPowerOf2_64(MulAmt1))
13454 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13455 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13457 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13458 DAG.getConstant(MulAmt1, VT));
13460 if (isPowerOf2_64(MulAmt2))
13461 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13462 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13464 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13465 DAG.getConstant(MulAmt2, VT));
13467 // Do not add new nodes to DAG combiner worklist.
13468 DCI.CombineTo(N, NewMul, false);
13473 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13474 SDValue N0 = N->getOperand(0);
13475 SDValue N1 = N->getOperand(1);
13476 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13477 EVT VT = N0.getValueType();
13479 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13480 // since the result of setcc_c is all zero's or all ones.
13481 if (VT.isInteger() && !VT.isVector() &&
13482 N1C && N0.getOpcode() == ISD::AND &&
13483 N0.getOperand(1).getOpcode() == ISD::Constant) {
13484 SDValue N00 = N0.getOperand(0);
13485 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13486 ((N00.getOpcode() == ISD::ANY_EXTEND ||
13487 N00.getOpcode() == ISD::ZERO_EXTEND) &&
13488 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13489 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13490 APInt ShAmt = N1C->getAPIntValue();
13491 Mask = Mask.shl(ShAmt);
13493 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13494 N00, DAG.getConstant(Mask, VT));
13499 // Hardware support for vector shifts is sparse which makes us scalarize the
13500 // vector operations in many cases. Also, on sandybridge ADD is faster than
13502 // (shl V, 1) -> add V,V
13503 if (isSplatVector(N1.getNode())) {
13504 assert(N0.getValueType().isVector() && "Invalid vector shift type");
13505 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13506 // We shift all of the values by one. In many cases we do not have
13507 // hardware support for this operation. This is better expressed as an ADD
13509 if (N1C && (1 == N1C->getZExtValue())) {
13510 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13517 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13519 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13520 const X86Subtarget *Subtarget) {
13521 EVT VT = N->getValueType(0);
13522 if (N->getOpcode() == ISD::SHL) {
13523 SDValue V = PerformSHLCombine(N, DAG);
13524 if (V.getNode()) return V;
13527 // On X86 with SSE2 support, we can transform this to a vector shift if
13528 // all elements are shifted by the same amount. We can't do this in legalize
13529 // because the a constant vector is typically transformed to a constant pool
13530 // so we have no knowledge of the shift amount.
13531 if (!Subtarget->hasXMMInt())
13534 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13535 (!Subtarget->hasAVX2() ||
13536 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13539 SDValue ShAmtOp = N->getOperand(1);
13540 EVT EltVT = VT.getVectorElementType();
13541 DebugLoc DL = N->getDebugLoc();
13542 SDValue BaseShAmt = SDValue();
13543 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13544 unsigned NumElts = VT.getVectorNumElements();
13546 for (; i != NumElts; ++i) {
13547 SDValue Arg = ShAmtOp.getOperand(i);
13548 if (Arg.getOpcode() == ISD::UNDEF) continue;
13552 for (; i != NumElts; ++i) {
13553 SDValue Arg = ShAmtOp.getOperand(i);
13554 if (Arg.getOpcode() == ISD::UNDEF) continue;
13555 if (Arg != BaseShAmt) {
13559 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13560 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13561 SDValue InVec = ShAmtOp.getOperand(0);
13562 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13563 unsigned NumElts = InVec.getValueType().getVectorNumElements();
13565 for (; i != NumElts; ++i) {
13566 SDValue Arg = InVec.getOperand(i);
13567 if (Arg.getOpcode() == ISD::UNDEF) continue;
13571 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13572 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13573 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13574 if (C->getZExtValue() == SplatIdx)
13575 BaseShAmt = InVec.getOperand(1);
13578 if (BaseShAmt.getNode() == 0)
13579 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13580 DAG.getIntPtrConstant(0));
13584 // The shift amount is an i32.
13585 if (EltVT.bitsGT(MVT::i32))
13586 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13587 else if (EltVT.bitsLT(MVT::i32))
13588 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13590 // The shift amount is identical so we can do a vector shift.
13591 SDValue ValOp = N->getOperand(0);
13592 switch (N->getOpcode()) {
13594 llvm_unreachable("Unknown shift opcode!");
13597 if (VT == MVT::v2i64)
13598 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13599 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13601 if (VT == MVT::v4i32)
13602 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13603 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13605 if (VT == MVT::v8i16)
13606 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13607 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13609 if (VT == MVT::v4i64)
13610 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13611 DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
13613 if (VT == MVT::v8i32)
13614 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13615 DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
13617 if (VT == MVT::v16i16)
13618 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13619 DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
13623 if (VT == MVT::v4i32)
13624 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13625 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13627 if (VT == MVT::v8i16)
13628 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13629 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13631 if (VT == MVT::v8i32)
13632 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13633 DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
13635 if (VT == MVT::v16i16)
13636 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13637 DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
13641 if (VT == MVT::v2i64)
13642 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13643 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13645 if (VT == MVT::v4i32)
13646 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13647 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13649 if (VT == MVT::v8i16)
13650 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13651 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13653 if (VT == MVT::v4i64)
13654 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13655 DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
13657 if (VT == MVT::v8i32)
13658 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13659 DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
13661 if (VT == MVT::v16i16)
13662 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13663 DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
13671 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
13672 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13673 // and friends. Likewise for OR -> CMPNEQSS.
13674 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13675 TargetLowering::DAGCombinerInfo &DCI,
13676 const X86Subtarget *Subtarget) {
13679 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13680 // we're requiring SSE2 for both.
13681 if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13682 SDValue N0 = N->getOperand(0);
13683 SDValue N1 = N->getOperand(1);
13684 SDValue CMP0 = N0->getOperand(1);
13685 SDValue CMP1 = N1->getOperand(1);
13686 DebugLoc DL = N->getDebugLoc();
13688 // The SETCCs should both refer to the same CMP.
13689 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13692 SDValue CMP00 = CMP0->getOperand(0);
13693 SDValue CMP01 = CMP0->getOperand(1);
13694 EVT VT = CMP00.getValueType();
13696 if (VT == MVT::f32 || VT == MVT::f64) {
13697 bool ExpectingFlags = false;
13698 // Check for any users that want flags:
13699 for (SDNode::use_iterator UI = N->use_begin(),
13701 !ExpectingFlags && UI != UE; ++UI)
13702 switch (UI->getOpcode()) {
13707 ExpectingFlags = true;
13709 case ISD::CopyToReg:
13710 case ISD::SIGN_EXTEND:
13711 case ISD::ZERO_EXTEND:
13712 case ISD::ANY_EXTEND:
13716 if (!ExpectingFlags) {
13717 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13718 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13720 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13721 X86::CondCode tmp = cc0;
13726 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
13727 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13728 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13729 X86ISD::NodeType NTOperator = is64BitFP ?
13730 X86ISD::FSETCCsd : X86ISD::FSETCCss;
13731 // FIXME: need symbolic constants for these magic numbers.
13732 // See X86ATTInstPrinter.cpp:printSSECC().
13733 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13734 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13735 DAG.getConstant(x86cc, MVT::i8));
13736 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13738 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13739 DAG.getConstant(1, MVT::i32));
13740 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13741 return OneBitOfTruth;
13749 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13750 /// so it can be folded inside ANDNP.
13751 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13752 EVT VT = N->getValueType(0);
13754 // Match direct AllOnes for 128 and 256-bit vectors
13755 if (ISD::isBuildVectorAllOnes(N))
13758 // Look through a bit convert.
13759 if (N->getOpcode() == ISD::BITCAST)
13760 N = N->getOperand(0).getNode();
13762 // Sometimes the operand may come from a insert_subvector building a 256-bit
13764 if (VT.getSizeInBits() == 256 &&
13765 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13766 SDValue V1 = N->getOperand(0);
13767 SDValue V2 = N->getOperand(1);
13769 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13770 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13771 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13772 ISD::isBuildVectorAllOnes(V2.getNode()))
13779 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13780 TargetLowering::DAGCombinerInfo &DCI,
13781 const X86Subtarget *Subtarget) {
13782 if (DCI.isBeforeLegalizeOps())
13785 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13789 EVT VT = N->getValueType(0);
13791 // Create ANDN, BLSI, and BLSR instructions
13792 // BLSI is X & (-X)
13793 // BLSR is X & (X-1)
13794 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13795 SDValue N0 = N->getOperand(0);
13796 SDValue N1 = N->getOperand(1);
13797 DebugLoc DL = N->getDebugLoc();
13799 // Check LHS for not
13800 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13801 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13802 // Check RHS for not
13803 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13804 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13806 // Check LHS for neg
13807 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13808 isZero(N0.getOperand(0)))
13809 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13811 // Check RHS for neg
13812 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13813 isZero(N1.getOperand(0)))
13814 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13816 // Check LHS for X-1
13817 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13818 isAllOnes(N0.getOperand(1)))
13819 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13821 // Check RHS for X-1
13822 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13823 isAllOnes(N1.getOperand(1)))
13824 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13829 // Want to form ANDNP nodes:
13830 // 1) In the hopes of then easily combining them with OR and AND nodes
13831 // to form PBLEND/PSIGN.
13832 // 2) To match ANDN packed intrinsics
13833 if (VT != MVT::v2i64 && VT != MVT::v4i64)
13836 SDValue N0 = N->getOperand(0);
13837 SDValue N1 = N->getOperand(1);
13838 DebugLoc DL = N->getDebugLoc();
13840 // Check LHS for vnot
13841 if (N0.getOpcode() == ISD::XOR &&
13842 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13843 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13844 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13846 // Check RHS for vnot
13847 if (N1.getOpcode() == ISD::XOR &&
13848 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13849 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13850 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13855 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13856 TargetLowering::DAGCombinerInfo &DCI,
13857 const X86Subtarget *Subtarget) {
13858 if (DCI.isBeforeLegalizeOps())
13861 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13865 EVT VT = N->getValueType(0);
13867 SDValue N0 = N->getOperand(0);
13868 SDValue N1 = N->getOperand(1);
13870 // look for psign/blend
13871 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
13872 if (!Subtarget->hasSSSE3orAVX() ||
13873 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
13876 // Canonicalize pandn to RHS
13877 if (N0.getOpcode() == X86ISD::ANDNP)
13879 // or (and (m, x), (pandn m, y))
13880 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13881 SDValue Mask = N1.getOperand(0);
13882 SDValue X = N1.getOperand(1);
13884 if (N0.getOperand(0) == Mask)
13885 Y = N0.getOperand(1);
13886 if (N0.getOperand(1) == Mask)
13887 Y = N0.getOperand(0);
13889 // Check to see if the mask appeared in both the AND and ANDNP and
13893 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13894 if (Mask.getOpcode() != ISD::BITCAST ||
13895 X.getOpcode() != ISD::BITCAST ||
13896 Y.getOpcode() != ISD::BITCAST)
13899 // Look through mask bitcast.
13900 Mask = Mask.getOperand(0);
13901 EVT MaskVT = Mask.getValueType();
13903 // Validate that the Mask operand is a vector sra node. The sra node
13904 // will be an intrinsic.
13905 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13908 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13909 // there is no psrai.b
13910 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13911 case Intrinsic::x86_sse2_psrai_w:
13912 case Intrinsic::x86_sse2_psrai_d:
13913 case Intrinsic::x86_avx2_psrai_w:
13914 case Intrinsic::x86_avx2_psrai_d:
13916 default: return SDValue();
13919 // Check that the SRA is all signbits.
13920 SDValue SraC = Mask.getOperand(2);
13921 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
13922 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13923 if ((SraAmt + 1) != EltBits)
13926 DebugLoc DL = N->getDebugLoc();
13928 // Now we know we at least have a plendvb with the mask val. See if
13929 // we can form a psignb/w/d.
13930 // psign = x.type == y.type == mask.type && y = sub(0, x);
13931 X = X.getOperand(0);
13932 Y = Y.getOperand(0);
13933 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13934 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13935 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType() &&
13936 (EltBits == 8 || EltBits == 16 || EltBits == 32)) {
13937 SDValue Sign = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X,
13938 Mask.getOperand(1));
13939 return DAG.getNode(ISD::BITCAST, DL, VT, Sign);
13941 // PBLENDVB only available on SSE 4.1
13942 if (!Subtarget->hasSSE41orAVX())
13945 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
13947 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
13948 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
13949 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
13950 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, X, Y);
13951 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
13955 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
13958 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13959 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13961 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13963 if (!N0.hasOneUse() || !N1.hasOneUse())
13966 SDValue ShAmt0 = N0.getOperand(1);
13967 if (ShAmt0.getValueType() != MVT::i8)
13969 SDValue ShAmt1 = N1.getOperand(1);
13970 if (ShAmt1.getValueType() != MVT::i8)
13972 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13973 ShAmt0 = ShAmt0.getOperand(0);
13974 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13975 ShAmt1 = ShAmt1.getOperand(0);
13977 DebugLoc DL = N->getDebugLoc();
13978 unsigned Opc = X86ISD::SHLD;
13979 SDValue Op0 = N0.getOperand(0);
13980 SDValue Op1 = N1.getOperand(0);
13981 if (ShAmt0.getOpcode() == ISD::SUB) {
13982 Opc = X86ISD::SHRD;
13983 std::swap(Op0, Op1);
13984 std::swap(ShAmt0, ShAmt1);
13987 unsigned Bits = VT.getSizeInBits();
13988 if (ShAmt1.getOpcode() == ISD::SUB) {
13989 SDValue Sum = ShAmt1.getOperand(0);
13990 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13991 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13992 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13993 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13994 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13995 return DAG.getNode(Opc, DL, VT,
13997 DAG.getNode(ISD::TRUNCATE, DL,
14000 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14001 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14003 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14004 return DAG.getNode(Opc, DL, VT,
14005 N0.getOperand(0), N1.getOperand(0),
14006 DAG.getNode(ISD::TRUNCATE, DL,
14013 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14014 TargetLowering::DAGCombinerInfo &DCI,
14015 const X86Subtarget *Subtarget) {
14016 if (DCI.isBeforeLegalizeOps())
14019 EVT VT = N->getValueType(0);
14021 if (VT != MVT::i32 && VT != MVT::i64)
14024 // Create BLSMSK instructions by finding X ^ (X-1)
14025 SDValue N0 = N->getOperand(0);
14026 SDValue N1 = N->getOperand(1);
14027 DebugLoc DL = N->getDebugLoc();
14029 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14030 isAllOnes(N0.getOperand(1)))
14031 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14033 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14034 isAllOnes(N1.getOperand(1)))
14035 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14040 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14041 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14042 const X86Subtarget *Subtarget) {
14043 LoadSDNode *Ld = cast<LoadSDNode>(N);
14044 EVT RegVT = Ld->getValueType(0);
14045 EVT MemVT = Ld->getMemoryVT();
14046 DebugLoc dl = Ld->getDebugLoc();
14047 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14049 ISD::LoadExtType Ext = Ld->getExtensionType();
14051 // If this is a vector EXT Load then attempt to optimize it using a
14052 // shuffle. We need SSE4 for the shuffles.
14053 // TODO: It is possible to support ZExt by zeroing the undef values
14054 // during the shuffle phase or after the shuffle.
14055 if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14056 assert(MemVT != RegVT && "Cannot extend to the same type");
14057 assert(MemVT.isVector() && "Must load a vector from memory");
14059 unsigned NumElems = RegVT.getVectorNumElements();
14060 unsigned RegSz = RegVT.getSizeInBits();
14061 unsigned MemSz = MemVT.getSizeInBits();
14062 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14063 // All sizes must be a power of two
14064 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
14066 // Attempt to load the original value using a single load op.
14067 // Find a scalar type which is equal to the loaded word size.
14068 MVT SclrLoadTy = MVT::i8;
14069 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14070 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14071 MVT Tp = (MVT::SimpleValueType)tp;
14072 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() == MemSz) {
14078 // Proceed if a load word is found.
14079 if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
14081 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14082 RegSz/SclrLoadTy.getSizeInBits());
14084 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14085 RegSz/MemVT.getScalarType().getSizeInBits());
14086 // Can't shuffle using an illegal type.
14087 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14089 // Perform a single load.
14090 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14092 Ld->getPointerInfo(), Ld->isVolatile(),
14093 Ld->isNonTemporal(), Ld->isInvariant(),
14094 Ld->getAlignment());
14096 // Insert the word loaded into a vector.
14097 SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14098 LoadUnitVecVT, ScalarLoad);
14100 // Bitcast the loaded value to a vector of the original element type, in
14101 // the size of the target vector type.
14102 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
14103 unsigned SizeRatio = RegSz/MemSz;
14105 // Redistribute the loaded elements into the different locations.
14106 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14107 for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
14109 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14110 DAG.getUNDEF(SlicedVec.getValueType()),
14111 ShuffleVec.data());
14113 // Bitcast to the requested type.
14114 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14115 // Replace the original load with the new sequence
14116 // and return the new chain.
14117 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
14118 return SDValue(ScalarLoad.getNode(), 1);
14124 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14125 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14126 const X86Subtarget *Subtarget) {
14127 StoreSDNode *St = cast<StoreSDNode>(N);
14128 EVT VT = St->getValue().getValueType();
14129 EVT StVT = St->getMemoryVT();
14130 DebugLoc dl = St->getDebugLoc();
14131 SDValue StoredVal = St->getOperand(1);
14132 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14134 // If we are saving a concatination of two XMM registers, perform two stores.
14135 // This is better in Sandy Bridge cause one 256-bit mem op is done via two
14136 // 128-bit ones. If in the future the cost becomes only one memory access the
14137 // first version would be better.
14138 if (VT.getSizeInBits() == 256 &&
14139 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14140 StoredVal.getNumOperands() == 2) {
14142 SDValue Value0 = StoredVal.getOperand(0);
14143 SDValue Value1 = StoredVal.getOperand(1);
14145 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14146 SDValue Ptr0 = St->getBasePtr();
14147 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14149 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14150 St->getPointerInfo(), St->isVolatile(),
14151 St->isNonTemporal(), St->getAlignment());
14152 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14153 St->getPointerInfo(), St->isVolatile(),
14154 St->isNonTemporal(), St->getAlignment());
14155 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14158 // Optimize trunc store (of multiple scalars) to shuffle and store.
14159 // First, pack all of the elements in one place. Next, store to memory
14160 // in fewer chunks.
14161 if (St->isTruncatingStore() && VT.isVector()) {
14162 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14163 unsigned NumElems = VT.getVectorNumElements();
14164 assert(StVT != VT && "Cannot truncate to the same type");
14165 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14166 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14168 // From, To sizes and ElemCount must be pow of two
14169 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14170 // We are going to use the original vector elt for storing.
14171 // Accumulated smaller vector elements must be a multiple of the store size.
14172 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14174 unsigned SizeRatio = FromSz / ToSz;
14176 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14178 // Create a type on which we perform the shuffle
14179 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14180 StVT.getScalarType(), NumElems*SizeRatio);
14182 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14184 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14185 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14186 for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
14188 // Can't shuffle using an illegal type
14189 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14191 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14192 DAG.getUNDEF(WideVec.getValueType()),
14193 ShuffleVec.data());
14194 // At this point all of the data is stored at the bottom of the
14195 // register. We now need to save it to mem.
14197 // Find the largest store unit
14198 MVT StoreType = MVT::i8;
14199 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14200 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14201 MVT Tp = (MVT::SimpleValueType)tp;
14202 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14206 // Bitcast the original vector into a vector of store-size units
14207 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14208 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14209 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14210 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14211 SmallVector<SDValue, 8> Chains;
14212 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14213 TLI.getPointerTy());
14214 SDValue Ptr = St->getBasePtr();
14216 // Perform one or more big stores into memory.
14217 for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14218 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14219 StoreType, ShuffWide,
14220 DAG.getIntPtrConstant(i));
14221 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14222 St->getPointerInfo(), St->isVolatile(),
14223 St->isNonTemporal(), St->getAlignment());
14224 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14225 Chains.push_back(Ch);
14228 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14233 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
14234 // the FP state in cases where an emms may be missing.
14235 // A preferable solution to the general problem is to figure out the right
14236 // places to insert EMMS. This qualifies as a quick hack.
14238 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14239 if (VT.getSizeInBits() != 64)
14242 const Function *F = DAG.getMachineFunction().getFunction();
14243 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14244 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
14245 && Subtarget->hasXMMInt();
14246 if ((VT.isVector() ||
14247 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14248 isa<LoadSDNode>(St->getValue()) &&
14249 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14250 St->getChain().hasOneUse() && !St->isVolatile()) {
14251 SDNode* LdVal = St->getValue().getNode();
14252 LoadSDNode *Ld = 0;
14253 int TokenFactorIndex = -1;
14254 SmallVector<SDValue, 8> Ops;
14255 SDNode* ChainVal = St->getChain().getNode();
14256 // Must be a store of a load. We currently handle two cases: the load
14257 // is a direct child, and it's under an intervening TokenFactor. It is
14258 // possible to dig deeper under nested TokenFactors.
14259 if (ChainVal == LdVal)
14260 Ld = cast<LoadSDNode>(St->getChain());
14261 else if (St->getValue().hasOneUse() &&
14262 ChainVal->getOpcode() == ISD::TokenFactor) {
14263 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14264 if (ChainVal->getOperand(i).getNode() == LdVal) {
14265 TokenFactorIndex = i;
14266 Ld = cast<LoadSDNode>(St->getValue());
14268 Ops.push_back(ChainVal->getOperand(i));
14272 if (!Ld || !ISD::isNormalLoad(Ld))
14275 // If this is not the MMX case, i.e. we are just turning i64 load/store
14276 // into f64 load/store, avoid the transformation if there are multiple
14277 // uses of the loaded value.
14278 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14281 DebugLoc LdDL = Ld->getDebugLoc();
14282 DebugLoc StDL = N->getDebugLoc();
14283 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14284 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14286 if (Subtarget->is64Bit() || F64IsLegal) {
14287 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14288 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14289 Ld->getPointerInfo(), Ld->isVolatile(),
14290 Ld->isNonTemporal(), Ld->isInvariant(),
14291 Ld->getAlignment());
14292 SDValue NewChain = NewLd.getValue(1);
14293 if (TokenFactorIndex != -1) {
14294 Ops.push_back(NewChain);
14295 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14298 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14299 St->getPointerInfo(),
14300 St->isVolatile(), St->isNonTemporal(),
14301 St->getAlignment());
14304 // Otherwise, lower to two pairs of 32-bit loads / stores.
14305 SDValue LoAddr = Ld->getBasePtr();
14306 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14307 DAG.getConstant(4, MVT::i32));
14309 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14310 Ld->getPointerInfo(),
14311 Ld->isVolatile(), Ld->isNonTemporal(),
14312 Ld->isInvariant(), Ld->getAlignment());
14313 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14314 Ld->getPointerInfo().getWithOffset(4),
14315 Ld->isVolatile(), Ld->isNonTemporal(),
14317 MinAlign(Ld->getAlignment(), 4));
14319 SDValue NewChain = LoLd.getValue(1);
14320 if (TokenFactorIndex != -1) {
14321 Ops.push_back(LoLd);
14322 Ops.push_back(HiLd);
14323 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14327 LoAddr = St->getBasePtr();
14328 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14329 DAG.getConstant(4, MVT::i32));
14331 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14332 St->getPointerInfo(),
14333 St->isVolatile(), St->isNonTemporal(),
14334 St->getAlignment());
14335 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14336 St->getPointerInfo().getWithOffset(4),
14338 St->isNonTemporal(),
14339 MinAlign(St->getAlignment(), 4));
14340 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14345 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14346 /// and return the operands for the horizontal operation in LHS and RHS. A
14347 /// horizontal operation performs the binary operation on successive elements
14348 /// of its first operand, then on successive elements of its second operand,
14349 /// returning the resulting values in a vector. For example, if
14350 /// A = < float a0, float a1, float a2, float a3 >
14352 /// B = < float b0, float b1, float b2, float b3 >
14353 /// then the result of doing a horizontal operation on A and B is
14354 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14355 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14356 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14357 /// set to A, RHS to B, and the routine returns 'true'.
14358 /// Note that the binary operation should have the property that if one of the
14359 /// operands is UNDEF then the result is UNDEF.
14360 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
14361 // Look for the following pattern: if
14362 // A = < float a0, float a1, float a2, float a3 >
14363 // B = < float b0, float b1, float b2, float b3 >
14365 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14366 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14367 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14368 // which is A horizontal-op B.
14370 // At least one of the operands should be a vector shuffle.
14371 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14372 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14375 EVT VT = LHS.getValueType();
14376 unsigned N = VT.getVectorNumElements();
14378 // View LHS in the form
14379 // LHS = VECTOR_SHUFFLE A, B, LMask
14380 // If LHS is not a shuffle then pretend it is the shuffle
14381 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14382 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14385 SmallVector<int, 8> LMask(N);
14386 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14387 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14388 A = LHS.getOperand(0);
14389 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14390 B = LHS.getOperand(1);
14391 cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14393 if (LHS.getOpcode() != ISD::UNDEF)
14395 for (unsigned i = 0; i != N; ++i)
14399 // Likewise, view RHS in the form
14400 // RHS = VECTOR_SHUFFLE C, D, RMask
14402 SmallVector<int, 8> RMask(N);
14403 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14404 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14405 C = RHS.getOperand(0);
14406 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14407 D = RHS.getOperand(1);
14408 cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14410 if (RHS.getOpcode() != ISD::UNDEF)
14412 for (unsigned i = 0; i != N; ++i)
14416 // Check that the shuffles are both shuffling the same vectors.
14417 if (!(A == C && B == D) && !(A == D && B == C))
14420 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14421 if (!A.getNode() && !B.getNode())
14424 // If A and B occur in reverse order in RHS, then "swap" them (which means
14425 // rewriting the mask).
14427 for (unsigned i = 0; i != N; ++i) {
14428 unsigned Idx = RMask[i];
14431 else if (Idx < 2*N)
14435 // At this point LHS and RHS are equivalent to
14436 // LHS = VECTOR_SHUFFLE A, B, LMask
14437 // RHS = VECTOR_SHUFFLE A, B, RMask
14438 // Check that the masks correspond to performing a horizontal operation.
14439 for (unsigned i = 0; i != N; ++i) {
14440 unsigned LIdx = LMask[i], RIdx = RMask[i];
14442 // Ignore any UNDEF components.
14443 if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
14444 || (!B.getNode() && (LIdx >= N || RIdx >= N)))
14447 // Check that successive elements are being operated on. If not, this is
14448 // not a horizontal operation.
14449 if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
14450 !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
14454 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14455 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14459 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14460 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14461 const X86Subtarget *Subtarget) {
14462 EVT VT = N->getValueType(0);
14463 SDValue LHS = N->getOperand(0);
14464 SDValue RHS = N->getOperand(1);
14466 // Try to synthesize horizontal adds from adds of shuffles.
14467 if (Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14468 isHorizontalBinOp(LHS, RHS, true))
14469 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14473 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14474 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14475 const X86Subtarget *Subtarget) {
14476 EVT VT = N->getValueType(0);
14477 SDValue LHS = N->getOperand(0);
14478 SDValue RHS = N->getOperand(1);
14480 // Try to synthesize horizontal subs from subs of shuffles.
14481 if (Subtarget->hasSSE3orAVX() && (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14482 isHorizontalBinOp(LHS, RHS, false))
14483 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14487 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14488 /// X86ISD::FXOR nodes.
14489 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14490 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14491 // F[X]OR(0.0, x) -> x
14492 // F[X]OR(x, 0.0) -> x
14493 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14494 if (C->getValueAPF().isPosZero())
14495 return N->getOperand(1);
14496 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14497 if (C->getValueAPF().isPosZero())
14498 return N->getOperand(0);
14502 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14503 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14504 // FAND(0.0, x) -> 0.0
14505 // FAND(x, 0.0) -> 0.0
14506 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14507 if (C->getValueAPF().isPosZero())
14508 return N->getOperand(0);
14509 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14510 if (C->getValueAPF().isPosZero())
14511 return N->getOperand(1);
14515 static SDValue PerformBTCombine(SDNode *N,
14517 TargetLowering::DAGCombinerInfo &DCI) {
14518 // BT ignores high bits in the bit index operand.
14519 SDValue Op1 = N->getOperand(1);
14520 if (Op1.hasOneUse()) {
14521 unsigned BitWidth = Op1.getValueSizeInBits();
14522 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14523 APInt KnownZero, KnownOne;
14524 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14525 !DCI.isBeforeLegalizeOps());
14526 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14527 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14528 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14529 DCI.CommitTargetLoweringOpt(TLO);
14534 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14535 SDValue Op = N->getOperand(0);
14536 if (Op.getOpcode() == ISD::BITCAST)
14537 Op = Op.getOperand(0);
14538 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14539 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14540 VT.getVectorElementType().getSizeInBits() ==
14541 OpVT.getVectorElementType().getSizeInBits()) {
14542 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14547 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14548 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
14549 // (and (i32 x86isd::setcc_carry), 1)
14550 // This eliminates the zext. This transformation is necessary because
14551 // ISD::SETCC is always legalized to i8.
14552 DebugLoc dl = N->getDebugLoc();
14553 SDValue N0 = N->getOperand(0);
14554 EVT VT = N->getValueType(0);
14555 if (N0.getOpcode() == ISD::AND &&
14557 N0.getOperand(0).hasOneUse()) {
14558 SDValue N00 = N0.getOperand(0);
14559 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14561 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14562 if (!C || C->getZExtValue() != 1)
14564 return DAG.getNode(ISD::AND, dl, VT,
14565 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14566 N00.getOperand(0), N00.getOperand(1)),
14567 DAG.getConstant(1, VT));
14573 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14574 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14575 unsigned X86CC = N->getConstantOperandVal(0);
14576 SDValue EFLAG = N->getOperand(1);
14577 DebugLoc DL = N->getDebugLoc();
14579 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14580 // a zext and produces an all-ones bit which is more useful than 0/1 in some
14582 if (X86CC == X86::COND_B)
14583 return DAG.getNode(ISD::AND, DL, MVT::i8,
14584 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14585 DAG.getConstant(X86CC, MVT::i8), EFLAG),
14586 DAG.getConstant(1, MVT::i8));
14591 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14592 const X86TargetLowering *XTLI) {
14593 SDValue Op0 = N->getOperand(0);
14594 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14595 // a 32-bit target where SSE doesn't support i64->FP operations.
14596 if (Op0.getOpcode() == ISD::LOAD) {
14597 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14598 EVT VT = Ld->getValueType(0);
14599 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14600 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14601 !XTLI->getSubtarget()->is64Bit() &&
14602 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14603 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14604 Ld->getChain(), Op0, DAG);
14605 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14612 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14613 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14614 X86TargetLowering::DAGCombinerInfo &DCI) {
14615 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14616 // the result is either zero or one (depending on the input carry bit).
14617 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14618 if (X86::isZeroNode(N->getOperand(0)) &&
14619 X86::isZeroNode(N->getOperand(1)) &&
14620 // We don't have a good way to replace an EFLAGS use, so only do this when
14622 SDValue(N, 1).use_empty()) {
14623 DebugLoc DL = N->getDebugLoc();
14624 EVT VT = N->getValueType(0);
14625 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14626 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14627 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14628 DAG.getConstant(X86::COND_B,MVT::i8),
14630 DAG.getConstant(1, VT));
14631 return DCI.CombineTo(N, Res1, CarryOut);
14637 // fold (add Y, (sete X, 0)) -> adc 0, Y
14638 // (add Y, (setne X, 0)) -> sbb -1, Y
14639 // (sub (sete X, 0), Y) -> sbb 0, Y
14640 // (sub (setne X, 0), Y) -> adc -1, Y
14641 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14642 DebugLoc DL = N->getDebugLoc();
14644 // Look through ZExts.
14645 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14646 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14649 SDValue SetCC = Ext.getOperand(0);
14650 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14653 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14654 if (CC != X86::COND_E && CC != X86::COND_NE)
14657 SDValue Cmp = SetCC.getOperand(1);
14658 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14659 !X86::isZeroNode(Cmp.getOperand(1)) ||
14660 !Cmp.getOperand(0).getValueType().isInteger())
14663 SDValue CmpOp0 = Cmp.getOperand(0);
14664 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14665 DAG.getConstant(1, CmpOp0.getValueType()));
14667 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14668 if (CC == X86::COND_NE)
14669 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14670 DL, OtherVal.getValueType(), OtherVal,
14671 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14672 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14673 DL, OtherVal.getValueType(), OtherVal,
14674 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14677 /// PerformADDCombine - Do target-specific dag combines on integer adds.
14678 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
14679 const X86Subtarget *Subtarget) {
14680 EVT VT = N->getValueType(0);
14681 SDValue Op0 = N->getOperand(0);
14682 SDValue Op1 = N->getOperand(1);
14684 // Try to synthesize horizontal adds from adds of shuffles.
14685 if ((Subtarget->hasSSSE3orAVX()) && (VT == MVT::v8i16 || VT == MVT::v4i32) &&
14686 isHorizontalBinOp(Op0, Op1, true))
14687 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
14689 return OptimizeConditionalInDecrement(N, DAG);
14692 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
14693 const X86Subtarget *Subtarget) {
14694 SDValue Op0 = N->getOperand(0);
14695 SDValue Op1 = N->getOperand(1);
14697 // X86 can't encode an immediate LHS of a sub. See if we can push the
14698 // negation into a preceding instruction.
14699 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14700 // If the RHS of the sub is a XOR with one use and a constant, invert the
14701 // immediate. Then add one to the LHS of the sub so we can turn
14702 // X-Y -> X+~Y+1, saving one register.
14703 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14704 isa<ConstantSDNode>(Op1.getOperand(1))) {
14705 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14706 EVT VT = Op0.getValueType();
14707 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14709 DAG.getConstant(~XorC, VT));
14710 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14711 DAG.getConstant(C->getAPIntValue()+1, VT));
14715 // Try to synthesize horizontal adds from adds of shuffles.
14716 EVT VT = N->getValueType(0);
14717 if ((Subtarget->hasSSSE3orAVX()) && (VT == MVT::v8i16 || VT == MVT::v4i32) &&
14718 isHorizontalBinOp(Op0, Op1, false))
14719 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
14721 return OptimizeConditionalInDecrement(N, DAG);
14724 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14725 DAGCombinerInfo &DCI) const {
14726 SelectionDAG &DAG = DCI.DAG;
14727 switch (N->getOpcode()) {
14729 case ISD::EXTRACT_VECTOR_ELT:
14730 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14732 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
14733 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
14734 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
14735 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
14736 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
14737 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
14740 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
14741 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
14742 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
14743 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
14744 case ISD::LOAD: return PerformLOADCombine(N, DAG, Subtarget);
14745 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
14746 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
14747 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
14748 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
14750 case X86ISD::FOR: return PerformFORCombine(N, DAG);
14751 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
14752 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
14753 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
14754 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
14755 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
14756 case X86ISD::SHUFPS: // Handle all target specific shuffles
14757 case X86ISD::SHUFPD:
14758 case X86ISD::PALIGN:
14759 case X86ISD::PUNPCKH:
14760 case X86ISD::UNPCKHP:
14761 case X86ISD::PUNPCKL:
14762 case X86ISD::UNPCKLP:
14763 case X86ISD::MOVHLPS:
14764 case X86ISD::MOVLHPS:
14765 case X86ISD::PSHUFD:
14766 case X86ISD::PSHUFHW:
14767 case X86ISD::PSHUFLW:
14768 case X86ISD::MOVSS:
14769 case X86ISD::MOVSD:
14770 case X86ISD::VPERMILPS:
14771 case X86ISD::VPERMILPD:
14772 case X86ISD::VPERM2F128:
14773 case X86ISD::VPERM2I128:
14774 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14780 /// isTypeDesirableForOp - Return true if the target has native support for
14781 /// the specified value type and it is 'desirable' to use the type for the
14782 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14783 /// instruction encodings are longer and some i16 instructions are slow.
14784 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14785 if (!isTypeLegal(VT))
14787 if (VT != MVT::i16)
14794 case ISD::SIGN_EXTEND:
14795 case ISD::ZERO_EXTEND:
14796 case ISD::ANY_EXTEND:
14809 /// IsDesirableToPromoteOp - This method query the target whether it is
14810 /// beneficial for dag combiner to promote the specified node. If true, it
14811 /// should return the desired promotion type by reference.
14812 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14813 EVT VT = Op.getValueType();
14814 if (VT != MVT::i16)
14817 bool Promote = false;
14818 bool Commute = false;
14819 switch (Op.getOpcode()) {
14822 LoadSDNode *LD = cast<LoadSDNode>(Op);
14823 // If the non-extending load has a single use and it's not live out, then it
14824 // might be folded.
14825 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14826 Op.hasOneUse()*/) {
14827 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14828 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14829 // The only case where we'd want to promote LOAD (rather then it being
14830 // promoted as an operand is when it's only use is liveout.
14831 if (UI->getOpcode() != ISD::CopyToReg)
14838 case ISD::SIGN_EXTEND:
14839 case ISD::ZERO_EXTEND:
14840 case ISD::ANY_EXTEND:
14845 SDValue N0 = Op.getOperand(0);
14846 // Look out for (store (shl (load), x)).
14847 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14860 SDValue N0 = Op.getOperand(0);
14861 SDValue N1 = Op.getOperand(1);
14862 if (!Commute && MayFoldLoad(N1))
14864 // Avoid disabling potential load folding opportunities.
14865 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14867 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14877 //===----------------------------------------------------------------------===//
14878 // X86 Inline Assembly Support
14879 //===----------------------------------------------------------------------===//
14881 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14882 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14884 std::string AsmStr = IA->getAsmString();
14886 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14887 SmallVector<StringRef, 4> AsmPieces;
14888 SplitString(AsmStr, AsmPieces, ";\n");
14890 switch (AsmPieces.size()) {
14891 default: return false;
14893 AsmStr = AsmPieces[0];
14895 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
14897 // FIXME: this should verify that we are targeting a 486 or better. If not,
14898 // we will turn this bswap into something that will be lowered to logical ops
14899 // instead of emitting the bswap asm. For now, we don't support 486 or lower
14900 // so don't worry about this.
14902 if (AsmPieces.size() == 2 &&
14903 (AsmPieces[0] == "bswap" ||
14904 AsmPieces[0] == "bswapq" ||
14905 AsmPieces[0] == "bswapl") &&
14906 (AsmPieces[1] == "$0" ||
14907 AsmPieces[1] == "${0:q}")) {
14908 // No need to check constraints, nothing other than the equivalent of
14909 // "=r,0" would be valid here.
14910 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14911 if (!Ty || Ty->getBitWidth() % 16 != 0)
14913 return IntrinsicLowering::LowerToByteSwap(CI);
14915 // rorw $$8, ${0:w} --> llvm.bswap.i16
14916 if (CI->getType()->isIntegerTy(16) &&
14917 AsmPieces.size() == 3 &&
14918 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14919 AsmPieces[1] == "$$8," &&
14920 AsmPieces[2] == "${0:w}" &&
14921 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14923 const std::string &ConstraintsStr = IA->getConstraintString();
14924 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14925 std::sort(AsmPieces.begin(), AsmPieces.end());
14926 if (AsmPieces.size() == 4 &&
14927 AsmPieces[0] == "~{cc}" &&
14928 AsmPieces[1] == "~{dirflag}" &&
14929 AsmPieces[2] == "~{flags}" &&
14930 AsmPieces[3] == "~{fpsr}") {
14931 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14932 if (!Ty || Ty->getBitWidth() % 16 != 0)
14934 return IntrinsicLowering::LowerToByteSwap(CI);
14939 if (CI->getType()->isIntegerTy(32) &&
14940 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14941 SmallVector<StringRef, 4> Words;
14942 SplitString(AsmPieces[0], Words, " \t,");
14943 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14944 Words[2] == "${0:w}") {
14946 SplitString(AsmPieces[1], Words, " \t,");
14947 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14948 Words[2] == "$0") {
14950 SplitString(AsmPieces[2], Words, " \t,");
14951 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14952 Words[2] == "${0:w}") {
14954 const std::string &ConstraintsStr = IA->getConstraintString();
14955 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14956 std::sort(AsmPieces.begin(), AsmPieces.end());
14957 if (AsmPieces.size() == 4 &&
14958 AsmPieces[0] == "~{cc}" &&
14959 AsmPieces[1] == "~{dirflag}" &&
14960 AsmPieces[2] == "~{flags}" &&
14961 AsmPieces[3] == "~{fpsr}") {
14962 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14963 if (!Ty || Ty->getBitWidth() % 16 != 0)
14965 return IntrinsicLowering::LowerToByteSwap(CI);
14972 if (CI->getType()->isIntegerTy(64)) {
14973 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14974 if (Constraints.size() >= 2 &&
14975 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14976 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14977 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
14978 SmallVector<StringRef, 4> Words;
14979 SplitString(AsmPieces[0], Words, " \t");
14980 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14982 SplitString(AsmPieces[1], Words, " \t");
14983 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14985 SplitString(AsmPieces[2], Words, " \t,");
14986 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14987 Words[2] == "%edx") {
14988 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14989 if (!Ty || Ty->getBitWidth() % 16 != 0)
14991 return IntrinsicLowering::LowerToByteSwap(CI);
15004 /// getConstraintType - Given a constraint letter, return the type of
15005 /// constraint it is for this target.
15006 X86TargetLowering::ConstraintType
15007 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15008 if (Constraint.size() == 1) {
15009 switch (Constraint[0]) {
15020 return C_RegisterClass;
15044 return TargetLowering::getConstraintType(Constraint);
15047 /// Examine constraint type and operand type and determine a weight value.
15048 /// This object must already have been set up with the operand type
15049 /// and the current alternative constraint selected.
15050 TargetLowering::ConstraintWeight
15051 X86TargetLowering::getSingleConstraintMatchWeight(
15052 AsmOperandInfo &info, const char *constraint) const {
15053 ConstraintWeight weight = CW_Invalid;
15054 Value *CallOperandVal = info.CallOperandVal;
15055 // If we don't have a value, we can't do a match,
15056 // but allow it at the lowest weight.
15057 if (CallOperandVal == NULL)
15059 Type *type = CallOperandVal->getType();
15060 // Look at the constraint type.
15061 switch (*constraint) {
15063 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15074 if (CallOperandVal->getType()->isIntegerTy())
15075 weight = CW_SpecificReg;
15080 if (type->isFloatingPointTy())
15081 weight = CW_SpecificReg;
15084 if (type->isX86_MMXTy() && Subtarget->hasMMX())
15085 weight = CW_SpecificReg;
15089 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
15090 weight = CW_Register;
15093 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15094 if (C->getZExtValue() <= 31)
15095 weight = CW_Constant;
15099 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15100 if (C->getZExtValue() <= 63)
15101 weight = CW_Constant;
15105 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15106 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15107 weight = CW_Constant;
15111 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15112 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15113 weight = CW_Constant;
15117 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15118 if (C->getZExtValue() <= 3)
15119 weight = CW_Constant;
15123 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15124 if (C->getZExtValue() <= 0xff)
15125 weight = CW_Constant;
15130 if (dyn_cast<ConstantFP>(CallOperandVal)) {
15131 weight = CW_Constant;
15135 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15136 if ((C->getSExtValue() >= -0x80000000LL) &&
15137 (C->getSExtValue() <= 0x7fffffffLL))
15138 weight = CW_Constant;
15142 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15143 if (C->getZExtValue() <= 0xffffffff)
15144 weight = CW_Constant;
15151 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15152 /// with another that has more specific requirements based on the type of the
15153 /// corresponding operand.
15154 const char *X86TargetLowering::
15155 LowerXConstraint(EVT ConstraintVT) const {
15156 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15157 // 'f' like normal targets.
15158 if (ConstraintVT.isFloatingPoint()) {
15159 if (Subtarget->hasXMMInt())
15161 if (Subtarget->hasXMM())
15165 return TargetLowering::LowerXConstraint(ConstraintVT);
15168 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15169 /// vector. If it is invalid, don't add anything to Ops.
15170 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15171 std::string &Constraint,
15172 std::vector<SDValue>&Ops,
15173 SelectionDAG &DAG) const {
15174 SDValue Result(0, 0);
15176 // Only support length 1 constraints for now.
15177 if (Constraint.length() > 1) return;
15179 char ConstraintLetter = Constraint[0];
15180 switch (ConstraintLetter) {
15183 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15184 if (C->getZExtValue() <= 31) {
15185 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15191 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15192 if (C->getZExtValue() <= 63) {
15193 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15199 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15200 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15201 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15207 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15208 if (C->getZExtValue() <= 255) {
15209 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15215 // 32-bit signed value
15216 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15217 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15218 C->getSExtValue())) {
15219 // Widen to 64 bits here to get it sign extended.
15220 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15223 // FIXME gcc accepts some relocatable values here too, but only in certain
15224 // memory models; it's complicated.
15229 // 32-bit unsigned value
15230 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15231 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15232 C->getZExtValue())) {
15233 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15237 // FIXME gcc accepts some relocatable values here too, but only in certain
15238 // memory models; it's complicated.
15242 // Literal immediates are always ok.
15243 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15244 // Widen to 64 bits here to get it sign extended.
15245 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15249 // In any sort of PIC mode addresses need to be computed at runtime by
15250 // adding in a register or some sort of table lookup. These can't
15251 // be used as immediates.
15252 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15255 // If we are in non-pic codegen mode, we allow the address of a global (with
15256 // an optional displacement) to be used with 'i'.
15257 GlobalAddressSDNode *GA = 0;
15258 int64_t Offset = 0;
15260 // Match either (GA), (GA+C), (GA+C1+C2), etc.
15262 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15263 Offset += GA->getOffset();
15265 } else if (Op.getOpcode() == ISD::ADD) {
15266 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15267 Offset += C->getZExtValue();
15268 Op = Op.getOperand(0);
15271 } else if (Op.getOpcode() == ISD::SUB) {
15272 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15273 Offset += -C->getZExtValue();
15274 Op = Op.getOperand(0);
15279 // Otherwise, this isn't something we can handle, reject it.
15283 const GlobalValue *GV = GA->getGlobal();
15284 // If we require an extra load to get this address, as in PIC mode, we
15285 // can't accept it.
15286 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15287 getTargetMachine())))
15290 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15291 GA->getValueType(0), Offset);
15296 if (Result.getNode()) {
15297 Ops.push_back(Result);
15300 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15303 std::pair<unsigned, const TargetRegisterClass*>
15304 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15306 // First, see if this is a constraint that directly corresponds to an LLVM
15308 if (Constraint.size() == 1) {
15309 // GCC Constraint Letters
15310 switch (Constraint[0]) {
15312 // TODO: Slight differences here in allocation order and leaving
15313 // RIP in the class. Do they matter any more here than they do
15314 // in the normal allocation?
15315 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15316 if (Subtarget->is64Bit()) {
15317 if (VT == MVT::i32 || VT == MVT::f32)
15318 return std::make_pair(0U, X86::GR32RegisterClass);
15319 else if (VT == MVT::i16)
15320 return std::make_pair(0U, X86::GR16RegisterClass);
15321 else if (VT == MVT::i8 || VT == MVT::i1)
15322 return std::make_pair(0U, X86::GR8RegisterClass);
15323 else if (VT == MVT::i64 || VT == MVT::f64)
15324 return std::make_pair(0U, X86::GR64RegisterClass);
15327 // 32-bit fallthrough
15328 case 'Q': // Q_REGS
15329 if (VT == MVT::i32 || VT == MVT::f32)
15330 return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15331 else if (VT == MVT::i16)
15332 return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15333 else if (VT == MVT::i8 || VT == MVT::i1)
15334 return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15335 else if (VT == MVT::i64)
15336 return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15338 case 'r': // GENERAL_REGS
15339 case 'l': // INDEX_REGS
15340 if (VT == MVT::i8 || VT == MVT::i1)
15341 return std::make_pair(0U, X86::GR8RegisterClass);
15342 if (VT == MVT::i16)
15343 return std::make_pair(0U, X86::GR16RegisterClass);
15344 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15345 return std::make_pair(0U, X86::GR32RegisterClass);
15346 return std::make_pair(0U, X86::GR64RegisterClass);
15347 case 'R': // LEGACY_REGS
15348 if (VT == MVT::i8 || VT == MVT::i1)
15349 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15350 if (VT == MVT::i16)
15351 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15352 if (VT == MVT::i32 || !Subtarget->is64Bit())
15353 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15354 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15355 case 'f': // FP Stack registers.
15356 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15357 // value to the correct fpstack register class.
15358 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15359 return std::make_pair(0U, X86::RFP32RegisterClass);
15360 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15361 return std::make_pair(0U, X86::RFP64RegisterClass);
15362 return std::make_pair(0U, X86::RFP80RegisterClass);
15363 case 'y': // MMX_REGS if MMX allowed.
15364 if (!Subtarget->hasMMX()) break;
15365 return std::make_pair(0U, X86::VR64RegisterClass);
15366 case 'Y': // SSE_REGS if SSE2 allowed
15367 if (!Subtarget->hasXMMInt()) break;
15369 case 'x': // SSE_REGS if SSE1 allowed
15370 if (!Subtarget->hasXMM()) break;
15372 switch (VT.getSimpleVT().SimpleTy) {
15374 // Scalar SSE types.
15377 return std::make_pair(0U, X86::FR32RegisterClass);
15380 return std::make_pair(0U, X86::FR64RegisterClass);
15388 return std::make_pair(0U, X86::VR128RegisterClass);
15394 // Use the default implementation in TargetLowering to convert the register
15395 // constraint into a member of a register class.
15396 std::pair<unsigned, const TargetRegisterClass*> Res;
15397 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15399 // Not found as a standard register?
15400 if (Res.second == 0) {
15401 // Map st(0) -> st(7) -> ST0
15402 if (Constraint.size() == 7 && Constraint[0] == '{' &&
15403 tolower(Constraint[1]) == 's' &&
15404 tolower(Constraint[2]) == 't' &&
15405 Constraint[3] == '(' &&
15406 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15407 Constraint[5] == ')' &&
15408 Constraint[6] == '}') {
15410 Res.first = X86::ST0+Constraint[4]-'0';
15411 Res.second = X86::RFP80RegisterClass;
15415 // GCC allows "st(0)" to be called just plain "st".
15416 if (StringRef("{st}").equals_lower(Constraint)) {
15417 Res.first = X86::ST0;
15418 Res.second = X86::RFP80RegisterClass;
15423 if (StringRef("{flags}").equals_lower(Constraint)) {
15424 Res.first = X86::EFLAGS;
15425 Res.second = X86::CCRRegisterClass;
15429 // 'A' means EAX + EDX.
15430 if (Constraint == "A") {
15431 Res.first = X86::EAX;
15432 Res.second = X86::GR32_ADRegisterClass;
15438 // Otherwise, check to see if this is a register class of the wrong value
15439 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15440 // turn into {ax},{dx}.
15441 if (Res.second->hasType(VT))
15442 return Res; // Correct type already, nothing to do.
15444 // All of the single-register GCC register classes map their values onto
15445 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
15446 // really want an 8-bit or 32-bit register, map to the appropriate register
15447 // class and return the appropriate register.
15448 if (Res.second == X86::GR16RegisterClass) {
15449 if (VT == MVT::i8) {
15450 unsigned DestReg = 0;
15451 switch (Res.first) {
15453 case X86::AX: DestReg = X86::AL; break;
15454 case X86::DX: DestReg = X86::DL; break;
15455 case X86::CX: DestReg = X86::CL; break;
15456 case X86::BX: DestReg = X86::BL; break;
15459 Res.first = DestReg;
15460 Res.second = X86::GR8RegisterClass;
15462 } else if (VT == MVT::i32) {
15463 unsigned DestReg = 0;
15464 switch (Res.first) {
15466 case X86::AX: DestReg = X86::EAX; break;
15467 case X86::DX: DestReg = X86::EDX; break;
15468 case X86::CX: DestReg = X86::ECX; break;
15469 case X86::BX: DestReg = X86::EBX; break;
15470 case X86::SI: DestReg = X86::ESI; break;
15471 case X86::DI: DestReg = X86::EDI; break;
15472 case X86::BP: DestReg = X86::EBP; break;
15473 case X86::SP: DestReg = X86::ESP; break;
15476 Res.first = DestReg;
15477 Res.second = X86::GR32RegisterClass;
15479 } else if (VT == MVT::i64) {
15480 unsigned DestReg = 0;
15481 switch (Res.first) {
15483 case X86::AX: DestReg = X86::RAX; break;
15484 case X86::DX: DestReg = X86::RDX; break;
15485 case X86::CX: DestReg = X86::RCX; break;
15486 case X86::BX: DestReg = X86::RBX; break;
15487 case X86::SI: DestReg = X86::RSI; break;
15488 case X86::DI: DestReg = X86::RDI; break;
15489 case X86::BP: DestReg = X86::RBP; break;
15490 case X86::SP: DestReg = X86::RSP; break;
15493 Res.first = DestReg;
15494 Res.second = X86::GR64RegisterClass;
15497 } else if (Res.second == X86::FR32RegisterClass ||
15498 Res.second == X86::FR64RegisterClass ||
15499 Res.second == X86::VR128RegisterClass) {
15500 // Handle references to XMM physical registers that got mapped into the
15501 // wrong class. This can happen with constraints like {xmm0} where the
15502 // target independent register mapper will just pick the first match it can
15503 // find, ignoring the required type.
15504 if (VT == MVT::f32)
15505 Res.second = X86::FR32RegisterClass;
15506 else if (VT == MVT::f64)
15507 Res.second = X86::FR64RegisterClass;
15508 else if (X86::VR128RegisterClass->hasType(VT))
15509 Res.second = X86::VR128RegisterClass;